]> oss.titaniummirror.com Git - tinyos-2.x.git/commitdiff
Initial commit of the Deluge T2. Some notes:
authorrazvanm <razvanm>
Tue, 22 May 2007 20:34:19 +0000 (20:34 +0000)
committerrazvanm <razvanm>
Tue, 22 May 2007 20:34:19 +0000 (20:34 +0000)
- TOSBoot includes some code to allow the MicaZ version to compile but it's not support for it it's not done yet.
- tools/tinyos/misc/Makefile.am is not updated yet so the new tools will not be installed by default.

104 files changed:
apps/tests/deluge/Blink/BlinkAppC.nc [new file with mode: 0644]
apps/tests/deluge/Blink/BlinkC.nc [new file with mode: 0644]
apps/tests/deluge/Blink/Makefile [new file with mode: 0644]
apps/tests/deluge/Blink/burn [new file with mode: 0755]
apps/tests/deluge/Blink/volumes-stm25p.xml [new file with mode: 0644]
apps/tests/deluge/GoldenImage/GoldenImageC.nc [new file with mode: 0644]
apps/tests/deluge/GoldenImage/Makefile [new file with mode: 0644]
apps/tests/deluge/GoldenImage/volumes-stm25p.xml [new file with mode: 0644]
apps/tests/deluge/SerialBlink/BlinkAppC.nc [new file with mode: 0644]
apps/tests/deluge/SerialBlink/BlinkC.nc [new file with mode: 0644]
apps/tests/deluge/SerialBlink/Makefile [new file with mode: 0644]
apps/tests/deluge/SerialBlink/volumes-stm25p.xml [new file with mode: 0644]
doc/html/deluge-t2-manual.css [new file with mode: 0644]
doc/html/deluge-t2-manual.html [new file with mode: 0644]
doc/pdf/deluge-t2-manual.pdf [new file with mode: 0644]
support/make/Makedefaults
support/make/bnp.extra [new file with mode: 0644]
tools/tinyos/misc/tinyos.py [new file with mode: 0644]
tools/tinyos/misc/tos-build-deluge-image [new file with mode: 0755]
tools/tinyos/misc/tos-deluge [new file with mode: 0755]
tos/lib/TOSBoot/Deluge.h [new file with mode: 0644]
tos/lib/TOSBoot/Exec.nc [new file with mode: 0644]
tos/lib/TOSBoot/ExtFlash.nc [new file with mode: 0644]
tos/lib/TOSBoot/Hardware.nc [new file with mode: 0644]
tos/lib/TOSBoot/Leds.nc [new file with mode: 0644]
tos/lib/TOSBoot/Makefile [new file with mode: 0644]
tos/lib/TOSBoot/ProgFlash.nc [new file with mode: 0644]
tos/lib/TOSBoot/TOSBoot.h [new file with mode: 0644]
tos/lib/TOSBoot/TOSBoot.nc [new file with mode: 0644]
tos/lib/TOSBoot/TOSBootM.nc [new file with mode: 0644]
tos/lib/TOSBoot/Voltage.nc [new file with mode: 0644]
tos/lib/TOSBoot/at45db/ExtFlashC.nc [new file with mode: 0644]
tos/lib/TOSBoot/avr/HardwareC.nc [new file with mode: 0644]
tos/lib/TOSBoot/avr/InternalFlashC.nc [new file with mode: 0644]
tos/lib/TOSBoot/avr/ProgFlashM.nc [new file with mode: 0644]
tos/lib/TOSBoot/avr/boot.h [new file with mode: 0644]
tos/lib/TOSBoot/crc.h [new file with mode: 0644]
tos/lib/TOSBoot/lib/ExecC.nc [new file with mode: 0644]
tos/lib/TOSBoot/lib/LedsC.nc [new file with mode: 0644]
tos/lib/TOSBoot/micaz/ExecC.nc [new file with mode: 0644]
tos/lib/TOSBoot/micaz/InternalFlash.h [new file with mode: 0644]
tos/lib/TOSBoot/micaz/PluginC.nc [new file with mode: 0644]
tos/lib/TOSBoot/micaz/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/TOSBoot/micaz/VoltageC.nc [new file with mode: 0644]
tos/lib/TOSBoot/micaz/avrhardware.h [new file with mode: 0644]
tos/lib/TOSBoot/micaz/hardware.h [new file with mode: 0644]
tos/lib/TOSBoot/msp430/HPLUSART0M.nc [new file with mode: 0644]
tos/lib/TOSBoot/msp430/HPLUSARTControl.nc [new file with mode: 0644]
tos/lib/TOSBoot/msp430/HardwareC.nc [new file with mode: 0644]
tos/lib/TOSBoot/msp430/InternalFlashC.nc [new file with mode: 0644]
tos/lib/TOSBoot/msp430/ProgFlashM.nc [new file with mode: 0644]
tos/lib/TOSBoot/msp430/VoltageC.nc [new file with mode: 0644]
tos/lib/TOSBoot/stm25p/ExtFlashC.nc [new file with mode: 0644]
tos/lib/TOSBoot/stm25p/ExtFlashM.nc [new file with mode: 0644]
tos/lib/TOSBoot/telosb/InternalFlash.h [new file with mode: 0644]
tos/lib/TOSBoot/telosb/InternalFlash.nc [new file with mode: 0644]
tos/lib/TOSBoot/telosb/PluginC.nc [new file with mode: 0644]
tos/lib/TOSBoot/telosb/PowerOffM.nc [new file with mode: 0644]
tos/lib/TOSBoot/telosb/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/TOSBoot/telosb/hardware.h [new file with mode: 0644]
tos/lib/net/Deluge/AutoStarterC.nc [new file with mode: 0644]
tos/lib/net/Deluge/AutoStarterP.nc [new file with mode: 0644]
tos/lib/net/Deluge/BitVecUtils.h [new file with mode: 0644]
tos/lib/net/Deluge/BitVecUtils.nc [new file with mode: 0644]
tos/lib/net/Deluge/BitVecUtilsC.nc [new file with mode: 0644]
tos/lib/net/Deluge/Crc.nc [new file with mode: 0644]
tos/lib/net/Deluge/CrcP.nc [new file with mode: 0644]
tos/lib/net/Deluge/Deluge.h [new file with mode: 0644]
tos/lib/net/Deluge/DelugeC.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugeMetadata.h [new file with mode: 0644]
tos/lib/net/Deluge/DelugeMetadata.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugeMsgs.h [new file with mode: 0644]
tos/lib/net/Deluge/DelugeP.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugePageTransfer.h [new file with mode: 0644]
tos/lib/net/Deluge/DelugePageTransfer.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugePageTransferC.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugePageTransferP.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugeStorageC.nc [new file with mode: 0644]
tos/lib/net/Deluge/DelugeStorageP.nc [new file with mode: 0644]
tos/lib/net/Deluge/FakeBlockReaderC.nc [new file with mode: 0644]
tos/lib/net/Deluge/FakeBlockWriterC.nc [new file with mode: 0644]
tos/lib/net/Deluge/FakeBlockWriterP.nc [new file with mode: 0644]
tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManager.h [new file with mode: 0644]
tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerC.nc [new file with mode: 0644]
tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerP.nc [new file with mode: 0644]
tos/lib/net/Deluge/Globals.nc [new file with mode: 0644]
tos/lib/net/Deluge/GlobalsC.nc [new file with mode: 0644]
tos/lib/net/Deluge/ObjectTransfer.nc [new file with mode: 0644]
tos/lib/net/Deluge/ObjectTransferC.nc [new file with mode: 0644]
tos/lib/net/Deluge/ObjectTransferP.nc [new file with mode: 0644]
tos/lib/net/Deluge/SerialStarterC.nc [new file with mode: 0644]
tos/lib/net/Deluge/StatsCollector.nc [new file with mode: 0644]
tos/lib/net/Deluge/StatsCollectorC.nc [new file with mode: 0644]
tos/lib/net/Deluge/StatsCollectorP.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/NetProg.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/NetProg.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/NetProgC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/NetProgM.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/TOSBoot.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/msp430/InternalFlashC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/telos/NetProg_platform.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/telosb/InternalFlash.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/telosb/InternalFlash.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/telosb/TOSBoot_platform.h [new file with mode: 0644]

diff --git a/apps/tests/deluge/Blink/BlinkAppC.nc b/apps/tests/deluge/Blink/BlinkAppC.nc
new file mode 100644 (file)
index 0000000..dae60f6
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * "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.
+ */
+
+/**
+ * Blink is a basic application that toggles the a mote LED periodically.
+ * It does so by starting a Timer that fires every second. It uses the
+ * OSKI TimerMilli service to achieve this goal.
+ *
+ * @author tinyos-help@millennium.berkeley.edu
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ **/
+
+configuration BlinkAppC
+{
+}
+implementation
+{
+  components MainC, BlinkC, LedsC, DelugeC;
+  components new TimerMilliC() as Timer0;
+
+  BlinkC -> MainC.Boot;
+
+  BlinkC.Timer0 -> Timer0;
+  BlinkC.Leds -> LedsC;
+}
+
diff --git a/apps/tests/deluge/Blink/BlinkC.nc b/apps/tests/deluge/Blink/BlinkC.nc
new file mode 100644 (file)
index 0000000..d51432c
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * "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.
+ */
+
+/**
+ * Implementation for Blink application.  Toggle the red LED when a
+ * Timer fires.
+ *
+ * @author tinyos-help@millennium.berkeley.edu
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ **/
+
+#include "Timer.h"
+
+module BlinkC
+{
+  uses interface Timer<TMilli> as Timer0;
+  uses interface Leds;
+  uses interface Boot;
+}
+
+implementation
+{
+  event void Boot.booted()
+  {
+    call Timer0.startPeriodic( 500 );
+  }
+
+  event void Timer0.fired()
+  {
+    dbg("BlinkC", "Timer 0 fired @ %s.\n", sim_time_string());
+#ifndef BLINK_REVERSE
+    call Leds.led1Toggle();
+#else
+    call Leds.led2Toggle();
+#endif
+  }
+}
+
diff --git a/apps/tests/deluge/Blink/Makefile b/apps/tests/deluge/Blink/Makefile
new file mode 100644 (file)
index 0000000..ee6423d
--- /dev/null
@@ -0,0 +1,7 @@
+COMPONENT=BlinkAppC
+TINYOS_NP=BNP
+
+CFLAGS += -DTOSH_DATA_LENGTH=100
+CFLAGS += -DDELUGE_BASESTATION
+
+include $(MAKERULES)
diff --git a/apps/tests/deluge/Blink/burn b/apps/tests/deluge/Blink/burn
new file mode 100755 (executable)
index 0000000..8bb82a3
--- /dev/null
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+if [ $# -ne 1 ]; then
+  echo "Usage: $0 /dev/ttyUSB0"
+  exit 2
+fi
+
+PORT=$1
+make clean
+
+echo ==================== Compile and load Blink ====================
+make telosb install bsl,$PORT
+
+echo ==================== Compile a new Blink ====================
+CFLAGS=-DBLINK_REVERSE make telosb 
+
+echo ==================== Upload the image ====================
+../../../../tools/tinyos/misc/tos-deluge $PORT -i 0 build/telosb/tos_image.xml
+
+echo ==================== Reboot ====================
+../../../../tools/tinyos/misc/tos-deluge $PORT -r 0 
diff --git a/apps/tests/deluge/Blink/volumes-stm25p.xml b/apps/tests/deluge/Blink/volumes-stm25p.xml
new file mode 100644 (file)
index 0000000..afc864a
--- /dev/null
@@ -0,0 +1,4 @@
+<volume_table>
+  <volume name="DELUGE0" size="65536"/>
+  <volume name="DELUGE1" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/apps/tests/deluge/GoldenImage/GoldenImageC.nc b/apps/tests/deluge/GoldenImage/GoldenImageC.nc
new file mode 100644 (file)
index 0000000..d99c2c9
--- /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 GoldenImageC {}
+
+implementation
+{
+  components DelugeC;
+}
+
diff --git a/apps/tests/deluge/GoldenImage/Makefile b/apps/tests/deluge/GoldenImage/Makefile
new file mode 100644 (file)
index 0000000..35393d2
--- /dev/null
@@ -0,0 +1,7 @@
+COMPONENT=GoldenImageC
+TINYOS_NP=BNP
+
+CFLAGS += -DTOSH_DATA_LENGTH=100
+CFLAGS += -DDELUGE_BASESTATION
+
+include $(MAKERULES)
diff --git a/apps/tests/deluge/GoldenImage/volumes-stm25p.xml b/apps/tests/deluge/GoldenImage/volumes-stm25p.xml
new file mode 100644 (file)
index 0000000..afc864a
--- /dev/null
@@ -0,0 +1,4 @@
+<volume_table>
+  <volume name="DELUGE0" size="65536"/>
+  <volume name="DELUGE1" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/apps/tests/deluge/SerialBlink/BlinkAppC.nc b/apps/tests/deluge/SerialBlink/BlinkAppC.nc
new file mode 100644 (file)
index 0000000..c3a9731
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * "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.
+ */
+
+/**
+ * Blink is a basic application that toggles the a mote LED periodically.
+ * It does so by starting a Timer that fires every second. It uses the
+ * OSKI TimerMilli service to achieve this goal.
+ *
+ * @author tinyos-help@millennium.berkeley.edu
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ **/
+
+configuration BlinkAppC
+{
+}
+implementation
+{
+  components MainC, BlinkC, LedsC, DelugeC;
+  components new TimerMilliC() as Timer0;
+  components new SerialAMSenderC(0);
+
+  BlinkC -> MainC.Boot;
+
+  BlinkC.Timer0 -> Timer0;
+  BlinkC.Leds -> LedsC;
+  BlinkC.AMSend -> SerialAMSenderC;
+}
diff --git a/apps/tests/deluge/SerialBlink/BlinkC.nc b/apps/tests/deluge/SerialBlink/BlinkC.nc
new file mode 100644 (file)
index 0000000..ef32ef4
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * "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.
+ */
+
+/**
+ * Implementation for Blink application.  Toggle the red LED when a
+ * Timer fires.
+ *
+ * @author tinyos-help@millennium.berkeley.edu
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ **/
+
+#include "Timer.h"
+
+module BlinkC
+{
+  uses interface Timer<TMilli> as Timer0;
+  uses interface Leds;
+  uses interface Boot;
+  uses interface AMSend;
+}
+
+implementation
+{
+  message_t byte_msg;
+  
+  event void Boot.booted()
+  {
+    call Timer0.startPeriodic( 1024 );
+  }
+
+  event void Timer0.fired()
+  {
+    char *payload = call AMSend.getPayload(&byte_msg);
+    dbg("BlinkC", "Timer 0 fired @ %s.\n", sim_time_string());
+#ifndef BLINK_REVERSE
+    call Leds.led1Toggle();
+    payload[0] = 1;
+#else
+    call Leds.led2Toggle();
+    payload[0] = 2;
+#endif
+    call AMSend.send(AM_BROADCAST_ADDR, &byte_msg, 1);
+  }
+
+  event void AMSend.sendDone(message_t* msg, error_t error) { };
+}
+
diff --git a/apps/tests/deluge/SerialBlink/Makefile b/apps/tests/deluge/SerialBlink/Makefile
new file mode 100644 (file)
index 0000000..ee6423d
--- /dev/null
@@ -0,0 +1,7 @@
+COMPONENT=BlinkAppC
+TINYOS_NP=BNP
+
+CFLAGS += -DTOSH_DATA_LENGTH=100
+CFLAGS += -DDELUGE_BASESTATION
+
+include $(MAKERULES)
diff --git a/apps/tests/deluge/SerialBlink/volumes-stm25p.xml b/apps/tests/deluge/SerialBlink/volumes-stm25p.xml
new file mode 100644 (file)
index 0000000..afc864a
--- /dev/null
@@ -0,0 +1,4 @@
+<volume_table>
+  <volume name="DELUGE0" size="65536"/>
+  <volume name="DELUGE1" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/doc/html/deluge-t2-manual.css b/doc/html/deluge-t2-manual.css
new file mode 100644 (file)
index 0000000..02a6f88
--- /dev/null
@@ -0,0 +1,193 @@
+
+               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;
+               }
+
+               .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;
+               }
+
+               /*
+               .verbatim {
+               color: #4d0000;
+               }
+               */
+
+               tt i {
+               font-family: serif;
+               }
+
+               .verbatim em {
+               font-family: serif;
+               }
+
+               .scheme em {
+               font-family: serif;
+               color: black;
+               }
+
+               .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%;
+               text-align: right;
+               }
+
+               .colophon a {
+               color: gray;
+               }
+
+               
\ No newline at end of file
diff --git a/doc/html/deluge-t2-manual.html b/doc/html/deluge-t2-manual.html
new file mode 100644 (file)
index 0000000..a807c8b
--- /dev/null
@@ -0,0 +1,256 @@
+<!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>
+<p>
+
+</p>
+<p>
+</p>
+<p>
+
+
+
+</p>
+<h1 class=title align=center><br><br>Deluge T2 - Programming Manual</h1>
+<p></p>
+<div align=center>
+Chieh-Jan Mike Liang<br>
+Razvan Musaloiu-E.<p>May 18, 2007</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. 
+Since the code from Deluge 2.0 is reused as much as possible, the 
+behavior and the usage of Deluge T2 should be similar to Deluge 2.0. 
+Having said that, it would 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 and tested on tmote sky 
+(<i>telosb</i>) only. In addition, Deluge T2 comes with 2 flash volumes by 
+default. However, more volumes can be added, if necessary. There are 
+also minor details that will be improved in future releases.</p>
+<p>
+</p>
+<a name="node_sec_2"></a>
+<h1>2&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 run a <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
+</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/</code>. For example,
+</p>
+<pre class=verbatim>   % tos-deluge.py /dev/ttyUSB0 -p 0
+</pre><p>
+You should see something similar to the output below.</p>
+<p>
+</p>
+<pre class=verbatim>   Pinging node ...
+   Connected to Deluge node.
+   --------------------------------------------------
+   Stored image 0
+     Prog Name:   BlinkAppC     
+     Compiled On: Thu May 17 00:36:33 2007
+     Platform:    telosb          
+     User ID:     mike          
+     Host Name:   sprite        
+     User Hash:   0xC50D8DA4L
+     Num Pages:   24/24
+   
+     Size:        26512
+     UID:         2302157803
+     Version:     6
+   --------------------------------------------------
+</pre><p></p>
+<p>
+The usage of <code class=verbatim>delugy.py</code> is available by running the script without 
+any arguments, and it will be discussed in section <a href="#node_sec_4">4</a>.</p>
+<p>
+</p>
+<a name="node_sec_3"></a>
+<h1>3&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_3.1"></a>
+<h2>3.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>   % make telosb install,0 bsl,/dev/ttyUSB0
+</pre><p>
+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>deluge.py</code>.</p>
+<p>
+</p>
+<a name="node_sec_3.2"></a>
+<h2>3.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 Make file. You need to make sure <code class=verbatim>DelugeC</code>
+component is included. In addition, the Make file should have the
+following lines:
+</p>
+<pre class=verbatim>   TINYOS_NP=BNP
+   CFLAGS += -DTOSH_DATA_LENGTH=100
+</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_3.3"></a>
+<h2>3.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.py /dev/ttyUSB0 -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.
+   --------------------------------------------------
+   Stored image 1
+     No proper Deluge image found!
+   --------------------------------------------------
+   Ihex read complete:
+     Total bytes = 25526
+     Sections = 2
+   --------------------------------------------------
+   Replace image with:
+     Prog Name:   BlinkAppC     
+     Compiled On: Mon May 07 00:01:43 2007
+     Platform:    telosb          
+     User ID:     mike          
+     Host Name:   sprite        
+     User Hash:   0xC50D8DA4L
+     Num Pages:   24/24
+   
+     Size:        26512
+     UID:         507153792
+     Version:     0
+   --------------------------------------------------
+</pre><p></p>
+<p>
+</p>
+<a name="node_sec_3.4"></a>
+<h2>3.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.py /dev/ttyUSB0 -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.py /dev/ttyUSB0 -d 1
+</pre><p>
+This command instructs the base station to notify the whole network of 
+the availablility 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. Upon receiving the complete image 
+over-the-air, each node automatically reboots and reprograms itself.</p>
+<p>
+</p>
+<a name="node_sec_4"></a>
+<h1>4&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 very 
+similar.</p>
+<p>
+</p>
+<a name="node_sec_4.1"></a>
+<h2>4.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_4.2"></a>
+<h2>4.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. All versioning information is kept on the mote, so 
+no state is stored on the PC.</p>
+<p>
+</p>
+<a name="node_sec_4.3"></a>
+<h2>4.3&nbsp;&nbsp;-r -reboot</h2>
+<p>This command sets up the mote to reprogram itself after reboot, and then 
+it reboots the mote. This command is applicable only to the directly 
+connected mote.</p>
+<p>
+</p>
+<a name="node_sec_4.4"></a>
+<h2>4.4&nbsp;&nbsp;-d -dissemination</h2>
+<p>This command instructs the directly connected mote to disseminate an 
+image to the network. This image is specified by the volume ID. Upon 
+successfully receiving an image, motes in the network automatically 
+reprogram themselves.</p>
+<p>
+</p>
+<a name="node_sec_4.5"></a>
+<h2>4.5&nbsp;&nbsp;-e -erase</h2>
+<p>This command erases a flash volume on the directly connected mote.</p>
+<p>
+</p>
+<a name="node_sec_4.6"></a>
+<h2>4.6&nbsp;&nbsp;-s -reset</h2>
+<p>This command resets versioning information of a specific image on the 
+directly connected mote.</p>
+<p>
+</p>
+<div align=right class=colophon>
+<i>Last modified: Friday, May 18th, 2007<br>
+HTML conversion by <a href="http://www.ccs.neu.edu/~dorai/tex2page/tex2page-doc.html">TeX2page 2004-09-11</a></i>
+</div>
+</body>
+</html>
diff --git a/doc/pdf/deluge-t2-manual.pdf b/doc/pdf/deluge-t2-manual.pdf
new file mode 100644 (file)
index 0000000..d326295
Binary files /dev/null and b/doc/pdf/deluge-t2-manual.pdf differ
index de4f4d07c569c417709b52a2869cee8410844d1e..ebaf830806ebb68af125b8facddd7b68d7f59827 100644 (file)
@@ -4,7 +4,7 @@
 DEFAULT_LOCAL_GROUP ?= 0x7d
 OPTFLAGS ?= -Os
 NESC_FLAGS ?= -Wnesc-all
-GOALS += ident_flags tos_image
+GOALS += ident_flags tos_image bnp
 
 define DEFAULT_HELP
 
diff --git a/support/make/bnp.extra b/support/make/bnp.extra
new file mode 100644 (file)
index 0000000..bf0cdbb
--- /dev/null
@@ -0,0 +1,24 @@
+#-*-Makefile-*- vim:syntax=make
+#$Id$
+
+DELUGE_DIR ?= $(TOSDIR)/lib/net/Deluge
+DELUGE_EXTRA ?= $(DELUGE_DIR)/extra
+TOSBOOT_DIR ?= $(TOSDIR)/lib/TOSBoot/build
+
+ifeq ($(TINYOS_NP),BNP)
+
+  CFLAGS += -DDELUGE
+  CFLAGS += -I$(TOSDIR)/lib/net -I$(DELUGE_DIR) -I$(DELUGE_DIR)/FlashVolumeManager
+
+  ifneq ($(filter telosb tmote,$(TARGETS)),)
+    CFLAGS += -I$(DELUGE_EXTRA) -I$(DELUGE_EXTRA)/msp430 -I$(DELUGE_EXTRA)/telos -I$(DELUGE_EXTRA)/telosb
+    ifeq ($(filter docs,$(GOALS)),)
+      CFLAGS += -Wl,--section-start=.text=0x4a00,--defsym=_reset_vector__=0x4000
+    endif
+    BOOTLOADER ?= $(TOSBOOT_DIR)/telosb/main.ihex
+    ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
+      BOOTLOADER := $(shell cygpath -m $(BOOTLOADER))
+    endif
+  endif
+
+endif
diff --git a/tools/tinyos/misc/tinyos.py b/tools/tinyos/misc/tinyos.py
new file mode 100644 (file)
index 0000000..22c9c94
--- /dev/null
@@ -0,0 +1,285 @@
+import struct, time, serial, socket
+
+# 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>
+
+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 = False   # Debug mode
+    
+    def __init__(self, port, baudrate):
+       self.__s = serial.Serial(port, baudrate, rtscts=0, timeout=0.5)
+    
+    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):
+        try:
+            r = struct.unpack("B", self.__s.read())[0]
+            return r
+        except struct.error:
+            # Serial port read timeout
+            raise socket.timeout
+    
+    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
+    
+    # Returns the next incoming serial packet
+    def sniff_packet(self):
+        try:
+            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 self.__debug == True:
+                if crc != packet_crc:
+                    print "Warning: wrong CRC!"
+                print "Recv:", self.__format_packet(un_packet)
+            return (ts, un_packet)
+        except socket.timeout:
+            return None
+    
+    # Filters and returns the next incoming serial packet with 
+    # specified AM group ID and AM ID
+    def read_packet(self, am_group, am_id):
+        packet = None
+        
+        while True:
+            packet = self.sniff_packet()
+            if not packet == None and len(packet[1]) >= 10:
+                if (packet[1])[8] == am_group and (packet[1])[9] == am_id:
+                    break
+            
+        return packet
+    
+    # Sends data with the specified AM group ID and AM ID. To have a "reliable"
+    # transfer, num_tries defines how many times to retry before giving up
+    def write_packet(self, am_group, am_id, data, num_tries=10):
+        for i in range(num_tries):
+            # 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]
+            
+            self.__put_bytes(packet)
+            if self.__debug == True:
+                print "Send:", self.__format_packet(packet)
+            
+            # Waits for ACK
+            for j in range(3):
+                while True:
+                    packet = self.sniff_packet()
+                    if packet == None:
+                        break
+                    elif (packet[1])[1] == self.SERIAL_PROTO_ACK:
+                        return True
+                        
+            # Debug messages
+            if self.__debug == True:
+                if i == (num_tries - 1):
+                    print "Failed to send the packet!" 
+                else:
+                    print "Timeout waiting for ACK... Retry"
+                        
+        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/tools/tinyos/misc/tos-build-deluge-image b/tools/tinyos/misc/tos-build-deluge-image
new file mode 100755 (executable)
index 0000000..c6af448
--- /dev/null
@@ -0,0 +1,188 @@
+#!/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 Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+# @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+
+import sys, struct, operator
+from xml.dom.minidom import parse
+
+DELUGE_PKTS_PER_PAGE = 48
+DELUGE_PKT_PAYLOAD_SIZE = 23
+DELUGE_BYTES_PER_PAGE = DELUGE_PKTS_PER_PAGE * DELUGE_PKT_PAYLOAD_SIZE
+DELUGE_MAX_PAGES = 128
+
+DELUGE_METADATA_SIZE = 16
+DELUGE_IDENT_SIZE = 128
+
+def sencode(s, dim):
+  s = [ord(c) for c in s]
+  if len(s) > dim:
+    return s[:dim]
+  return s + [0] * (dim - len(s))
+
+def encode(val, dim):
+  output = []
+  for i in range(dim):
+      output.append(val & 0xFF)
+      val = val >> 8
+  return output
+
+def decode(v):
+  r = long(0)
+  for i in v[::-1]:
+      r = (r << 8) + i
+  return r
+
+def int2byte(v):
+    return "".join([struct.pack("B", i) for i in v])
+
+def crc16(data):
+  crc = 0
+  for b in 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 pages(data):
+    return (len(data) / DELUGE_BYTES_PER_PAGE) + \
+               (len(data) % DELUGE_BYTES_PER_PAGE != 0)
+
+def align(data):
+  mod = len(data) % DELUGE_BYTES_PER_PAGE
+  if mod == 0:
+    return data
+  return data + [0] * (DELUGE_BYTES_PER_PAGE - mod)
+
+def deluge_metadata(data, img_num):
+  uid = ident['uid_hash']
+  num_pages = pages(data)
+  image_number = img_num
+  crc = crc16([image_number] + [num_pages])
+  completed_pages = num_pages
+  return encode(uid, 4) + \
+         encode(version, 2) + \
+         [image_number] + \
+         [num_pages] + \
+         encode(crc, 2) + \
+         [completed_pages] + \
+         [0] + \
+         encode(len(data) + 16, 2) + \
+         ([0] * 2)
+
+def deluge_ident():
+  tmp = sencode(ident['program_name'], 16) + \
+        sencode(ident['user_id'], 16) + \
+        sencode(ident['hostname'], 16) + \
+        sencode(ident['platform'], 16) + \
+        encode(ident['size'], 4) + \
+        encode(ident['unix_time'], 4) + \
+        encode(ident['user_hash'], 4) + \
+        encode(ident['uid_hash'], 4)
+  return tmp + [0] * (DELUGE_IDENT_SIZE - len(tmp))
+
+def deluge_crc(data):
+  crc = [0] * DELUGE_MAX_PAGES
+  crc[0] = crc16(data[2*DELUGE_MAX_PAGES:DELUGE_BYTES_PER_PAGE])
+  #sys.stderr.write("crc[0] = 0x%x\n" % (crc[0]))
+  j = 1
+  for i in range(DELUGE_BYTES_PER_PAGE, len(data)-1, DELUGE_BYTES_PER_PAGE):
+    crc[j] = crc16(data[i:i+DELUGE_BYTES_PER_PAGE])
+    #sys.stderr.write("crc[%d] = 0x%x\n" % (j, crc[j]))
+    j += 1
+  return reduce(operator.add, [encode(i, 2) for i in crc]) + data[2*DELUGE_MAX_PAGES:]
+
+version = 0
+
+for i in range(len(sys.argv)):
+  if sys.argv[i] == '-v':
+    version = int(sys.argv[i+1])
+  elif sys.argv[i] == '-i':
+    img_num = int(sys.argv[i+1])
+    
+dom = parse(sys.argv[-1])
+ident = {}
+ident_list = [(n.localName, n.firstChild.nodeValue)
+              for n in dom.getElementsByTagName('ident')[0].childNodes if n.localName != None]
+for (k, v) in ident_list:
+  ident[k] = v
+for p in ['unix_time', 'user_hash', 'uid_hash']:
+  ident[p] = int(ident[p][:-1], 16)
+image = dom.getElementsByTagName('image')[0].firstChild.nodeValue
+
+all = []
+section = []
+end_addr = None
+for line in image.split():
+    #print "DEBUG:", line
+    length = int(line[1:3], 16)
+    addr = int(line[3:7], 16)
+    rectype = int(line[7:9], 16)
+    data = []
+    if len(line) > 11:
+        data = [int(line[i:i+2], 16) for i in range(9, len(line)-2, 2)]
+    crc = int(line[-2:], 16)
+    if rectype in [0x00, 0x03]:
+        if not end_addr:
+            end_addr = addr
+            start_addr = addr
+        if end_addr != addr:
+            all.append((start_addr, section))
+            if rectype == 0x03:
+                # This last record updates the first 4 bytes which
+                # holds some some low level configuration. They are
+                # the same all the time so I guess that's why they are
+                # skipped.
+                break
+            section = []
+            start_addr = addr
+        section += data
+        end_addr = addr + length
+    elif rectype == 0x01:
+        all.append((start_addr, section))
+        section = []
+        start_addr = addr
+
+sys.stderr.write('Ihex read complete:\n')
+sys.stderr.write('  Total bytes = %d\n' % reduce(operator.add, [len(l) for (_, l) in all]))
+sys.stderr.write('  Sections = %d\n' % len(all))
+
+# Usually, there are two sections: one for the code and one for the
+# interrupt vector.
+
+all_data = []
+for (addr, data) in all:
+  all_data += encode(addr, 4) + \
+              encode(len(data), 4) + \
+              data
+ident['size'] = len(all_data)
+all_data = deluge_ident() + all_data
+all_data = align([0] * 2 * DELUGE_MAX_PAGES + all_data)
+all_data = deluge_crc(all_data)
+sys.stdout.write(int2byte(deluge_metadata(all_data, img_num)) + \
+      int2byte(all_data))
+
diff --git a/tools/tinyos/misc/tos-deluge b/tools/tinyos/misc/tos-deluge
new file mode 100755 (executable)
index 0000000..ec12aad
--- /dev/null
@@ -0,0 +1,399 @@
+#!/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 Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+# @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+
+###############################################################################
+# Deluge Python Toolchain
+#
+# A command line utility to interact with nodes via a direct serial connection.
+# For the usage menu, please run this tool without any arguments. For example, 
+# "./tos-deluge.py"
+###############################################################################
+
+import sys, os, stat, struct, subprocess
+import tinyos
+from datetime import datetime
+import os.path 
+
+# Script-specific parameters
+HEX_OUTPUT_LINE_SIZE = 16
+# Path to the python script that builds Deluge image from XML
+PY_PATH_BUILD_IMAGE  = os.path.join(os.path.dirname(sys.argv[0]), 'tos-build-deluge-image')
+
+# TinyOS serial communication parameters
+SERIAL_AMGROUP           = 0
+SERIAL_AMID              = 0xAB
+SERIAL_DATA_PAYLOAD_SIZE = 80
+
+# Serial message types
+MSG_ERASE    = 0
+MSG_WRITE    = 1
+MSG_READ     = 2
+MSG_REPROG   = 5
+MSG_DISS     = 6
+
+ERROR_SUCCESS = 0
+ERROR_FAIL    = 1
+
+# Deluge-specific parameters
+DELUGE_PKTS_PER_PAGE    = 48
+DELUGE_PKT_PAYLOAD_SIZE = 23
+DELUGE_MAX_PAGES        = 128
+DELUGE_METADATA_SIZE    = 16 + 16 + 16 + 16 + 4 + 4 + 4 + 4   # Metadata size in binary 
+                                                              # image
+
+class SerialReqPacket(tinyos.GenericPacket):
+    def __init__(self, packet = None):
+        tinyos.GenericPacket.__init__(self,
+                                      [('msg_type', 'int',  1),
+                                       ('img_num',  '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),
+                                      ('data',  'blob', None)],
+                                     packet)
+
+# Displays an integer representation of byte stream to hex representation
+def print_hex(start_addr, byte_stream):
+    num_iterations = int( (len(byte_stream) - 1) / HEX_OUTPUT_LINE_SIZE ) + 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 += "%02x" % byte_stream[i * HEX_OUTPUT_LINE_SIZE + j] + " "
+    print line
+    
+    start_addr += HEX_OUTPUT_LINE_SIZE
+
+# Computes 16-bit CRC
+def crc16(data):
+    crc = 0
+    for b in 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
+
+# Converts a byte-stream array to int representation
+def toInt(byte_stream):
+    r = long(0)
+    for i in byte_stream[::-1]:
+        r = (r << 8) + i
+    
+    return r
+
+# Converts a byte-stream array to string representation
+def toString(byte_stream):
+    r = ""
+    for i in range(len(byte_stream)):
+        if byte_stream[i] == 0:
+            r += " "
+        else:
+            r += struct.pack("B", byte_stream[i])
+    
+    return r
+
+# Converts a byte-stream array to image status string representation
+def toStatusStr(num_space, binary_stream):
+    r = "%sProg Name:   %s\n" % (" " * num_space, 
+                                 toString(binary_stream[16:32]))
+    r += "%sCompiled On: %s\n" % (" " * num_space, 
+                                  datetime.fromtimestamp(toInt(binary_stream[84:88])).strftime('%a %h %d %T %Y'))
+    r += "%sPlatform:    %s\n" % (" " * num_space, 
+                                  toString(binary_stream[64:80]))
+    r += "%sUser ID:     %s\n" % (" " * num_space, 
+                                  toString(binary_stream[32:48]))
+    r += "%sHost Name:   %s\n" % (" " * num_space, 
+                                  toString(binary_stream[48:64]))
+    r += "%sUser Hash:   %s\n" % (" " * num_space, 
+                                  hex(toInt(binary_stream[88:92])))
+    r += "%sNum Pages:   %d/%d" % (" " * num_space, 
+                                   toInt(binary_stream[7:8]), 
+                                   toInt(binary_stream[10:11]))
+    
+    r += "\n\n"
+    r += "%sSize:        %d\n" % (" " * num_space, 
+                                   toInt(binary_stream[12:14]))
+    r += "%sUID:         %d\n" % (" " * num_space, 
+                                   toInt(binary_stream[0:4]))
+    r += "%sVersion:     %d" % (" " * num_space, 
+                                   toInt(binary_stream[4:6]))
+    
+    return r
+
+# Returns the metadata (first 16 bytes of the image) plus the "ident" 
+# (DELUGE_METADATA_SIZE bytes after CRC)
+def getMetaData(s, img_num):
+    r = []
+    # Gets the metadata (first 16 bytes of the image)
+    sreqpkt = SerialReqPacket((MSG_READ, img_num, 0, 16, []))
+  
+    if s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload()):
+        packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+        sreplypkt = SerialReplyPacket(packet[1])
+        if sreplypkt.error == ERROR_SUCCESS:
+            r.extend(sreplypkt.data)
+      
+            # Gets the "ident" portion of the image
+            sreqpkt["offset"] = 16 + (2 * DELUGE_MAX_PAGES)
+            sreqpkt["len"] = DELUGE_METADATA_SIZE
+            if s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload()):
+                packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+                sreplypkt = SerialReplyPacket(packet[1])
+                if sreplypkt.error == ERROR_SUCCESS:
+                    r.extend(sreplypkt.data)
+                    
+                    # Checks for valid CRC and timestamp
+                    if crc16(r[6:8]) == toInt(r[8:10]) and r[84:88] != [0xFF, 0xFF, 0xFF, 0xFF]:
+                        return r
+                else:
+                    print "ERROR: Unable to retrieve image information"
+        else:
+            print "ERROR: Unable to retrieve image information"
+
+    return None
+
+# Prints status of the image in the external flash
+def op_ping(s, img_num):
+    metadata = getMetaData(s, img_num)
+    if not metadata == None:
+        print "Connected to Deluge node."
+        # Prints out image status
+        print "--------------------------------------------------"
+        print "Stored image %d" % img_num
+        print toStatusStr(2, metadata)
+        print "--------------------------------------------------"
+        return True
+        
+    print "No proper Deluge image found!"
+    return False
+
+# Erases an image volume
+def op_erase(s, img_num):
+    sreqpkt = SerialReqPacket((MSG_ERASE, img_num, 0, 0, []))
+    success = s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload())
+    if success == True:
+        packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+        sreplypkt = SerialReplyPacket(packet[1])
+        if sreplypkt.error == ERROR_SUCCESS:
+            return True
+        else:
+            print "ERROR: Unable to erase the flash volume"
+            return False
+        
+    print "ERROR: Unable to send the command"
+    return False
+
+# Writes to an image volume
+def op_write(s, img_num, binary_stream):
+    sreqpkt = SerialReqPacket((MSG_WRITE, img_num, 0, 0, []))
+    local_crc = 0   # Running CRC
+    length = len(binary_stream)
+    
+    sreqpkt.offset = 0
+    while length > 0:
+        # Calculates the payload size for the current packet
+        if length >= SERIAL_DATA_PAYLOAD_SIZE:
+            sreqpkt.len = SERIAL_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", binary_stream[sreqpkt.offset + i])[0])
+        
+        # Sends over serial to the mote
+        if s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload()) == False:
+            print "ERROR: Unable to send the last serial packet (file offset: %d)" % sreqpkt.offset
+            return False
+        
+        # Waiting for confirmation
+        packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+        sreplypkt = SerialReplyPacket(packet[1])
+        if sreplypkt.error != ERROR_SUCCESS:
+            print "ERROR: Unable to write to the flash volume (file offset: %d)" % sreqpkt.offset
+            return False
+            
+        local_crc = s.crc16(local_crc, sreqpkt.data)   # Computes running CRC
+        length -= sreqpkt.len
+        sreqpkt.offset += sreqpkt.len
+        
+    return True
+
+# Injects an image (specified by tos_image_xml) to an image volume
+def op_inject(s, img_num, tos_image_xml):
+    # Gets status information of stored image
+    metadata = getMetaData(s, img_num)
+    print "Connected to Deluge nodes."
+    print "--------------------------------------------------"
+    print "Stored image %d" % img_num
+    version = 0
+    if not metadata == None:
+        version = toInt(metadata[4:6]) + 1   # Increments the version
+        print toStatusStr(2, metadata)
+    else:
+        print "  No proper Deluge image found!"
+    print "--------------------------------------------------"
+    
+    # Creates binary image from the TOS image XML
+    try:
+        os.stat(tos_image_xml)         # Checks whether tos_image_xml is a valid file
+        os.stat(PY_PATH_BUILD_IMAGE)   # Checks whether PY_PATH_BUILD_IMAGE is a valid file
+    except:
+        print "ERROR: Unable to create a binary image from the TOS image XML, \"%s\"" % tos_image_xml
+        return False
+    p = subprocess.Popen([PY_PATH_BUILD_IMAGE, "-v", str(version), "-i", str(img_num), tos_image_xml], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    print p.stderr.read(),
+    print "--------------------------------------------------"
+    
+    # Writes the new binary image
+    if op_erase(s, img_num):
+        if op_write(s, img_num, p.stdout.read()):
+            metadata = getMetaData(s, img_num)
+            if not metadata == None:       
+                print "Replace image with:"
+                print toStatusStr(2, metadata)
+                print "--------------------------------------------------"
+        
+                return True
+    
+    return False
+
+# Requests the mote to reboot and reprogram itself
+def op_reprog(s, img_num):
+    if getMetaData(s, img_num) == None:
+        print "ERROR: No proper Deluge image found!"
+    else:
+        sreqpkt = SerialReqPacket((MSG_REPROG, img_num, 0, 0, []))
+        success = s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload())
+        if success == True:
+            packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+            sreplypkt = SerialReplyPacket(packet[1])
+            if sreplypkt.error == ERROR_SUCCESS:
+                return True
+            else:
+                print "ERROR: Unable to reboot the mote"
+                return False
+            
+        print "ERROR: Unable to send the command"
+    return False
+
+# Requests the mote to disseminate an image
+def op_diss(s, img_num):
+    if getMetaData(s, img_num) == None:
+        print "ERROR: No proper Deluge image found!"
+    else:
+        sreqpkt = SerialReqPacket((MSG_DISS, img_num, 0, 0, []))
+        success = s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload())
+        if success == True:
+            packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+            sreplypkt = SerialReplyPacket(packet[1])
+            if sreplypkt.error == ERROR_SUCCESS:
+                return True
+            else:
+                print "ERROR: Unable to start the command dissemination"
+                return False
+            
+        print "ERROR: Unable to send the command"
+    return False
+      
+# Resets image versioning information
+def op_reset(s, img_num):
+    sreqpkt = SerialReqPacket((MSG_WRITE, img_num, 4, 2, [0, 0]))
+    if s.write_packet(SERIAL_AMGROUP, SERIAL_AMID, sreqpkt.payload()) == False:
+        print "ERROR: Unable to send the last serial packet (file offset: %d)" % sreqpkt.offset
+        return False
+        
+    # Waiting for confirmation
+    packet = s.read_packet(SERIAL_AMGROUP, SERIAL_AMID)
+    sreplypkt = SerialReplyPacket(packet[1])
+    if sreplypkt.error != ERROR_SUCCESS:
+        print "ERROR: Unable to write new versioning information"
+        return False
+            
+    return True
+      
+def print_usage():
+    print "Usage: %s <device> <-p|-i|-r|-d|-e|-s> image_number [options]" % sys.argv[0]
+    print "  -p --ping\n     Provide status of the image in the external flash"
+    print "  -i --inject\n     Inject a compiled TinyOS application"
+    print "      [options]: <tos_image.xml file path>"
+    print "  -r --reboot\n     Reboot and reprogram the directly-connected mote"
+    print "  -d --dissemination\n     Disseminate the image in the external flash to the network"
+    print "  -e --erase\n     Erase an image in the external flash"
+    print "  -s --reset\n     Reset the versioning information for a given image"
+
+# ======== MAIN ======== #
+num_req_arg = 4   # Minimum number of required arguments for this script
+if len(sys.argv) >= num_req_arg:
+    try:
+        sys.argv[3] = int(sys.argv[3])
+    except:
+        print "ERROR: Volume ID is not valid"
+        os._exit(-1)
+    
+    # Initializes serial port communication
+    try:
+        s = tinyos.Serial(sys.argv[1], 115200)
+        s.set_debug(False)   # Disables debug msg
+    except:
+        print "ERROR: Unable to initialize serial port connection"
+        os._exit(-1)
+    
+    if sys.argv[2] in ["-p", "--ping"]:
+        print "Pinging node ..."
+        op_ping(s, sys.argv[3]) 
+    elif sys.argv[2] in ["-i", "--inject"] and len(sys.argv) == (num_req_arg + 1):
+        print "Pinging node ..."
+        op_inject(s, sys.argv[3], sys.argv[4])
+    elif sys.argv[2] in ["-r", "--reboot"]:
+        if op_reprog(s, sys.argv[3]):
+            print "Command sent"
+    elif sys.argv[2] in ["-d", "--dissemination"]:
+        if op_diss(s, sys.argv[3]):
+            print "Command sent"
+    elif sys.argv[2] in ["-e", "--erase"]:
+        if op_erase(s, sys.argv[3]):
+            print "Image number %d erased" % sys.argv[3]
+    elif sys.argv[2] in ["-s", "--reset"]:
+        if op_reset(s, sys.argv[3]):
+            print "Successfully reset image versioning information"
+    else:
+        print_usage()
+
+else:
+    print_usage()
diff --git a/tos/lib/TOSBoot/Deluge.h b/tos/lib/TOSBoot/Deluge.h
new file mode 100644 (file)
index 0000000..b6aa287
--- /dev/null
@@ -0,0 +1,142 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 __DELUGE_H__
+#define __DELUGE_H__
+
+#include "DelugeMetadata.h"
+#include "TOSBoot.h"
+
+#ifndef DELUGE_NUM_IMAGES
+#define DELUGE_NUM_IMAGES 3
+#endif
+
+enum {
+  DELUGE_VERSION                    = 2,
+  DELUGE_MAX_ADV_PERIOD_LOG2        = 22,
+  DELUGE_NUM_NEWDATA_ADVS_REQUIRED  = 2,
+  DELUGE_NUM_MIN_ADV_PERIODS        = 2,
+  DELUGE_MAX_NUM_REQ_TRIES          = 1,
+  DELUGE_REBOOT_DELAY               = 4,
+  DELUGE_FAILED_SEND_DELAY          = 16,
+  DELUGE_MIN_DELAY                  = 16,
+  DELUGE_PKTS_PER_PAGE              = 48,
+  DELUGE_PKT_PAYLOAD_SIZE           = 23,
+  DELUGE_DATA_OFFSET                = 128,
+  DELUGE_IDENT_SIZE                 = 128,
+  DELUGE_INVALID_ADDR               = (0x7fffffffL),
+  DELUGE_MAX_REQ_DELAY              = (0x1L << (DELUGE_MIN_ADV_PERIOD_LOG2-1)),
+  DELUGE_NACK_TIMEOUT               = (DELUGE_MAX_REQ_DELAY >> 0x1),
+  DELUGE_BYTES_PER_PAGE             = (DELUGE_PKTS_PER_PAGE*DELUGE_PKT_PAYLOAD_SIZE),
+  DELUGE_PKT_BITVEC_SIZE            = (((DELUGE_PKTS_PER_PAGE-1) / 8) + 1),
+  DELUGE_MAX_IMAGE_SIZE             = (128L*1024L),
+  DELUGE_MAX_PAGES                  = 128,
+  DELUGE_CRC_SIZE                   = sizeof(uint16_t),
+  DELUGE_CRC_BLOCK_SIZE             = DELUGE_MAX_PAGES*DELUGE_CRC_SIZE,
+  DELUGE_GOLDEN_IMAGE_NUM           = 0x0,
+  DELUGE_INVALID_VNUM               = -1,
+  DELUGE_INVALID_IMGNUM             = 0xff,
+  DELUGE_INVALID_PKTNUM             = 0xff,
+  DELUGE_INVALID_PGNUM              = 0xff,
+};
+
+#include "Storage.h"
+
+struct deluge_image_t {
+  imgnum_t imageNum;
+  volume_id_t volumeId;
+};
+
+typedef struct DelugeAdvTimer {
+  uint32_t timer      : 32;
+  uint8_t  periodLog2 : 8;
+  bool     overheard  : 1;
+  uint8_t  newAdvs    : 7;
+} DelugeAdvTimer;
+
+typedef struct DelugeNodeDesc {
+  imgvnum_t vNum;
+  uint32_t  uid;
+  imgnum_t  imgNum;
+  uint8_t   reserved;
+  uint16_t  crc;
+} DelugeNodeDesc;
+
+enum {
+  DELUGE_VOLUME_ID_0 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 2
+  DELUGE_VOLUME_ID_1 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 3
+  DELUGE_VOLUME_ID_2 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 4
+  DELUGE_VOLUME_ID_3 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 5
+  DELUGE_VOLUME_ID_4 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 6
+  DELUGE_VOLUME_ID_5 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 7
+  DELUGE_VOLUME_ID_6 = unique("StorageManager"),
+#if DELUGE_NUM_IMAGES >= 8
+  DELUGE_VOLUME_ID_7 = unique("StorageManager"),
+#endif
+#endif
+#endif
+#endif
+#endif
+#endif
+#endif
+};
+
+static const struct deluge_image_t DELUGE_IMAGES[DELUGE_NUM_IMAGES] = {
+  { DELUGE_VOLUME_ID_0, 0xDF },
+#if DELUGE_NUM_IMAGES >= 2
+  { DELUGE_VOLUME_ID_1, 0xD0 },
+#if DELUGE_NUM_IMAGES >= 3
+  { DELUGE_VOLUME_ID_2, 0xD1 },
+#if DELUGE_NUM_IMAGES >= 4
+  { DELUGE_VOLUME_ID_3, 0xD2 },
+#if DELUGE_NUM_IMAGES >= 5
+  { DELUGE_VOLUME_ID_4, 0xD3 },
+#if DELUGE_NUM_IMAGES >= 6
+  { DELUGE_VOLUME_ID_5, 0xD4 },
+#if DELUGE_NUM_IMAGES >= 7
+  { DELUGE_VOLUME_ID_6, 0xD5 },
+#if DELUGE_NUM_IMAGES >= 8
+  { DELUGE_VOLUME_ID_7, 0xD6 },
+#endif
+#endif
+#endif
+#endif
+#endif
+#endif
+#endif
+};
+
+#endif
diff --git a/tos/lib/TOSBoot/Exec.nc b/tos/lib/TOSBoot/Exec.nc
new file mode 100644 (file)
index 0000000..3d42c0d
--- /dev/null
@@ -0,0 +1,4 @@
+
+interface Exec {
+  command void exec();
+}
diff --git a/tos/lib/TOSBoot/ExtFlash.nc b/tos/lib/TOSBoot/ExtFlash.nc
new file mode 100644 (file)
index 0000000..a45e8e7
--- /dev/null
@@ -0,0 +1,35 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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>
+ */
+
+interface ExtFlash {
+  command void startRead(uint32_t addr);
+  command uint8_t  readByte();
+  command void stopRead();
+}
diff --git a/tos/lib/TOSBoot/Hardware.nc b/tos/lib/TOSBoot/Hardware.nc
new file mode 100644 (file)
index 0000000..879c044
--- /dev/null
@@ -0,0 +1,34 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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>
+ */
+
+interface Hardware {
+  command void init();
+  command void reboot();
+}
diff --git a/tos/lib/TOSBoot/Leds.nc b/tos/lib/TOSBoot/Leds.nc
new file mode 100644 (file)
index 0000000..c672d1b
--- /dev/null
@@ -0,0 +1,35 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 Leds {
+  command void set(uint8_t ledsOn);
+  command void flash(uint8_t a);
+  command void glow(uint8_t a, uint8_t b);
+}
diff --git a/tos/lib/TOSBoot/Makefile b/tos/lib/TOSBoot/Makefile
new file mode 100644 (file)
index 0000000..5692418
--- /dev/null
@@ -0,0 +1,72 @@
+# $Id$
+
+#                                                                      tab:2
+#
+#
+# "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>
+#
+
+COMPONENT=TOSBoot
+TINYOS_NP=
+
+PFLAGS += -DNESC_BUILD_BINARY
+
+# ifeq ($(MAKECMDGOALS),mica2)
+#   CFLAGS += -DTOSBOOT_START=0x1f000 -DTOSBOOT_END=0x20000
+#   CFLAGS += -Wl,--section-start=.text=0x1f000
+#   CFLAGS += -Iat45db -Iavr -Imica2 -Ilib
+# endif
+
+# ifeq ($(MAKECMDGOALS),mica2dot)
+#   CFLAGS += -DTOSBOOT_START=0x1f000 -DTOSBOOT_END=0x20000
+#   CFLAGS += -Wl,--section-start=.text=0x1f000
+#   CFLAGS += -Iat45db -Iavr -Imica2dot -Ilib
+# endif
+
+ifeq ($(MAKECMDGOALS),micaz)
+  CFLAGS += -DTOSBOOT_START=0x1f000 -DTOSBOOT_END=0x20000
+  CFLAGS += -Wl,--section-start=.text=0x1f000
+  CFLAGS += -Iat45db -Iavr -Imicaz -Ilib
+  CFLAGS += -I../net/Deluge
+endif
+
+# ifeq ($(MAKECMDGOALS),telosa)
+#   CFLAGS += -DTOSBOOT_START=0x1100 -DTOSBOOT_END=0x1a00
+#   CFLAGS += -Iat45db -Imsp430 -Itelos -Ilib
+#   POST_BUILD_EXTRA_DEPS += strip_iv
+# endif
+
+ifeq ($(MAKECMDGOALS),telosb)
+  CFLAGS += -DTOSBOOT_START=0x4000 -DTOSBOOT_END=0x4a00
+  CFLAGS += -Imsp430 -Istm25p -Itelosb -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
+
+include $(MAKERULES)
diff --git a/tos/lib/TOSBoot/ProgFlash.nc b/tos/lib/TOSBoot/ProgFlash.nc
new file mode 100644 (file)
index 0000000..6b67bbb
--- /dev/null
@@ -0,0 +1,33 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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>
+ */
+
+interface ProgFlash {
+  command error_t write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len);
+}
diff --git a/tos/lib/TOSBoot/TOSBoot.h b/tos/lib/TOSBoot/TOSBoot.h
new file mode 100644 (file)
index 0000000..ab5524b
--- /dev/null
@@ -0,0 +1,39 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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"
+
+typedef struct tosboot_args_t {
+  uint32_t imageAddr;
+  uint8_t  gestureCount;
+  bool     noReprogram;
+} tosboot_args_t;
+
+#endif
diff --git a/tos/lib/TOSBoot/TOSBoot.nc b/tos/lib/TOSBoot/TOSBoot.nc
new file mode 100644 (file)
index 0000000..d08429b
--- /dev/null
@@ -0,0 +1,61 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 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
new file mode 100644 (file)
index 0000000..b5098a1
--- /dev/null
@@ -0,0 +1,259 @@
+/*
+ * "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;
+    uint8_t  i;
+    for ( i = 0; i < 4; i++ )
+      result |= ((in_flash_addr_t)call ExtFlash.readByte() & 0xff) << (i*8);    
+    return result;
+  }
+
+  bool verifyImage(ex_flash_addr_t startAddr) {
+
+    uint16_t crcTarget = 0, crcTmp = 0;
+    uint16_t addr, len;
+    pgnum_t  numPgs;
+    uint8_t  i;
+
+    // read size of image
+    call ExtFlash.startRead(startAddr + offsetof(DelugeImgDesc,numPgs));
+    numPgs = call ExtFlash.readByte();
+    call ExtFlash.stopRead();
+
+    if (numPgs == 0 || numPgs == 0xff)
+      return FALSE;
+
+    startAddr += DELUGE_METADATA_SIZE;
+
+    addr = DELUGE_CRC_BLOCK_SIZE;
+    len = DELUGE_BYTES_PER_PAGE-DELUGE_CRC_BLOCK_SIZE;
+
+    for ( i = 0; i < numPgs && crcTarget == crcTmp; i++ ) {
+
+      // read crc
+      call ExtFlash.startRead(startAddr + i*sizeof(uint16_t));
+      crcTarget = (uint16_t)(call ExtFlash.readByte() & 0xff);
+      crcTarget |= (uint16_t)(call ExtFlash.readByte() & 0xff) << 8;
+      call ExtFlash.stopRead();
+
+      // compute crc
+      call ExtFlash.startRead(startAddr + addr);
+      for ( crcTmp = 0; len; len-- )
+       crcTmp = crcByte(crcTmp, call ExtFlash.readByte());
+      call ExtFlash.stopRead();
+
+      addr = (uint16_t)(i+1)*DELUGE_BYTES_PER_PAGE;
+      len = DELUGE_BYTES_PER_PAGE;
+    }
+
+    return (i == numPgs) && (crcTarget == crcTmp);
+  }
+
+  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_METADATA_SIZE + DELUGE_CRC_BLOCK_SIZE + DELUGE_IDENT_SIZE;
+
+    call ExtFlash.startRead(curAddr);
+
+    intAddr = extFlashReadAddr();
+    secLength = extFlashReadAddr();
+    curAddr = curAddr + 8;
+
+    // check that the image starts on the correct boundary
+    if (intAddr != TOSBOOT_END) {
+      call ExtFlash.stopRead();
+      return R_INVALID_IMAGE_ERROR;
+    }
+
+    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 )
+         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() {
+
+    tosboot_args_t 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() __attribute__ ((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/Voltage.nc b/tos/lib/TOSBoot/Voltage.nc
new file mode 100644 (file)
index 0000000..de4bbec
--- /dev/null
@@ -0,0 +1,33 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 Voltage {
+  command bool okToProgram();
+}
diff --git a/tos/lib/TOSBoot/at45db/ExtFlashC.nc b/tos/lib/TOSBoot/at45db/ExtFlashC.nc
new file mode 100644 (file)
index 0000000..1d5d3c8
--- /dev/null
@@ -0,0 +1,126 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 ExtFlashC {
+  provides {
+    interface Init;
+    interface StdControl;
+    interface ExtFlash;
+  }
+}
+
+implementation {
+
+  uint32_t addr;
+
+  command error_t Init.init() {
+    TOSH_MAKE_FLASH_CS_OUTPUT();
+    TOSH_SET_FLASH_CS_PIN();
+    TOSH_MAKE_FLASH_CLK_OUTPUT();
+    TOSH_CLR_FLASH_CLK_PIN();
+    TOSH_MAKE_FLASH_OUT_OUTPUT();      
+    TOSH_SET_FLASH_OUT_PIN();
+    TOSH_MAKE_FLASH_IN_INPUT();
+    TOSH_CLR_FLASH_IN_PIN();
+    return SUCCESS; 
+  }
+
+  command error_t StdControl.start() { return SUCCESS; }
+  command error_t StdControl.stop() { return SUCCESS; }
+
+  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;
+
+  }
+
+  command void ExtFlash.startRead(uint32_t newAddr) {
+
+    uint8_t  cmdBuf[4];
+    uint8_t  i;
+
+    addr = newAddr;
+
+    cmdBuf[0] = 0x68;
+    cmdBuf[1] = (addr >> 15) & 0xff;
+    cmdBuf[2] = (addr >> 7) & 0xfe;
+    cmdBuf[3] = addr & 0xff;
+    
+    TOSH_CLR_FLASH_CLK_PIN();
+    TOSH_CLR_FLASH_CS_PIN();
+    
+    for(i = 0; i < 4; i++)
+      SPIByte(cmdBuf[i]);
+    for(i = 0; i < 4; i++)
+      SPIByte(0x0);
+    
+    TOSH_SET_FLASH_CLK_PIN();
+    TOSH_CLR_FLASH_CLK_PIN();
+
+  }
+
+  command uint8_t ExtFlash.readByte() {
+    if (!(addr & 0xff)) {
+      call ExtFlash.stopRead();
+      call ExtFlash.startRead(addr);
+    }
+    addr++;
+    return SPIByte(0);
+  }
+
+  command void ExtFlash.stopRead() {
+    TOSH_SET_FLASH_CS_PIN();
+  }
+
+}
diff --git a/tos/lib/TOSBoot/avr/HardwareC.nc b/tos/lib/TOSBoot/avr/HardwareC.nc
new file mode 100644 (file)
index 0000000..c48c89b
--- /dev/null
@@ -0,0 +1,46 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 HardwareC {
+  provides {
+    interface Hardware;
+  }
+}
+
+implementation {
+
+  command void Hardware.init() {}
+  
+  command void Hardware.reboot() {
+    wdt_enable(1);
+    while(1);
+  }
+
+}
diff --git a/tos/lib/TOSBoot/avr/InternalFlashC.nc b/tos/lib/TOSBoot/avr/InternalFlashC.nc
new file mode 100644 (file)
index 0000000..1d6d8fb
--- /dev/null
@@ -0,0 +1,65 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 InternalFlash;
+
+module InternalFlashC {
+  provides interface InternalFlash;
+}
+
+implementation {
+
+  command error_t InternalFlash.write(void* addr, void* buf, uint16_t size) {
+
+    uint8_t *addrPtr = (uint8_t*)addr;
+    uint8_t *bufPtr = (uint8_t*)buf;
+
+    for ( ; size; size-- )
+      eeprom_write_byte(addrPtr++, *bufPtr++);
+
+    while(!eeprom_is_ready());
+
+    return SUCCESS;
+
+  }
+
+  command error_t InternalFlash.read(void* addr, void* buf, uint16_t size) {
+
+    uint8_t *addrPtr = (uint8_t*)addr;
+    uint8_t *bufPtr = (uint8_t*)buf;
+
+    for ( ; size; size-- )
+      *bufPtr++ = eeprom_read_byte(addrPtr++);
+
+    return SUCCESS;
+
+  }
+
+}
diff --git a/tos/lib/TOSBoot/avr/ProgFlashM.nc b/tos/lib/TOSBoot/avr/ProgFlashM.nc
new file mode 100644 (file)
index 0000000..8bada2d
--- /dev/null
@@ -0,0 +1,65 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 <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( 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/avr/boot.h b/tos/lib/TOSBoot/avr/boot.h
new file mode 100644 (file)
index 0000000..08c89ce
--- /dev/null
@@ -0,0 +1,498 @@
+/* Copyright (c) 2002, 2003, 2004  Eric B. Weddington\r
+   All rights reserved.\r
+\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are met:\r
+\r
+   * Redistributions of source code must retain the above copyright\r
+     notice, this list of conditions and the following disclaimer.\r
+   * Redistributions in binary form must reproduce the above copyright\r
+     notice, this list of conditions and the following disclaimer in\r
+     the documentation and/or other materials provided with the\r
+     distribution.\r
+   * Neither the name of the copyright holders nor the names of\r
+     contributors may be used to endorse or promote products derived\r
+     from this software without specific prior written permission.\r
+\r
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\r
+  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+  POSSIBILITY OF SUCH DAMAGE. */\r
+\r
+#ifndef _AVR_BOOT_H_\r
+#define _AVR_BOOT_H_    1\r
+\r
+/** \defgroup avr_boot Bootloader Support Utilities\r
+    \code\r
+    #include <avr/io.h>\r
+    #include <avr/boot.h>\r
+    \endcode\r
+\r
+    The macros in this module provide a C language interface to the\r
+    bootloader support functionality of certain AVR processors. These\r
+    macros are designed to work with all sizes of flash memory.\r
+\r
+    \note Not all AVR processors provide bootloader support. See your\r
+    processor datasheet to see if it provides bootloader support.\r
+\r
+    \todo From email with Marek: On smaller devices (all except ATmega64/128),\r
+    __SPM_REG is in the I/O space, accessible with the shorter "in" and "out"\r
+    instructions - since the boot loader has a limited size, this could be an\r
+    important optimization.\r
+\r
+    \par API Usage Example\r
+    The following code shows typical usage of the boot API.\r
+\r
+    \code\r
+    #include <avr/interrupt.h>\r
+    #include <avr/pgmspace.h>\r
+    \r
+    #define ADDRESS     0x1C000UL\r
+    \r
+    void boot_test(void)\r
+    {\r
+        unsigned char buffer[8];\r
+    \r
+        cli();\r
+    \r
+        // Erase page.\r
+        boot_page_erase((unsigned long)ADDRESS);\r
+        while(boot_rww_busy())\r
+        {\r
+            boot_rww_enable();\r
+        }\r
+    \r
+        // Write data to buffer a word at a time. Note incrementing address\r
+        // by 2. SPM_PAGESIZE is defined in the microprocessor IO header file.\r
+        for(unsigned long i = ADDRESS; i < ADDRESS + SPM_PAGESIZE; i += 2)\r
+        {\r
+            boot_page_fill(i, (i-ADDRESS) + ((i-ADDRESS+1) << 8));\r
+        }\r
+    \r
+        // Write page.\r
+        boot_page_write((unsigned long)ADDRESS);\r
+        while(boot_rww_busy())\r
+        {\r
+            boot_rww_enable();\r
+        }\r
+    \r
+        sei();\r
+    \r
+        // Read back the values and display.\r
+        // (The show() function is undefined and is used here as an example\r
+        // only.)\r
+        for(unsigned long i = ADDRESS; i < ADDRESS + 256; i++)\r
+        {\r
+            show(utoa(pgm_read_byte(i), buffer, 16));\r
+        }\r
+    \r
+        return;\r
+    }\endcode */\r
+\r
+#include <avr/eeprom.h>\r
+#include <avr/io.h>\r
+#include <inttypes.h>\r
+#include <limits.h>\r
+\r
+/* Check for SPM Control Register in processor. */\r
+#if defined (SPMCSR)\r
+#  define __SPM_REG    SPMCSR\r
+#elif defined (SPMCR)\r
+#  define __SPM_REG    SPMCR\r
+#else\r
+#  error AVR processor does not provide bootloader support!\r
+#endif\r
+\r
+/** \ingroup avr_boot\r
+    \def BOOTLOADER_SECTION\r
+\r
+    Used to declare a function or variable to be placed into a\r
+    new section called .bootloader. This section and its contents\r
+    can then be relocated to any address (such as the bootloader\r
+    NRWW area) at link-time. */\r
+\r
+#define BOOTLOADER_SECTION    __attribute__ ((section (".bootloader")))\r
+\r
+/* Create common bit definitions. */\r
+#ifdef ASB\r
+#define __COMMON_ASB    ASB\r
+#else\r
+#define __COMMON_ASB    RWWSB\r
+#endif\r
+\r
+#ifdef ASRE\r
+#define __COMMON_ASRE   ASRE\r
+#else\r
+#define __COMMON_ASRE   RWWSRE\r
+#endif\r
+\r
+/* Define the bit positions of the Boot Lock Bits. */\r
+\r
+#define BLB12           5\r
+#define BLB11           4\r
+#define BLB02           3\r
+#define BLB01           2\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_spm_interrupt_enable()\r
+    Enable the SPM interrupt. */\r
+\r
+#define boot_spm_interrupt_enable()   (__SPM_REG |= (uint8_t)_BV(SPMIE))\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_spm_interrupt_disable()\r
+    Disable the SPM interrupt. */\r
+\r
+#define boot_spm_interrupt_disable()  (__SPM_REG &= (uint8_t)~_BV(SPMIE))\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_is_spm_interrupt()\r
+    Check if the SPM interrupt is enabled. */\r
+\r
+#define boot_is_spm_interrupt()       (__SPM_REG & (uint8_t)_BV(SPMIE))\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_rww_busy()\r
+    Check if the RWW section is busy. */\r
+\r
+#define boot_rww_busy()          (__SPM_REG & (uint8_t)_BV(__COMMON_ASB))\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_spm_busy()\r
+    Check if the SPM instruction is busy. */\r
+\r
+#define boot_spm_busy()               (__SPM_REG & (uint8_t)_BV(SPMEN))\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_spm_busy_wait()\r
+    Wait while the SPM instruction is busy. */\r
+\r
+#define boot_spm_busy_wait()          do{}while(boot_spm_busy())\r
+\r
+#define __BOOT_PAGE_ERASE         (_BV(SPMEN) | _BV(PGERS))\r
+#define __BOOT_PAGE_WRITE         (_BV(SPMEN) | _BV(PGWRT))\r
+#define __BOOT_PAGE_FILL          _BV(SPMEN)\r
+#define __BOOT_RWW_ENABLE         (_BV(SPMEN) | _BV(__COMMON_ASRE))\r
+#define __BOOT_LOCK_BITS_SET      (_BV(SPMEN) | _BV(BLBSET))\r
+\r
+#define __BOOT_LOCK_BITS_MASK     (_BV(BLB01) | _BV(BLB02) \\r
+                                   | _BV(BLB11) | _BV(BLB12))\r
+\r
+#define eeprom_busy_wait() do {} while (!eeprom_is_ready())\r
+\r
+#define __boot_page_fill_normal(address, data)   \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw  r0, %3\n\t"                       \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        "clr  r1\n\t"                            \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_FILL),       \\r
+          "r" ((uint16_t)address),               \\r
+          "r" ((uint16_t)data)                   \\r
+        : "r0", "r30", "r31"                     \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_fill_alternate(address, data)\\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw  r0, %3\n\t"                       \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        ".word 0xffff\n\t"                       \\r
+        "nop\n\t"                                \\r
+        "clr  r1\n\t"                            \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_FILL),       \\r
+          "r" ((uint16_t)address),               \\r
+          "r" ((uint16_t)data)                   \\r
+        : "r0", "r30", "r31"                     \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_fill_extended(address, data) \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw  r0, %4\n\t"                       \\r
+        "movw r30, %A3\n\t"                      \\r
+        "sts %1, %C3\n\t"                        \\r
+        "sts %0, %2\n\t"                         \\r
+        "spm\n\t"                                \\r
+        "clr  r1\n\t"                            \\r
+        : "=m" (__SPM_REG),                      \\r
+          "=m" (RAMPZ)                           \\r
+        : "r" ((uint8_t)__BOOT_PAGE_FILL),       \\r
+          "r" ((uint32_t)address),               \\r
+          "r" ((uint16_t)data)                   \\r
+        : "r0", "r30", "r31"                     \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_erase_normal(address)        \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_ERASE),      \\r
+          "r" ((uint16_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_erase_alternate(address)     \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        ".word 0xffff\n\t"                       \\r
+        "nop\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_ERASE),      \\r
+          "r" ((uint16_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_erase_extended(address)      \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %A3\n\t"                      \\r
+        "sts  %1, %C3\n\t"                       \\r
+        "sts %0, %2\n\t"                         \\r
+        "spm\n\t"                                \\r
+        : "=m" (__SPM_REG),                      \\r
+          "=m" (RAMPZ)                           \\r
+        : "r" ((uint8_t)__BOOT_PAGE_ERASE),      \\r
+          "r" ((uint32_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_write_normal(address)        \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_WRITE),      \\r
+          "r" ((uint16_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_write_alternate(address)     \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %2\n\t"                       \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        ".word 0xffff\n\t"                       \\r
+        "nop\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_PAGE_WRITE),      \\r
+          "r" ((uint16_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_page_write_extended(address)      \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "movw r30, %A3\n\t"                      \\r
+        "sts %1, %C3\n\t"                        \\r
+        "sts %0, %2\n\t"                         \\r
+        "spm\n\t"                                \\r
+        : "=m" (__SPM_REG),                      \\r
+          "=m" (RAMPZ)                           \\r
+        : "r" ((uint8_t)__BOOT_PAGE_WRITE),      \\r
+          "r" ((uint32_t)address)                \\r
+        : "r30", "r31"                           \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_rww_enable()                      \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_RWW_ENABLE)       \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_rww_enable_alternate()            \\r
+({                                               \\r
+    boot_spm_busy_wait();                        \\r
+    eeprom_busy_wait();                          \\r
+    __asm__ __volatile__                         \\r
+    (                                            \\r
+        "sts %0, %1\n\t"                         \\r
+        "spm\n\t"                                \\r
+        ".word 0xffff\n\t"                       \\r
+        "nop\n\t"                                \\r
+        : "=m" (__SPM_REG)                       \\r
+        : "r" ((uint8_t)__BOOT_RWW_ENABLE)       \\r
+    );                                           \\r
+})\r
+\r
+#define __boot_lock_bits_set(lock_bits)                    \\r
+({                                                         \\r
+    uint8_t value = (uint8_t)(lock_bits | __BOOT_LOCK_BITS_MASK); \\r
+    boot_spm_busy_wait();                                  \\r
+    eeprom_busy_wait();                                    \\r
+    __asm__ __volatile__                                   \\r
+    (                                                      \\r
+        "ldi r30, 1\n\t"                                   \\r
+        "ldi r31, 0\n\t"                                   \\r
+        "mov r0, %2\n\t"                                   \\r
+        "sts %0, %1\n\t"                                   \\r
+        "spm\n\t"                                          \\r
+        : "=m" (__SPM_REG)                                 \\r
+        : "r" ((uint8_t)__BOOT_LOCK_BITS_SET),             \\r
+          "r" (value)                                      \\r
+        : "r0", "r30", "r31"                               \\r
+    );                                                     \\r
+})\r
+\r
+#define __boot_lock_bits_set_alternate(lock_bits)          \\r
+({                                                         \\r
+    uint8_t value = (uint8_t)(lock_bits | __BOOT_LOCK_BITS_MASK); \\r
+    boot_spm_busy_wait();                                  \\r
+    eeprom_busy_wait();                                    \\r
+    __asm__ __volatile__                                   \\r
+    (                                                      \\r
+        "ldi r30, 1\n\t"                                   \\r
+        "ldi r31, 0\n\t"                                   \\r
+        "mov r0, %2\n\t"                                   \\r
+        "sts %0, %1\n\t"                                   \\r
+        "spm\n\t"                                          \\r
+        ".word 0xffff\n\t"                                 \\r
+        "nop\n\t"                                          \\r
+        : "=m" (__SPM_REG)                                 \\r
+        : "r" ((uint8_t)__BOOT_LOCK_BITS_SET),       \\r
+          "r" (value)                                      \\r
+        : "r0", "r30", "r31"                               \\r
+    );                                                     \\r
+})\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_page_fill(address, data)\r
+\r
+    Fill the bootloader temporary page buffer for flash \r
+    address with data word. \r
+\r
+    \note The address is a byte address. The data is a word. The AVR \r
+    writes data to the buffer a word at a time, but addresses the buffer\r
+    per byte! So, increment your address by 2 between calls, and send 2\r
+    data bytes in a word format! The LSB of the data is written to the lower \r
+    address; the MSB of the data is written to the higher address.*/\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_page_erase(address)\r
+\r
+    Erase the flash page that contains address.\r
+\r
+    \note address is a byte address in flash, not a word address. */\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_page_write(address)\r
+\r
+    Write the bootloader temporary page buffer \r
+    to flash page that contains address.\r
+    \r
+    \note address is a byte address in flash, not a word address. */\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_rww_enable()\r
+\r
+    Enable the Read-While-Write memory section. */\r
+\r
+/** \ingroup avr_boot\r
+    \def boot_lock_bits_set(lock_bits)\r
+\r
+    Set the bootloader lock bits. */\r
+\r
+/* Normal versions of the macros use 16-bit addresses.\r
+   Extended versions of the macros use 32-bit addresses.\r
+   Alternate versions of the macros use 16-bit addresses and require special\r
+   instruction sequences after LPM.\r
+\r
+   FLASHEND is defined in the ioXXXX.h file.\r
+   USHRT_MAX is defined in <limits.h>. */ \r
+\r
+#if defined(__AVR_ATmega161__) || defined(__AVR_ATmega163__) \\r
+    || defined(__AVR_ATmega323__)\r
+\r
+/* Alternate: ATmega161/163/323 and 16 bit address */\r
+#define boot_page_fill(address, data) __boot_page_fill_alternate(address, data)\r
+#define boot_page_erase(address)      __boot_page_erase_alternate(address)\r
+#define boot_page_write(address)      __boot_page_write_alternate(address)\r
+#define boot_rww_enable()             __boot_rww_enable_alternate()\r
+#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set_alternate(lock_bits)\r
+\r
+#elif (FLASHEND > USHRT_MAX) && !defined(__USING_MINT8)\r
+\r
+/* Extended: >16 bit address */\r
+#define boot_page_fill(address, data) __boot_page_fill_extended(address, data)\r
+#define boot_page_erase(address)      __boot_page_erase_extended(address)\r
+#define boot_page_write(address)      __boot_page_write_extended(address)\r
+#define boot_rww_enable()             __boot_rww_enable()\r
+#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set(lock_bits)\r
+\r
+#else\r
+\r
+/* Normal: 16 bit address */\r
+#define boot_page_fill(address, data) __boot_page_fill_normal(address, data)\r
+#define boot_page_erase(address)      __boot_page_erase_normal(address)\r
+#define boot_page_write(address)      __boot_page_write_normal(address)\r
+#define boot_rww_enable()             __boot_rww_enable()\r
+#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set(lock_bits)\r
+\r
+#endif\r
+\r
+#endif /* _AVR_BOOT_H_ */\r
diff --git a/tos/lib/TOSBoot/crc.h b/tos/lib/TOSBoot/crc.h
new file mode 100644 (file)
index 0000000..64391d3
--- /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.
+ */
+
+/**
+ * Default CRC function. Note that avrmote has a much more efficient one. 
+ *
+ * This CRC-16 function produces a 16-bit running CRC that adheres to the
+ * ITU-T CRC standard.
+ *
+ * The ITU-T polynomial is: G_16(x) = x^16 + x^12 + x^5 + 1
+ *
+ */
+
+uint16_t 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;
+}
diff --git a/tos/lib/TOSBoot/lib/ExecC.nc b/tos/lib/TOSBoot/lib/ExecC.nc
new file mode 100644 (file)
index 0000000..f29fb8c
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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/lib/LedsC.nc b/tos/lib/TOSBoot/lib/LedsC.nc
new file mode 100644 (file)
index 0000000..476f76e
--- /dev/null
@@ -0,0 +1,80 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 LedsC {
+  provides interface Leds;
+}
+
+implementation {
+
+  enum {
+    RED_BIT = 1,
+    GREEN_BIT = 2,
+    YELLOW_BIT = 4
+  };
+
+  command void Leds.set(uint8_t ledsOn) {
+    if (ledsOn & GREEN_BIT) 
+      TOSH_CLR_GREEN_LED_PIN();
+    else
+      TOSH_SET_GREEN_LED_PIN();
+    if (ledsOn & YELLOW_BIT ) 
+      TOSH_CLR_YELLOW_LED_PIN();
+    else 
+      TOSH_SET_YELLOW_LED_PIN();
+    if (ledsOn & RED_BIT) 
+      TOSH_CLR_RED_LED_PIN();
+    else 
+      TOSH_SET_RED_LED_PIN();
+  }
+
+  command void Leds.flash(uint8_t a) {
+    uint8_t i, j;
+    for ( i = 3; i; i-- ) {
+      call Leds.set(a);
+      for ( j = 4; j; j-- )
+       wait(0xffff);
+      call Leds.set(0);
+      for ( j = 4; j; j-- )
+       wait(0xffff);
+    }
+  }
+
+  command void Leds.glow(uint8_t a, uint8_t b) {
+    int i;
+    for (i = 1536; i > 0; i -= 4) {
+      call Leds.set(a);
+      wait(i);
+      call Leds.set(b);
+      wait(1536-i);
+    }
+  }
+
+}
diff --git a/tos/lib/TOSBoot/micaz/ExecC.nc b/tos/lib/TOSBoot/micaz/ExecC.nc
new file mode 100644 (file)
index 0000000..dc789ac
--- /dev/null
@@ -0,0 +1,40 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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() {
+    __asm__ __volatile__ ("jmp 0x0000\n\t" ::);
+  }
+
+}
diff --git a/tos/lib/TOSBoot/micaz/InternalFlash.h b/tos/lib/TOSBoot/micaz/InternalFlash.h
new file mode 100644 (file)
index 0000000..01f69e8
--- /dev/null
@@ -0,0 +1,41 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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 the avr
+ * platform.
+ *
+ * Valid address range is 0x0 - 0xFFF.
+ *
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __INTERNAL_FLASH_H__
+#define __INTERNAL_FLASH_H__
+
+#include <avr/eeprom.h>
+
+#endif
diff --git a/tos/lib/TOSBoot/micaz/PluginC.nc b/tos/lib/TOSBoot/micaz/PluginC.nc
new file mode 100644 (file)
index 0000000..237998e
--- /dev/null
@@ -0,0 +1,13 @@
+
+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/micaz/TOSBoot_platform.h b/tos/lib/TOSBoot/micaz/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..e18285e
--- /dev/null
@@ -0,0 +1,47 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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 = 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,
+};
+
+enum {
+  DELUGE_MIN_ADV_PERIOD_LOG2 = 9,
+  DELUGE_QSIZE = 2,
+};
+
+#endif
diff --git a/tos/lib/TOSBoot/micaz/VoltageC.nc b/tos/lib/TOSBoot/micaz/VoltageC.nc
new file mode 100644 (file)
index 0000000..85b8f10
--- /dev/null
@@ -0,0 +1,58 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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() {
+
+    // 250 KHz ADC clock (4MHz/16)
+    outp( 0x04, ADCSR );
+    // clear interrupt flag by writing a 1
+    sbi( ADCSR, ADIF );
+    // setup input channel
+    outp( VOLTAGE_PORT, ADMUX );
+    // adc enable
+    sbi( ADCSR, ADEN );
+    // adc start conversion
+    sbi( ADCSR, ADSC );
+    // wait for conversion to complete
+    while ( !bit_is_set( ADCSR, ADIF ) );
+
+    return ( __inw(ADCL) < VTHRESH  );
+
+  }
+
+}
diff --git a/tos/lib/TOSBoot/micaz/avrhardware.h b/tos/lib/TOSBoot/micaz/avrhardware.h
new file mode 100644 (file)
index 0000000..4263d56
--- /dev/null
@@ -0,0 +1,196 @@
+// $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:             Jason Hill, Philip Levis, Nelson Lee
+ *
+ *
+ */
+
+/**
+ * @author Jason Hill
+ * @author Philip Levis
+ * @author Nelson Lee
+ */
+
+
+#ifndef TOSH_AVRHARDWARE_H
+#define TOSH_AVRHARDWARE_H
+
+// check for a new-look avr-libc
+#if defined(DTOSTR_ALWAYS_SIGN) && !defined(TOSH_NEW_AVRLIBC)
+#define TOSH_NEW_AVRLIBC
+#endif
+
+#ifdef TOSH_NEW_AVRLIBC
+#include <avr/io.h>
+#include <avr/signal.h>
+#include <avr/interrupt.h>
+#include <avr/wdt.h>
+#include <avr/pgmspace.h>
+#include <avr/eeprom.h>
+
+#ifndef sbi
+/* avr-libc 1.2.3 doesn't include these anymore. */
+#define sbi(port, bit) ((port) |= _BV(bit))
+#define cbi(port, bit) ((port) &= ~_BV(bit))
+#define inp(port) (port)
+#define inb(port) (port)
+#define outp(value, port) ((port) = (value))
+#define outb(port, value) ((port) = (value))
+#define inw(port) (*(volatile uint16_t *)&(port))
+#define outw(port, value) ((*(volatile uint16_t *)&(port)) = (value))
+#define PRG_RDB(addr) pgm_read_byte(addr)
+#endif
+
+#else
+#include <io.h>
+#include <sig-avr.h>
+#include <interrupt.h>
+#include <wdt.h>
+#include <pgmspace.h>
+#endif /* TOSH_NEW_AVRLIBC */
+
+// check for version 3.3 of GNU gcc or later
+#if ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3))
+#define __outw(val, port) outw(port, val);
+#endif
+
+#ifndef __inw
+#ifndef __SFR_OFFSET
+#define __SFR_OFFSET 0
+#endif /* !__SFR_OFFSET */
+#define __inw(_port) inw(_port)
+
+#define __inw_atomic(__sfrport) ({                             \
+       uint16_t __t;                                   \
+       bool bStatus;                                   \
+       bStatus = bit_is_set(SREG,7);                   \
+       cli();                                          \
+       __t = inw(__sfrport);                           \
+       if (bStatus) sei();                             \
+       __t;                                            \
+ })
+
+#endif /* __inw */
+
+#define TOSH_ASSIGN_PIN(name, port, bit) \
+static inline void TOSH_SET_##name##_PIN() {sbi(PORT##port , bit);} \
+static inline void TOSH_CLR_##name##_PIN() {cbi(PORT##port , bit);} \
+static inline int TOSH_READ_##name##_PIN() \
+  {return (inp(PIN##port) & (1 << bit)) != 0;} \
+static inline void TOSH_MAKE_##name##_OUTPUT() {sbi(DDR##port , bit);} \
+static inline void TOSH_MAKE_##name##_INPUT() {cbi(DDR##port , bit);} 
+
+#define TOSH_ASSIGN_OUTPUT_ONLY_PIN(name, port, bit) \
+static inline void TOSH_SET_##name##_PIN() {sbi(PORT##port , bit);} \
+static inline void TOSH_CLR_##name##_PIN() {cbi(PORT##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();} 
+
+// We need slightly different defs than SIGNAL, INTERRUPT
+#define TOSH_SIGNAL(signame)                                   \
+void signame() __attribute__ ((signal, spontaneous, C))
+
+#define TOSH_INTERRUPT(signame)                                \
+void signame() __attribute__ ((interrupt, spontaneous, C))
+
+/* Watchdog Prescaler
+ */
+enum {
+  TOSH_period16 = 0x00, // 47ms
+  TOSH_period32 = 0x01, // 94ms
+  TOSH_period64 = 0x02, // 0.19s
+  TOSH_period128 = 0x03, // 0.38s
+  TOSH_period256 = 0x04, // 0.75s
+  TOSH_period512 = 0x05, // 1.5s
+  TOSH_period1024 = 0x06, // 3.0s
+  TOSH_period2048 = 0x07 // 6.0s
+};
+
+void TOSH_wait()
+{
+  asm volatile("nop");
+  asm volatile("nop");
+}
+
+// atomic statement runtime support
+
+/* typedef uint8_t __nesc_atomic_t; */
+
+/* __nesc_atomic_t __nesc_atomic_start(void); */
+/* void __nesc_atomic_end(__nesc_atomic_t oldSreg); */
+
+/* #ifndef NESC_BUILD_BINARY */
+
+/* inline __nesc_atomic_t __nesc_atomic_start(void) __attribute__((spontaneous)) */
+/* { */
+/*   __nesc_atomic_t result = inp(SREG); */
+/*   cli(); */
+/*   return result; */
+/* } */
+
+/* inline void __nesc_atomic_end(__nesc_atomic_t oldSreg) __attribute__((spontaneous)) */
+/* { */
+/*   outp(oldSreg, SREG); */
+/* } */
+
+/* #endif */
+
+/* inline void __nesc_atomic_sleep() */
+/* { */
+/*   /\* Atomically enable interrupts and sleep *\/ */
+/*   sei();  // Make sure interrupts are on, so we can wake up! */
+/*   asm volatile ("sleep"); */
+/*   TOSH_wait(); */
+/* } */
+
+
+/* inline void __nesc_enable_interrupt() { */
+/*   sei(); */
+/* } */
+
+/* inline void __nesc_disable_interrupt() { */
+/*   cli(); */
+/* } */
+
+#endif //TOSH_AVRHARDWARE_H
diff --git a/tos/lib/TOSBoot/micaz/hardware.h b/tos/lib/TOSBoot/micaz/hardware.h
new file mode 100644 (file)
index 0000000..8f7a1c7
--- /dev/null
@@ -0,0 +1,143 @@
+// $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.
+ */
+/*                                                                     tab:4
+ *  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.  By
+ *  downloading, copying, installing or using the software you agree to
+ *  this license.  If you do not agree to this license, do not download,
+ *  install, copy or use the software.
+ *
+ *  Intel Open Source License 
+ *
+ *  Copyright (c) 2002 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.
+ * 
+ * 
+ */
+/*
+ *
+ * $Id$
+ *
+ */
+
+#ifndef __HARDWARE_H__
+#define __HARDWARE_H__
+
+#include <atm128hardware.h>
+#include <avrhardware.h>
+
+typedef uint32_t in_flash_addr_t;
+typedef uint32_t ex_flash_addr_t;
+
+void wait( uint16_t t ) {
+  for ( ; t; t-- );
+}
+
+// LED assignments
+TOSH_ASSIGN_PIN(RED_LED, A, 2);
+TOSH_ASSIGN_PIN(GREEN_LED, A, 1);
+TOSH_ASSIGN_PIN(YELLOW_LED, A, 0);
+
+TOSH_ASSIGN_PIN(SERIAL_ID, A, 4);
+
+// Flash assignments
+TOSH_ASSIGN_PIN(FLASH_CS, A, 3);
+TOSH_ASSIGN_PIN(FLASH_CLK,  D, 5);
+TOSH_ASSIGN_PIN(FLASH_OUT,  D, 3);
+TOSH_ASSIGN_PIN(FLASH_IN,  D, 2);
+
+// power control assignments
+TOSH_ASSIGN_PIN(PW0, C, 0);
+TOSH_ASSIGN_PIN(PW1, C, 1);
+TOSH_ASSIGN_PIN(PW2, C, 2);
+TOSH_ASSIGN_PIN(PW3, C, 3);
+TOSH_ASSIGN_PIN(PW4, C, 4);
+TOSH_ASSIGN_PIN(PW5, C, 5);
+TOSH_ASSIGN_PIN(PW6, C, 6);
+TOSH_ASSIGN_PIN(PW7, C, 7);
+
+void TOSH_SET_PIN_DIRECTIONS(void)
+{
+  TOSH_MAKE_RED_LED_OUTPUT();
+  TOSH_MAKE_YELLOW_LED_OUTPUT();
+  TOSH_MAKE_GREEN_LED_OUTPUT();
+      
+  TOSH_MAKE_PW7_OUTPUT();
+  TOSH_MAKE_PW6_OUTPUT();
+  TOSH_MAKE_PW5_OUTPUT();
+  TOSH_MAKE_PW4_OUTPUT();
+  TOSH_MAKE_PW3_OUTPUT(); 
+  TOSH_MAKE_PW2_OUTPUT();
+  TOSH_MAKE_PW1_OUTPUT();
+  TOSH_MAKE_PW0_OUTPUT();
+
+  TOSH_MAKE_SERIAL_ID_INPUT();
+  TOSH_CLR_SERIAL_ID_PIN();  // Prevent sourcing current
+
+  TOSH_MAKE_FLASH_CS_OUTPUT();
+  TOSH_MAKE_FLASH_OUT_OUTPUT();
+  TOSH_MAKE_FLASH_CLK_OUTPUT();
+  TOSH_SET_FLASH_CS_PIN();
+}
+
+enum {
+  VOLTAGE_PORT = 30,
+  VTHRESH = 0x1cf, // 2.7V
+};
+
+#endif
+
+
+
+
diff --git a/tos/lib/TOSBoot/msp430/HPLUSART0M.nc b/tos/lib/TOSBoot/msp430/HPLUSART0M.nc
new file mode 100644 (file)
index 0000000..e53c9eb
--- /dev/null
@@ -0,0 +1,128 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..4e4998f
--- /dev/null
@@ -0,0 +1,46 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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/HardwareC.nc b/tos/lib/TOSBoot/msp430/HardwareC.nc
new file mode 100644 (file)
index 0000000..ab5ef93
--- /dev/null
@@ -0,0 +1,48 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 HardwareC {
+  provides {
+    interface Hardware;
+  }
+}
+
+implementation {
+
+  command void Hardware.init() {
+    BCSCTL1 = RSEL0 | RSEL1 | RSEL2 | XT2OFF;
+    DCOCTL = DCO0 | DCO1 | DCO2;
+  }
+  
+  command void Hardware.reboot() {
+    WDTCTL = 0;
+  }
+
+}
diff --git a/tos/lib/TOSBoot/msp430/InternalFlashC.nc b/tos/lib/TOSBoot/msp430/InternalFlashC.nc
new file mode 100644 (file)
index 0000000..a913bd7
--- /dev/null
@@ -0,0 +1,122 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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."
+ *
+ */
+
+/**
+ * InternalFlashC.nc - 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>
+ */
+
+includes InternalFlash;
+
+module InternalFlashC {
+  provides interface InternalFlash;
+}
+
+implementation {
+
+  enum {
+    IFLASH_OFFSET     = 0x1000,
+    IFLASH_SIZE       = 128,
+    IFLASH_SEG0_VNUM_ADDR = 0x107f,
+    IFLASH_SEG1_VNUM_ADDR = 0x10ff,
+    IFLASH_INVALID_VNUM = -1,
+  };
+
+  uint8_t chooseSegment() {
+    int8_t vnum0 = *(int8_t*)IFLASH_SEG0_VNUM_ADDR;
+    int8_t vnum1 = *(int8_t*)IFLASH_SEG1_VNUM_ADDR;
+    if (vnum0 == IFLASH_INVALID_VNUM)
+      return 1;
+    else if (vnum1 == IFLASH_INVALID_VNUM)
+      return 0;
+    return ( (int8_t)(vnum0 - vnum1) < 0 );
+  }
+
+  command error_t InternalFlash.write(void* addr, void* buf, uint16_t size) {
+
+    volatile int8_t *newPtr;
+    int8_t *oldPtr;
+    int8_t *bufPtr = (int8_t*)buf;
+    int8_t version;
+    uint16_t i;
+
+    addr += IFLASH_OFFSET;
+    newPtr = oldPtr = (int8_t*)IFLASH_OFFSET;
+    if (chooseSegment()) {
+      oldPtr += IFLASH_SIZE;
+    }
+    else {
+      addr += IFLASH_SIZE;
+      newPtr += IFLASH_SIZE;
+    }
+
+    FCTL2 = FWKEY + FSSEL1 + FN2;
+    FCTL3 = FWKEY;
+    FCTL1 = FWKEY + ERASE;
+    *newPtr = 0;
+    FCTL1 = FWKEY + WRT;
+    
+    for ( i = 0; i < IFLASH_SIZE-1; i++, newPtr++, oldPtr++ ) {
+      if ((uint16_t)newPtr < (uint16_t)addr || (uint16_t)addr+size <= (uint16_t)newPtr)
+       *newPtr = *oldPtr;
+      else
+       *newPtr = *bufPtr++;
+    }
+    version = *oldPtr + 1;
+    if (version == IFLASH_INVALID_VNUM)
+      version++;
+    *newPtr = version;
+    
+    FCTL1 = FWKEY;
+    FCTL3 = FWKEY + LOCK;
+
+    return SUCCESS;
+
+  }
+
+  command error_t InternalFlash.read(void* addr, void* buf, uint16_t size) {
+
+    addr += IFLASH_OFFSET;
+    if (chooseSegment())
+      addr += IFLASH_SIZE;
+
+    memcpy(buf, addr, size);
+
+    return SUCCESS;
+
+  }
+
+}
diff --git a/tos/lib/TOSBoot/msp430/ProgFlashM.nc b/tos/lib/TOSBoot/msp430/ProgFlashM.nc
new file mode 100644 (file)
index 0000000..de8b262
--- /dev/null
@@ -0,0 +1,70 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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/msp430/VoltageC.nc b/tos/lib/TOSBoot/msp430/VoltageC.nc
new file mode 100644 (file)
index 0000000..50a08f8
--- /dev/null
@@ -0,0 +1,72 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 {
+
+  enum {
+    VTHRESH = 0xE66, // 2.7V
+  };
+
+  command bool Voltage.okToProgram() {
+
+    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/stm25p/ExtFlashC.nc b/tos/lib/TOSBoot/stm25p/ExtFlashC.nc
new file mode 100644 (file)
index 0000000..d9c507c
--- /dev/null
@@ -0,0 +1,51 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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 
+    ExtFlashM,
+    HPLUSART0M;
+
+  Init = ExtFlashM;
+  StdControl = ExtFlashM;
+  ExtFlash = ExtFlashM;
+
+  ExtFlashM.USARTControl -> HPLUSART0M;
+
+}
diff --git a/tos/lib/TOSBoot/stm25p/ExtFlashM.nc b/tos/lib/TOSBoot/stm25p/ExtFlashM.nc
new file mode 100644 (file)
index 0000000..f3d16c0
--- /dev/null
@@ -0,0 +1,114 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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/telosb/InternalFlash.h b/tos/lib/TOSBoot/telosb/InternalFlash.h
new file mode 100644 (file)
index 0000000..aa4f872
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..ab860c0
--- /dev/null
@@ -0,0 +1,37 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..de5a7bd
--- /dev/null
@@ -0,0 +1,46 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..404f892
--- /dev/null
@@ -0,0 +1,85 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..afc7693
--- /dev/null
@@ -0,0 +1,47 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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/telosb/hardware.h b/tos/lib/TOSBoot/telosb/hardware.h
new file mode 100644 (file)
index 0000000..ddfae86
--- /dev/null
@@ -0,0 +1,88 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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, 5, 4);
+TOSH_ASSIGN_PIN(GREEN_LED, 5, 5);
+TOSH_ASSIGN_PIN(YELLOW_LED, 5, 6);
+
+// 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_PWR, 4, 3);
+TOSH_ASSIGN_PIN(FLASH_CS, 4, 4);
+TOSH_ASSIGN_PIN(FLASH_HOLD, 4, 7);
+
+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/net/Deluge/AutoStarterC.nc b/tos/lib/net/Deluge/AutoStarterC.nc
new file mode 100644 (file)
index 0000000..ea20545
--- /dev/null
@@ -0,0 +1,38 @@
+/* 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 AutoStarterC
+{
+  uses interface SplitControl;
+}
+
+implementation
+{
+  components MainC, AutoStarterP;
+  
+  SplitControl = AutoStarterP;
+  AutoStarterP.Boot -> MainC;
+}
diff --git a/tos/lib/net/Deluge/AutoStarterP.nc b/tos/lib/net/Deluge/AutoStarterP.nc
new file mode 100644 (file)
index 0000000..d13acff
--- /dev/null
@@ -0,0 +1,45 @@
+/* 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>
+ */
+
+module AutoStarterP
+{
+  uses {
+    interface Boot;
+    interface SplitControl;
+  }
+}
+
+implementation
+{
+  event void Boot.booted()
+  {
+    call SplitControl.start();
+  }
+  
+  event void SplitControl.startDone(error_t error) { }
+  event void SplitControl.stopDone(error_t error) { }
+
+}
diff --git a/tos/lib/net/Deluge/BitVecUtils.h b/tos/lib/net/Deluge/BitVecUtils.h
new file mode 100644 (file)
index 0000000..0e5b716
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * "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."
+ */
+
+/**
+ * Provides generic methods for manipulating bit vectors.
+ *
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __BITVEC_UTILS_H__
+#define __BITVEC_UTILS_H__
+
+#define BIT_GET(x, i) ((x) & (1 << (i)))
+#define BIT_SET(x, i) ((x) | (1 << (i)))
+#define BIT_CLEAR(x, i) ((x) & ~(1 << (i)))
+
+#define BITVEC_GET(x, i) (BIT_GET((x)[(i)/8], (i)%8))
+#define BITVEC_SET(x, i) ((x)[(i)/8] = BIT_SET((x)[(i)/8], (i)%8))
+#define BITVEC_CLEAR(x, i) ((x)[(i)/8] = BIT_CLEAR((x)[(i)/8], (i)%8))
+
+#endif
diff --git a/tos/lib/net/Deluge/BitVecUtils.nc b/tos/lib/net/Deluge/BitVecUtils.nc
new file mode 100644 (file)
index 0000000..259a874
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * "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."
+ */
+
+/**
+ * Provides generic methods for manipulating bit vectors.
+ *
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+interface BitVecUtils {
+  /**
+   * Locates the index of the first '1' bit in a bit vector.
+   *
+   * @param result     the location of the '1' bit
+   * @param fromIndex  the index to start search for '1' bit
+   * @param bitVec     the bit vector
+   * @param length     the length of the bit vector in bits
+   * @return           <code>SUCCESS</code> if a '1' bit was found;
+   *                   <code>FAIL</code> otherwise.
+   */
+  command error_t indexOf(uint16_t* pResult, uint16_t fromIndex, 
+                          uint8_t* bitVec, uint16_t length);
+
+  /**
+   * Counts the number of '1' bits in a bit vector.
+   *
+   * @param result  the number of '1' bits
+   * @param bitVec  the bit vector
+   * @param length  the length of the bit vector in bits
+   * @return        <code>SUCCESS</code> if the operation completed successfully;
+   *                <code>FAIL</code> otherwise.
+   */
+  command error_t countOnes(uint16_t* pResult, uint8_t* bitVec, 
+                            uint16_t length);
+
+  /**
+   * Generates an ASCII representation of the bit vector.
+   *
+   * @param buf     the character array to place the ASCII string
+   * @param bitVec  the bit vector
+   * @param length  the length of the bit vector in bits
+   */
+  command void printBitVec(char* buf, uint8_t* bitVec, uint16_t length);
+}
diff --git a/tos/lib/net/Deluge/BitVecUtilsC.nc b/tos/lib/net/Deluge/BitVecUtilsC.nc
new file mode 100644 (file)
index 0000000..8c28611
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * "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."
+ */
+
+/**
+ * Provides generic methods for manipulating bit vectors.
+ *
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#include "BitVecUtils.h"
+
+module BitVecUtilsC {
+  provides interface BitVecUtils;
+}
+
+implementation {
+  command error_t BitVecUtils.indexOf(uint16_t* pResult, uint16_t fromIndex, 
+                                                              uint8_t* bitVec, uint16_t length) {
+    uint16_t i = fromIndex;
+
+    if (length == 0)
+      return FAIL;
+    
+    do {
+      if (BITVEC_GET(bitVec, i)) {
+        *pResult = i;
+        return SUCCESS;
+      }
+      i = (i+1) % length;
+    } while (i != fromIndex);
+    
+    return FAIL;
+  }
+
+  command error_t BitVecUtils.countOnes(uint16_t* pResult, uint8_t* bitVec, uint16_t length) {
+
+    int count = 0;
+    int i;
+
+    for ( i = 0; i < length; i++ ) {
+      if (BITVEC_GET(bitVec, i))
+       count++;
+    }
+
+    *pResult = count;
+
+    return SUCCESS;
+
+  }
+
+  command void BitVecUtils.printBitVec(char* buf, uint8_t* bitVec, uint16_t length) {
+#ifdef PLATFORM_PC
+    uint16_t i;
+    
+    dbg(DBG_TEMP, "");
+    for ( i = 0; i < length; i++ ) {
+      sprintf(buf++, "%d", !!BITVEC_GET(bitVec, i));
+    }
+#endif   
+  }
+
+}
diff --git a/tos/lib/net/Deluge/Crc.nc b/tos/lib/net/Deluge/Crc.nc
new file mode 100644 (file)
index 0000000..31fedfd
--- /dev/null
@@ -0,0 +1,29 @@
+/* \r
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  \r
+ * All rights reserved.\r
+ *\r
+ * Permission to use, copy, modify, and distribute this software and its\r
+ * documentation for any purpose, without fee, and without written agreement is\r
+ * hereby granted, provided that the above copyright notice, the following\r
+ * two paragraphs and the author appear in all copies of this software.\r
+ * \r
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR\r
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\r
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF\r
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+ * \r
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,\r
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\r
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS\r
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO\r
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."\r
+ */\r
+\r
+/**\r
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>\r
+ */\r
+\r
+interface Crc\r
+{\r
+  command uint16_t crc16(void* buf, uint8_t len);\r
+}\r
diff --git a/tos/lib/net/Deluge/CrcP.nc b/tos/lib/net/Deluge/CrcP.nc
new file mode 100644 (file)
index 0000000..06ae498
--- /dev/null
@@ -0,0 +1,48 @@
+/* \r
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  \r
+ * All rights reserved.\r
+ *\r
+ * Permission to use, copy, modify, and distribute this software and its\r
+ * documentation for any purpose, without fee, and without written agreement is\r
+ * hereby granted, provided that the above copyright notice, the following\r
+ * two paragraphs and the author appear in all copies of this software.\r
+ * \r
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR\r
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\r
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF\r
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+ * \r
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,\r
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\r
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS\r
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO\r
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."\r
+ */\r
+\r
+/**\r
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>\r
+ */\r
+\r
+#include "crc.h"\r
+\r
+module CrcP\r
+{\r
+  provides interface Crc;\r
+}\r
+\r
+implementation\r
+{\r
+  // From T1 "tos/system/CrcC.nc"\r
+  command uint16_t Crc.crc16(void* buf, uint8_t len)\r
+  {\r
+    uint8_t* tmpBuf = (uint8_t*)buf;\r
+    uint16_t crc;\r
+    \r
+    for (crc = 0; len > 0; len--) {\r
+      crc = crcByte(crc, *tmpBuf);   // Calculates running CRC\r
+      tmpBuf++;\r
+    }\r
+    \r
+    return crc;\r
+  }\r
+}\r
diff --git a/tos/lib/net/Deluge/Deluge.h b/tos/lib/net/Deluge/Deluge.h
new file mode 100644 (file)
index 0000000..c9ec9cb
--- /dev/null
@@ -0,0 +1,52 @@
+/* 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__
+
+#include "DelugeMetadata.h"
+
+enum {
+  DELUGE_INVALID_UID = 0xffffffff,
+  DELUGE_NUM_VOLUMES = 2,
+};
+
+typedef nx_struct DelugeDissemination {
+  nx_uint32_t uid;      // unique id of image
+  nx_uint16_t vNum;     // version num of image
+  nx_uint8_t  imgNum;   // image number
+  nx_uint16_t size;     // size of the image
+} DelugeDissemination;
+
+typedef struct DelugeNodeDesc {
+  imgvnum_t vNum;
+  uint32_t  uid;
+  imgnum_t  imgNum;
+  uint8_t   reserved;
+  uint16_t  crc;
+} DelugeNodeDesc;
+
+#endif
diff --git a/tos/lib/net/Deluge/DelugeC.nc b/tos/lib/net/Deluge/DelugeC.nc
new file mode 100644 (file)
index 0000000..957f98c
--- /dev/null
@@ -0,0 +1,71 @@
+/* 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>
+ */
+
+#include "Deluge.h"
+
+configuration DelugeC {}
+
+implementation
+{
+  components DelugeStorageC;
+
+#ifdef DELUGE_BASESTATION
+  components SerialStarterC;
+  components new FlashVolumeManagerC(0xAB);
+
+  DelugeP.ReprogNotify -> FlashVolumeManagerC;
+  FlashVolumeManagerC.BlockRead[0] -> DelugeStorageC.BlockRead[0];
+  FlashVolumeManagerC.BlockWrite[0] -> DelugeStorageC.BlockWrite[0];
+  FlashVolumeManagerC.StorageMap[0] -> DelugeStorageC.StorageMap[0];
+  FlashVolumeManagerC.BlockRead[1] -> DelugeStorageC.BlockRead[1];
+  FlashVolumeManagerC.BlockWrite[1] -> DelugeStorageC.BlockWrite[1];
+  FlashVolumeManagerC.StorageMap[1] -> DelugeStorageC.StorageMap[1];
+#endif
+  
+  components ObjectTransferC;
+  ObjectTransferC.BlockRead[0] -> DelugeStorageC.BlockRead[0];
+  ObjectTransferC.BlockWrite[0] -> DelugeStorageC.BlockWrite[0];
+  ObjectTransferC.BlockRead[1] -> DelugeStorageC.BlockRead[1];
+  ObjectTransferC.BlockWrite[1] -> DelugeStorageC.BlockWrite[1];
+  
+  components new DisseminatorC(DelugeDissemination, 0xDE00), DisseminationC;
+  components ActiveMessageC;
+  components NetProgC, DelugeP;
+  components new TimerMilliC() as Timer;
+  components LedsC, NoLedsC;
+  DelugeP.Leds -> LedsC;  
+  DelugeP.DisseminationValue -> DisseminatorC;
+  DelugeP.DisseminationUpdate -> DisseminatorC;
+  DelugeP.StdControlDissemination -> DisseminationC;
+  DelugeP.ObjectTransfer -> ObjectTransferC;
+  DelugeP.NetProg -> NetProgC;
+  DelugeP.StorageReadyNotify -> DelugeStorageC;
+  DelugeP.DelugeMetadata -> DelugeStorageC;
+  DelugeP.RadioSplitControl -> ActiveMessageC;
+  
+  components InternalFlashC as IFlash;
+  DelugeP.IFlash -> IFlash;
+}
diff --git a/tos/lib/net/Deluge/DelugeMetadata.h b/tos/lib/net/Deluge/DelugeMetadata.h
new file mode 100644 (file)
index 0000000..1c17f59
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * "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>
+ */
+
+#ifndef __DELUGE_METADATA_H__
+#define __DELUGE_METADATA_H__
+
+#define DELUGE_METADATA_SIZE 16
+
+typedef int16_t imgvnum_t;
+typedef uint8_t  imgnum_t;
+typedef uint8_t   pgnum_t;
+
+typedef struct DelugeImgDesc {
+  uint32_t  uid;            // unique id of image
+  imgvnum_t vNum;           // version num of image
+  imgnum_t  imgNum;         // image number
+  pgnum_t   numPgs;         // num pages of complete image
+  uint16_t  crc;            // crc for vNum and numPgs
+  uint8_t   numPgsComplete; // numPgsComplete in image
+  uint8_t   reserved;
+  uint16_t  size;           // size of the whole image (metadata + CRCs + ident + binary)
+} DelugeImgDesc;
+
+#endif
diff --git a/tos/lib/net/Deluge/DelugeMetadata.nc b/tos/lib/net/Deluge/DelugeMetadata.nc
new file mode 100644 (file)
index 0000000..d600444
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * "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."
+ *
+ * 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>
+ */
+
+interface DelugeMetadata {
+  command DelugeImgDesc* getImgDesc(imgnum_t imgNum);
+}
diff --git a/tos/lib/net/Deluge/DelugeMsgs.h b/tos/lib/net/Deluge/DelugeMsgs.h
new file mode 100644 (file)
index 0000000..2da6fdd
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * "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."
+ *
+ * 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>
+ */
+
+#ifndef __DELUGE_MSGS_H__
+#define __DELUGE_MSGS_H__
+
+#include "DelugePageTransfer.h"
+
+enum {
+  DELUGE_ADV_NORMAL = 0,
+  DELUGE_ADV_ERROR  = 1,
+  DELUGE_ADV_PC     = 2,
+  DELUGE_ADV_PING   = 3,
+  DELUGE_ADV_RESET  = 4,
+};
+
+typedef nx_struct DelugeAdvMsg {
+  nx_uint16_t       sourceAddr;
+  nx_uint8_t        version;    // Deluge Version
+  nx_uint8_t        type;
+  //DelugeNodeDesc nodeDesc;
+  DelugeObjDesc  objDesc;
+  nx_uint8_t        reserved;
+} DelugeAdvMsg;
+
+typedef nx_struct DelugeReqMsg {
+  nx_uint16_t     dest;
+  nx_uint16_t     sourceAddr;
+  nx_object_id_t  objid;
+  nx_page_num_t   pgNum;
+  nx_uint8_t      requestedPkts[DELUGE_PKT_BITVEC_SIZE];
+} DelugeReqMsg;
+
+typedef nx_struct DelugeDataMsg {
+  nx_object_id_t objid;
+  nx_page_num_t pgNum;
+  nx_uint8_t    pktNum;
+  nx_uint8_t    data[DELUGE_PKT_PAYLOAD_SIZE];
+} DelugeDataMsg;
+
+#endif
diff --git a/tos/lib/net/Deluge/DelugeP.nc b/tos/lib/net/Deluge/DelugeP.nc
new file mode 100644 (file)
index 0000000..8102048
--- /dev/null
@@ -0,0 +1,140 @@
+/* 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>
+ */
+
+module DelugeP
+{
+  uses {
+    interface Leds;
+    interface Notify<uint8_t> as StorageReadyNotify;
+    interface DisseminationUpdate<DelugeDissemination>;
+    interface DisseminationValue<DelugeDissemination>;
+    interface StdControl as StdControlDissemination;
+    interface DelugeMetadata;
+    interface ObjectTransfer;
+    interface NetProg;
+    interface InternalFlash as IFlash;
+    interface SplitControl as RadioSplitControl;
+    
+#ifdef DELUGE_BASESTATION
+    interface Notify<uint8_t> as ReprogNotify;
+#endif
+  }
+}
+
+implementation
+{
+  uint8_t img_num;
+  
+  /**
+   * Starts the radio
+   */
+  event void StorageReadyNotify.notify(uint8_t val)
+  {
+    call RadioSplitControl.start();
+  }
+
+#ifdef DELUGE_BASESTATION
+  /**
+   * Starts disseminating image information
+   */
+  event void ReprogNotify.notify(uint8_t new_img_num)
+  {
+    DelugeDissemination delugeDis;
+    DelugeImgDesc *imgDesc;
+    
+    imgDesc = call DelugeMetadata.getImgDesc(new_img_num);
+    if (imgDesc->uid != DELUGE_INVALID_UID) {
+      call ObjectTransfer.stop();
+      call Leds.led0Toggle();
+      img_num = new_img_num;
+      
+      delugeDis.uid = imgDesc->uid;
+      delugeDis.vNum = imgDesc->vNum;
+      delugeDis.imgNum = imgDesc->imgNum;
+      delugeDis.size = imgDesc->size;
+      
+      call DisseminationUpdate.change(&delugeDis);   // Disseminates image information
+      call ObjectTransfer.publish(delugeDis.uid,
+                                  delugeDis.size,
+                                  delugeDis.imgNum);   // Prepares to publish image data
+    }
+  }
+#endif
+
+  /**
+   * Receives a disseminated message. If the message contains information about a
+   * newer image, then we should grab this image from the network
+   */
+  event void DisseminationValue.changed()
+  {
+    const DelugeDissemination *delugeDis = call DisseminationValue.get();
+    DelugeImgDesc *imgDesc = call DelugeMetadata.getImgDesc(delugeDis->imgNum);
+    
+    if (imgDesc->uid == delugeDis->uid) {
+      if (imgDesc->vNum < delugeDis->vNum) {
+        img_num = delugeDis->imgNum;   // Note which image number to boot
+        call ObjectTransfer.receive(delugeDis->uid, delugeDis->size, delugeDis->imgNum);
+      }
+    } else {
+      img_num = delugeDis->imgNum;   // Note which image number to boot
+      call ObjectTransfer.receive(delugeDis->uid, delugeDis->size, delugeDis->imgNum);
+    }
+  }
+
+  /**
+   * Reboots and reprograms with the newly received image
+   */
+  event void ObjectTransfer.receiveDone(error_t error)
+  {
+    call ObjectTransfer.stop();
+    if (error == SUCCESS) {
+      call NetProg.programImgAndReboot(img_num);
+    }
+  }
+
+  /**
+   * Prepares to publish the image that was just reprogrammed
+   */
+  event void RadioSplitControl.startDone(error_t error)
+  {
+    if (error == SUCCESS) {
+      // Start publishing the current image
+      DelugeImgDesc *imgDesc;
+      DelugeNodeDesc nodeDesc;
+      call IFlash.read((uint8_t*)IFLASH_NODE_DESC_ADDR,
+                       &nodeDesc,
+                       sizeof(DelugeNodeDesc));   // Reads which image was just reprogrammed
+      imgDesc = call DelugeMetadata.getImgDesc(nodeDesc.imgNum);
+      if (nodeDesc.uid == imgDesc->uid && imgDesc->uid != DELUGE_INVALID_UID) {
+        call ObjectTransfer.publish(imgDesc->uid, imgDesc->size, imgDesc->imgNum);
+      }
+            
+      call StdControlDissemination.start();
+    }
+  }
+  
+  event void RadioSplitControl.stopDone(error_t error) {}
+}
diff --git a/tos/lib/net/Deluge/DelugePageTransfer.h b/tos/lib/net/Deluge/DelugePageTransfer.h
new file mode 100644 (file)
index 0000000..cc91452
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * "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."
+ *
+ * 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>
+ */
+
+#ifndef DELUGEPAGETRANSFER_H
+#define DELUGEPAGETRANSFER_H
+
+#include "extra/telosb/TOSBoot_platform.h"
+
+#define AM_DELUGEADVMSG  161
+#define AM_DELUGEREQMSG  162
+#define AM_DELUGEDATAMSG 163
+
+typedef int32_t object_id_t;
+typedef nx_int32_t nx_object_id_t;
+typedef uint32_t object_size_t;
+typedef nx_uint32_t nx_object_size_t;
+typedef uint8_t page_num_t;
+typedef nx_uint8_t nx_page_num_t;
+
+enum {
+//  DELUGE_PKTS_PER_PAGE    = 48,
+//  DELUGE_PKT_PAYLOAD_SIZE = 23,
+//  DELUGE_BYTES_PER_PAGE   = (DELUGE_PKTS_PER_PAGE * DELUGE_PKT_PAYLOAD_SIZE),
+  DELUGE_PKT_PAYLOAD_SIZE  = TOSH_DATA_LENGTH - sizeof(nx_object_id_t) - sizeof(nx_page_num_t) - sizeof(nx_uint8_t),
+  DELUGE_BYTES_PER_PAGE    = 1024,
+  DELUGE_PKTS_PER_PAGE     = ((DELUGE_BYTES_PER_PAGE - 1) / DELUGE_PKT_PAYLOAD_SIZE) + 1,
+  
+  DELUGE_VERSION                    = 2,
+  DELUGE_MAX_ADV_PERIOD_LOG2        = 22,
+  DELUGE_NUM_NEWDATA_ADVS_REQUIRED  = 2,
+  DELUGE_NUM_MIN_ADV_PERIODS        = 2,
+  DELUGE_MAX_NUM_REQ_TRIES          = 1,
+  DELUGE_REBOOT_DELAY               = 4,
+  DELUGE_FAILED_SEND_DELAY          = 16,
+  DELUGE_MIN_DELAY                  = 16,
+  DELUGE_DATA_OFFSET                = 128,
+  DELUGE_IDENT_SIZE                 = 128,
+  DELUGE_INVALID_ADDR               = (0x7fffffffL),
+  DELUGE_MAX_REQ_DELAY              = (0x1L << (DELUGE_MIN_ADV_PERIOD_LOG2 - 1)),
+  DELUGE_NACK_TIMEOUT               = (DELUGE_MAX_REQ_DELAY >> 0x1),
+  DELUGE_PKT_BITVEC_SIZE            = (((DELUGE_PKTS_PER_PAGE - 1) / 8) + 1),
+  DELUGE_MAX_IMAGE_SIZE             = (128L * 1024L),
+  DELUGE_MAX_PAGES                  = 128,
+  DELUGE_CRC_SIZE                   = sizeof(uint16_t),
+  DELUGE_CRC_BLOCK_SIZE             = DELUGE_MAX_PAGES * DELUGE_CRC_SIZE,
+  DELUGE_GOLDEN_IMAGE_NUM           = 0x0,
+  DELUGE_INVALID_OBJID              = 0xff,
+  DELUGE_INVALID_PKTNUM             = 0xff,
+  DELUGE_INVALID_PGNUM              = 0xff,
+  
+  // From "DelugeMetadata.h"
+};
+
+typedef struct DelugeAdvTimer {
+  uint32_t timer      : 32;
+  uint8_t  periodLog2 : 8;
+  bool     overheard  : 1;
+  uint8_t  newAdvs    : 7;
+} DelugeAdvTimer;
+
+typedef nx_struct DelugeObjDesc {
+  nx_object_id_t objid;
+  nx_page_num_t  numPgs;         // num pages of complete image
+  nx_uint16_t    crc;            // crc for vNum and numPgs
+  nx_page_num_t  numPgsComplete; // numPgsComplete in image
+  nx_uint8_t     reserved;
+} DelugeObjDesc;
+
+#endif
diff --git a/tos/lib/net/Deluge/DelugePageTransfer.nc b/tos/lib/net/Deluge/DelugePageTransfer.nc
new file mode 100644 (file)
index 0000000..b2929be
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * "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."
+ *
+ * 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 "DelugePageTransfer.h"
+
+interface DelugePageTransfer {
+  command error_t setWorkingPage(object_id_t new_objid, page_num_t new_pgNum);
+  command error_t dataAvailable(uint16_t sourceAddr);
+  command bool isTransferring();
+  event void suppressMsgs(object_id_t new_objid);
+  event void receivedPage(object_id_t new_objid, page_num_t new_pgNum);
+  command void setImgNum(uint8_t new_img_num);
+  
+  command error_t stop();
+}
diff --git a/tos/lib/net/Deluge/DelugePageTransferC.nc b/tos/lib/net/Deluge/DelugePageTransferC.nc
new file mode 100644 (file)
index 0000000..b36d09e
--- /dev/null
@@ -0,0 +1,72 @@
+/* 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 DelugePageTransferC
+{
+  provides interface DelugePageTransfer;
+  uses {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    
+    interface Receive as ReceiveDataMsg;
+    interface Receive as ReceiveReqMsg;
+    interface AMSend as SendDataMsg;
+    interface AMSend as SendReqMsg;
+    interface AMPacket;
+    interface PacketAcknowledgements;
+  }
+}
+
+implementation
+{
+  components DelugePageTransferP;
+  
+  DelugePageTransfer = DelugePageTransferP;
+  BlockRead[0] = DelugePageTransferP.BlockRead[0];
+  BlockWrite[0] = DelugePageTransferP.BlockWrite[0];
+  BlockRead[1] = DelugePageTransferP.BlockRead[1];
+  BlockWrite[1] = DelugePageTransferP.BlockWrite[1];
+  
+  ReceiveDataMsg = DelugePageTransferP.ReceiveDataMsg;
+  ReceiveReqMsg = DelugePageTransferP.ReceiveReqMsg;
+  SendDataMsg = DelugePageTransferP.SendDataMsg;
+  SendReqMsg = DelugePageTransferP.SendReqMsg;
+  
+  AMPacket = DelugePageTransferP.AMPacket;
+  PacketAcknowledgements = DelugePageTransferP.PacketAcknowledgements;
+  
+  components RandomC, BitVecUtilsC, new TimerMilliC() as Timer;
+  DelugePageTransferP.Random -> RandomC;
+  DelugePageTransferP.Timer -> Timer;
+  DelugePageTransferP.BitVecUtils -> BitVecUtilsC;
+  
+  components NoLedsC, LedsC;
+  DelugePageTransferP.Leds -> LedsC;
+  
+  // For collecting statistics
+  //components StatsCollectorC;
+  //DelugePageTransferP.StatsCollector -> StatsCollectorC.StatsCollector;
+}
diff --git a/tos/lib/net/Deluge/DelugePageTransferP.nc b/tos/lib/net/Deluge/DelugePageTransferP.nc
new file mode 100644 (file)
index 0000000..c2b4074
--- /dev/null
@@ -0,0 +1,493 @@
+/*
+ * "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."
+ *
+ * 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 "DelugeMsgs.h"
+#include "BitVecUtils.h"
+
+module DelugePageTransferP
+{
+  provides interface DelugePageTransfer;
+  uses {
+    interface BitVecUtils;
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    
+    interface Receive as ReceiveDataMsg;
+    interface Receive as ReceiveReqMsg;
+    interface AMSend as SendDataMsg;
+    interface AMSend as SendReqMsg;
+    interface AMPacket;
+    interface PacketAcknowledgements;
+    interface Timer<TMilli> as Timer;
+    interface Random;
+    
+    interface Leds;
+    //interface StatsCollector;
+  }
+}
+
+implementation
+{
+  // send/receive page buffers, and state variables for buffers
+  uint8_t pktsToSend[DELUGE_PKT_BITVEC_SIZE];    // bit vec of packets to send
+  uint8_t pktsToReceive[DELUGE_PKT_BITVEC_SIZE]; // bit vec of packets to receive
+
+  DelugeDataMsg rxQueue[DELUGE_QSIZE];
+  uint8_t       head, size;
+
+  enum {
+    S_DISABLED,
+    S_IDLE,     
+    S_TX_LOCKING,
+    S_SENDING,
+    S_RX_LOCKING,
+    S_RECEIVING,
+  };
+  
+  // state variables
+  uint8_t      state        = S_DISABLED;
+  uint16_t     nodeAddr;
+  uint8_t      remainingAttempts;
+  bool         suppressReq;
+  object_id_t  objToSend    = DELUGE_INVALID_OBJID;
+  page_num_t   pageToSend   = DELUGE_INVALID_PGNUM;
+  object_id_t  workingObjid = DELUGE_INVALID_OBJID;
+  page_num_t   workingPgNum = DELUGE_INVALID_PGNUM;
+  uint8_t      imgNum       = 0;
+  
+  message_t pMsgBuf;
+  bool      isBusy_pMsgBuf = FALSE;
+  uint8_t   publisher_addr;   // For collecting stats only
+  
+  void changeState(uint8_t newState);
+  
+  void startReqTimer(bool first)
+  {
+    uint32_t delay;
+    if (first) {
+      delay = DELUGE_MIN_DELAY + (call Random.rand32() % DELUGE_MAX_REQ_DELAY);
+    } else {
+      delay = DELUGE_NACK_TIMEOUT + (call Random.rand32() % DELUGE_NACK_TIMEOUT);
+    }
+    call Timer.startOneShot(delay);
+  }
+  
+  void setupReqMsg()
+  {
+    DelugeReqMsg *pReqMsg = (DelugeReqMsg *)(call SendReqMsg.getPayload(&pMsgBuf));
+    
+    if (state == S_RX_LOCKING) {
+      if (isBusy_pMsgBuf) {
+        return;
+      }
+      isBusy_pMsgBuf = TRUE;
+      changeState(S_RECEIVING);
+      pReqMsg->dest = nodeAddr;
+      pReqMsg->sourceAddr = TOS_NODE_ID;
+      pReqMsg->objid = workingObjid;
+      pReqMsg->pgNum = workingPgNum;
+    }
+    
+    if (state != S_RECEIVING) {
+      return;
+    }
+    
+    // suppress request
+    if (suppressReq) {
+      startReqTimer(FALSE);
+      suppressReq = FALSE;
+    }
+    // tried too many times, give up
+    else if (remainingAttempts == 0) {
+      changeState(S_IDLE);
+    }
+    // send req message
+    else {
+      uint32_t i;
+      for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+        pReqMsg->requestedPkts[i] = pktsToReceive[i];
+      }
+      //memcpy(pReqMsg->requestedPkts, pktsToReceive, DELUGE_PKT_BITVEC_SIZE);
+      
+      if (call SendReqMsg.send(pReqMsg->dest, &pMsgBuf, sizeof(DelugeReqMsg)) != SUCCESS) {
+       startReqTimer(FALSE);
+      }
+    }
+  }
+  
+  storage_addr_t calcOffset(page_num_t pgNum, uint8_t pktNum)
+  {
+    return (storage_addr_t)pgNum * (storage_addr_t)DELUGE_BYTES_PER_PAGE
+            + (uint16_t)pktNum * (uint16_t)DELUGE_PKT_PAYLOAD_SIZE;
+            //+ DELUGE_METADATA_SIZE;
+  }
+  
+  void setupDataMsg()
+  {
+    DelugeDataMsg *pDataMsg = (DelugeDataMsg *)(call SendDataMsg.getPayload(&pMsgBuf));
+    uint16_t nextPkt;
+    
+    if (state != S_SENDING && state != S_TX_LOCKING) {
+      return;
+    }
+    
+    signal DelugePageTransfer.suppressMsgs(objToSend);
+    
+    if (state == S_TX_LOCKING) {
+      if (isBusy_pMsgBuf) {
+        return;
+      }
+      isBusy_pMsgBuf = TRUE;
+      changeState(S_SENDING);
+      pDataMsg->objid = objToSend;
+      pDataMsg->pgNum = pageToSend;
+      pDataMsg->pktNum = 0;
+    }
+    
+    if (call BitVecUtils.indexOf(&nextPkt, pDataMsg->pktNum, pktsToSend, DELUGE_PKTS_PER_PAGE) != SUCCESS) {
+      // no more packets to send
+      //dbg(DBG_USR1, "DELUGE: SEND_DONE\n");
+      changeState(S_IDLE);
+    } else {
+      pDataMsg->pktNum = nextPkt;
+      if (call BlockRead.read[imgNum](calcOffset(pageToSend, nextPkt), pDataMsg->data, DELUGE_PKT_PAYLOAD_SIZE) != SUCCESS) {
+        call Timer.startOneShot(DELUGE_FAILED_SEND_DELAY);
+      }
+    }
+  }
+  
+  void unlockPMsgBuf()
+  {
+    isBusy_pMsgBuf = FALSE;
+    
+    switch(state) {
+      case S_TX_LOCKING:
+        setupDataMsg();
+        break;
+      case S_RX_LOCKING:
+        setupReqMsg();
+        break;
+    }
+  }
+  
+  void changeState(uint8_t newState)
+  {
+    if ((newState == S_DISABLED || newState == S_IDLE)
+       && (state == S_SENDING || state == S_RECEIVING)) {
+      unlockPMsgBuf();
+    }
+    
+    state = newState;
+  }
+  
+  void suppressMsgs(object_id_t objid, page_num_t pgNum)
+  {
+    if (state == S_SENDING || state == S_TX_LOCKING) {
+      if (objid < objToSend || (objid == objToSend && pgNum < pageToSend)) {
+       uint32_t i;
+       changeState(S_IDLE);
+       for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+          pktsToSend[i] = 0x00;
+       }
+       //memset(pktsToSend, 0x00, DELUGE_PKT_BITVEC_SIZE);
+      }
+    } else if (state == S_RECEIVING || state == S_RX_LOCKING) {
+      if (objid < workingObjid || (objid == workingObjid && pgNum <= workingPgNum)) {
+       // suppress next request since similar request has been overheard
+       suppressReq = TRUE;
+      }
+    }
+  }
+  
+  void writeData()
+  {
+    if(call BlockWrite.write[imgNum](calcOffset(rxQueue[head].pgNum, rxQueue[head].pktNum),
+                            rxQueue[head].data, DELUGE_PKT_PAYLOAD_SIZE) != SUCCESS) {
+      size = 0;
+    }
+  }
+  
+  command error_t DelugePageTransfer.stop()
+  {
+    uint32_t i;
+    
+    call Timer.stop();
+    changeState(S_DISABLED);
+    workingObjid = DELUGE_INVALID_OBJID;
+    workingPgNum = DELUGE_INVALID_PGNUM;
+    
+    for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+      pktsToReceive[i] = 0x00;
+    }
+    for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+      pktsToSend[i] = 0x00;
+    }
+    //memset(pktsToReceive, 0x00, DELUGE_PKT_BITVEC_SIZE);
+    //memset(pktsToSend, 0x00, DELUGE_PKT_BITVEC_SIZE);
+    
+    return SUCCESS;
+  }
+  
+  command error_t DelugePageTransfer.setWorkingPage(object_id_t new_objid, page_num_t new_pgNum)
+  {
+    uint32_t i;
+    
+    if (state == S_DISABLED) {
+      changeState(S_IDLE);
+    }
+    
+    workingObjid = new_objid;
+    workingPgNum = new_pgNum;
+    
+    for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+      pktsToReceive[i] = 0xFF;
+    }
+    //memset(pktsToReceive, (nx_uint8_t)0xff, DELUGE_PKT_BITVEC_SIZE);
+    
+    return SUCCESS;
+  }
+  
+  command bool DelugePageTransfer.isTransferring()
+  {
+    return (state != S_IDLE && state != S_DISABLED);
+  }
+  
+  command error_t DelugePageTransfer.dataAvailable(uint16_t sourceAddr)
+  {
+    if (state == S_IDLE) {
+      // currently idle, so request data from source
+      changeState(S_RX_LOCKING);
+      nodeAddr = sourceAddr;
+      remainingAttempts = DELUGE_MAX_NUM_REQ_TRIES;
+      suppressReq = FALSE;
+      
+      // randomize request to prevent collision
+      startReqTimer(TRUE);
+    }
+    
+    return SUCCESS;
+  }
+  
+  event void Timer.fired()
+  {
+    setupReqMsg();
+    setupDataMsg();
+  }
+  
+  event void SendReqMsg.sendDone(message_t* msg, error_t error)
+  {
+    if (state != S_RECEIVING) {
+      return;
+    }
+    
+    remainingAttempts--;
+    // start timeout timer in case request is not serviced
+    startReqTimer(FALSE);
+  }
+  
+  event message_t* ReceiveReqMsg.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    DelugeReqMsg *rxReqMsg = (DelugeReqMsg*)payload;
+    object_id_t objid;
+    page_num_t pgNum;
+    int i;
+    
+    //dbg(DBG_USR1, "DELUGE: Received REQ_MSG(dest=%d,vNum=%d,imgNum=%d,pgNum=%d,pkts=%x)\n",
+    //    rxReqMsg->dest, rxReqMsg->vNum, rxReqMsg->imgNum, rxReqMsg->pgNum, rxReqMsg->requestedPkts[0]);
+    
+    if (state == S_DISABLED) {
+      return msg;
+    }
+    
+    objid = rxReqMsg->objid;
+    pgNum = rxReqMsg->pgNum;
+    
+    // check if need to suppress req or data msgs
+    suppressMsgs(objid, pgNum);
+    
+    // if not for me, ignore request
+    if (rxReqMsg->dest != TOS_NODE_ID
+        || objid != workingObjid
+       || pgNum >= workingPgNum) {
+      return msg;
+    }
+    
+    if (state == S_IDLE
+       || ((state == S_SENDING || state == S_TX_LOCKING)
+           && objid == objToSend
+           && pgNum == pageToSend)) {
+      // take union of packet bit vectors
+      for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+        pktsToSend[i] |= rxReqMsg->requestedPkts[i];
+      }
+    }
+    
+    if (state == S_IDLE) {
+      // not currently sending, so start sending data
+      changeState(S_TX_LOCKING);
+      objToSend = objid;
+      pageToSend = pgNum;
+      nodeAddr = AM_BROADCAST_ADDR;
+      setupDataMsg();
+    }
+    
+    return msg;
+  }
+  
+  event void SendDataMsg.sendDone(message_t* msg, error_t error)
+  {
+    DelugeDataMsg *pDataMsg = (DelugeDataMsg *)(call SendDataMsg.getPayload(&pMsgBuf));
+    BITVEC_CLEAR(pktsToSend, pDataMsg->pktNum);
+    call Timer.startOneShot(2);
+    
+// For collecting stats
+if (error == SUCCESS) {
+  //call StatsCollector.endPubPktTransTime();
+}
+  }
+  
+  event message_t* ReceiveDataMsg.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    DelugeDataMsg* rxDataMsg = (DelugeDataMsg*)payload;
+    
+    if (state == S_DISABLED) {
+      return msg;
+    }
+    
+    //dbg(DBG_USR1, "DELUGE: Received DATA_MSG(vNum=%d,imgNum=%d,pgNum=%d,pktNum=%d)\n",
+    //    rxDataMsg->vNum, rxDataMsg->imgNum, rxDataMsg->pgNum, rxDataMsg->pktNum);
+    
+    // check if need to suppress req or data messages
+    suppressMsgs(rxDataMsg->objid, rxDataMsg->pgNum);
+    
+    if (rxDataMsg->objid == workingObjid
+       && rxDataMsg->pgNum == workingPgNum
+       && BITVEC_GET(pktsToReceive, rxDataMsg->pktNum)
+       && size < DELUGE_QSIZE) {
+      // got a packet we need
+      
+// For collecting stats
+if (rxDataMsg->pktNum == 0) {
+  //call StatsCollector.startRecvPageTransTime(0);
+  dbg("Deluge", "%.3f 115 116 116 117 115 1 %d\n", ((float)((sim_time() * 1000) / sim_ticks_per_sec())) / 1000, CC2420_DEF_CHANNEL);
+}
+call Leds.led1Toggle();
+//call Leds.set(rxDataMsg->pktNum);
+      
+      //dbg(DBG_USR1, "DELUGE: SAVING(pgNum=%d,pktNum=%d)\n", 
+      //    rxDataMsg->pgNum, rxDataMsg->pktNum);
+      
+      // copy data
+      memcpy(&rxQueue[head^size], rxDataMsg, sizeof(DelugeDataMsg));
+      if (++size == 1) {
+        publisher_addr = call AMPacket.source(msg);   // For collecting stats
+       writeData();
+      }
+    }
+    
+    return msg;
+  }
+  
+  event void BlockRead.readDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    DelugeDataMsg *pDataMsg = (DelugeDataMsg *)(call SendDataMsg.getPayload(&pMsgBuf));
+    // make sure this event for us
+    if (buf != pDataMsg->data) {
+      return;
+    }
+    
+    if (state != S_SENDING) {
+      return;
+    }
+    
+    if (error != SUCCESS) {
+      changeState(S_IDLE);
+      return;
+    }
+    
+    if (call SendDataMsg.send(nodeAddr, &pMsgBuf, sizeof(DelugeDataMsg)) != SUCCESS) {
+      call Timer.startOneShot(DELUGE_FAILED_SEND_DELAY);
+    } else {
+// For collecting stats
+//call StatsCollector.startPubPktTransTime();
+//call Leds.led1Toggle();
+    }
+  }
+  
+  event void BlockRead.computeCrcDone[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) { }
+  
+  event void BlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    uint16_t tmp;
+    
+    // make sure this event for us
+    if (buf != rxQueue[head].data) {
+      return;
+    }
+    
+    // failed to write
+    if (error != SUCCESS) {
+      uint32_t i;
+      for (i = 0; i < DELUGE_PKT_BITVEC_SIZE; i++) {
+        pktsToReceive[i] = 0xFF;
+      }
+      size = 0;
+      return;
+    }
+    
+    // mark packet as received
+    BITVEC_CLEAR(pktsToReceive, rxQueue[head].pktNum);
+    head = (head + 1) % DELUGE_QSIZE;
+    size--;
+    
+    if (call BitVecUtils.indexOf(&tmp, 0, pktsToReceive, DELUGE_PKTS_PER_PAGE) != SUCCESS) {
+// For collecting stats
+//call StatsCollector.endRecvPageTransTime(publisher_addr);
+dbg("Deluge", "%.3f 115 116 116 117 115 2 %d\n", ((float)((sim_time() * 1000) / sim_ticks_per_sec())) / 1000, publisher_addr);
+
+      signal DelugePageTransfer.receivedPage(workingObjid, workingPgNum);
+      changeState(S_IDLE);
+      size = 0;
+    } else if (size) {
+      writeData();
+    }
+  }
+  
+  event void BlockWrite.eraseDone[uint8_t img_num](error_t error) {}
+  event void BlockWrite.syncDone[uint8_t img_num](error_t error) {}
+  
+  command void DelugePageTransfer.setImgNum(uint8_t new_img_num)
+  {
+    imgNum = new_img_num;
+  }
+  
+  default command error_t BlockRead.read[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockWrite.write[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+}
diff --git a/tos/lib/net/Deluge/DelugeStorageC.nc b/tos/lib/net/Deluge/DelugeStorageC.nc
new file mode 100644 (file)
index 0000000..31f7635
--- /dev/null
@@ -0,0 +1,65 @@
+/* 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>
+ */
+
+#include "StorageVolumes.h"
+
+configuration DelugeStorageC
+{
+  provides {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    interface StorageMap[uint8_t img_num];
+    interface DelugeMetadata;
+    
+    interface Notify<uint8_t>;
+  }
+}
+
+implementation
+{
+  components new BlockStorageC(VOLUME_DELUGE0) as BlockStorageC_0;
+  components new BlockStorageC(VOLUME_DELUGE1) as BlockStorageC_1;
+  components DelugeStorageP;
+
+  BlockRead[0] = DelugeStorageP.BlockRead[0];
+  BlockWrite[0] = DelugeStorageP.BlockWrite[0];
+  StorageMap[0] = BlockStorageC_0;
+  BlockRead[1] = DelugeStorageP.BlockRead[1];
+  BlockWrite[1] = DelugeStorageP.BlockWrite[1];
+  StorageMap[1] = BlockStorageC_1;
+  DelugeMetadata = DelugeStorageP.DelugeMetadata;
+
+  DelugeStorageP.SubBlockRead[0] -> BlockStorageC_0;
+  DelugeStorageP.SubBlockWrite[0] -> BlockStorageC_0;
+  DelugeStorageP.SubBlockRead[1] -> BlockStorageC_1;
+  DelugeStorageP.SubBlockWrite[1] -> BlockStorageC_1;
+  
+  components LedsC, MainC;
+  DelugeStorageP.Leds -> LedsC;
+  DelugeStorageP.Boot -> MainC;
+  
+  Notify = DelugeStorageP.Notify;
+}
diff --git a/tos/lib/net/Deluge/DelugeStorageP.nc b/tos/lib/net/Deluge/DelugeStorageP.nc
new file mode 100644 (file)
index 0000000..2bdb5f0
--- /dev/null
@@ -0,0 +1,188 @@
+/* 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>
+ */
+
+#include "Deluge.h"
+
+module DelugeStorageP
+{
+  uses {
+    interface BlockRead as SubBlockRead[uint8_t img_num];
+    interface BlockWrite as SubBlockWrite[uint8_t img_num];
+    interface Boot;
+    interface Leds;
+  }
+  provides {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    interface DelugeMetadata;
+    
+    interface Notify<uint8_t>;
+  }
+}
+
+implementation
+{
+  enum {
+    S_INIT,
+    S_READY,
+  };
+
+  uint8_t state = S_INIT;
+  uint8_t last_init_img_num = 0;
+  DelugeImgDesc imgDesc[DELUGE_NUM_VOLUMES];
+
+  event void Boot.booted()
+  {
+    uint32_t i;
+    for (i = 0; i < DELUGE_NUM_VOLUMES; i++) {
+      imgDesc[i].uid = DELUGE_INVALID_UID;
+      imgDesc[i].vNum = 0;
+      imgDesc[i].imgNum = 0;
+      imgDesc[i].numPgs = 0;
+      imgDesc[i].crc = 0;
+      imgDesc[i].numPgsComplete = 0;
+      imgDesc[i].reserved = 0;
+      imgDesc[i].size = 0;
+    }
+    
+    // Reads image descriptions
+    state = S_INIT;
+    if (DELUGE_NUM_VOLUMES > 0) {
+      call SubBlockRead.read[last_init_img_num](0, &(imgDesc[last_init_img_num]), sizeof(DelugeImgDesc));
+    }
+  }
+
+  command DelugeImgDesc* DelugeMetadata.getImgDesc(imgnum_t imgNum)
+  {
+    return &(imgDesc[imgNum]);
+  }
+
+  // SubBlockRead commands
+  command error_t BlockRead.read[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len)
+  {
+    return call SubBlockRead.read[img_num](addr, buf, len);
+  }
+
+  command error_t BlockRead.computeCrc[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc)
+  {
+    return call SubBlockRead.computeCrc[img_num](addr, len, crc);
+  }
+
+  command storage_len_t BlockRead.getSize[uint8_t img_num]()
+  {
+    return call SubBlockRead.getSize[img_num]();
+  }
+
+  // BlockRead events
+  event void SubBlockRead.readDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    if (state == S_READY) {
+      signal BlockRead.readDone[img_num](addr, buf, len, error);
+    } else {
+      // Continues reading image descriptions
+      if (error == SUCCESS) {
+        last_init_img_num++;
+        if (last_init_img_num >= DELUGE_NUM_VOLUMES) {
+          signal Notify.notify(SUCCESS);
+          state = S_READY;
+        } else {
+          call SubBlockRead.read[last_init_img_num](0, &(imgDesc[last_init_img_num]), sizeof(DelugeImgDesc));
+        }
+      }
+    }
+  }
+
+  event void SubBlockRead.computeCrcDone[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error)
+  {
+    signal BlockRead.computeCrcDone[img_num](addr, len, crc, error);
+  }
+
+  // SubBlockWrite commands
+  command error_t BlockWrite.write[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len)
+  {
+    return call SubBlockWrite.write[img_num](addr, buf, len);
+  }
+
+  command error_t BlockWrite.erase[uint8_t img_num]()
+  {
+    return call SubBlockWrite.erase[img_num]();
+  }
+
+  command error_t BlockWrite.sync[uint8_t img_num]()
+  {
+    return call SubBlockWrite.sync[img_num]();
+  }
+
+  // BlockWrite events
+  event void SubBlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    if (error == SUCCESS) {
+      if (addr < sizeof(DelugeImgDesc)) {
+        memcpy((char*)&(imgDesc[img_num]) + addr, buf, sizeof(DelugeImgDesc) - addr);
+      }
+    }
+    
+    signal BlockWrite.writeDone[img_num](addr, buf, len, error);
+  }
+
+  event void SubBlockWrite.eraseDone[uint8_t img_num](error_t error)
+  {
+    if (error == SUCCESS) {
+      // Successful erase triggers resetting the cached image description
+      imgDesc[img_num].uid = DELUGE_INVALID_UID;
+      imgDesc[img_num].vNum = 0;
+      imgDesc[img_num].imgNum = 0;
+      imgDesc[img_num].numPgs = 0;
+      imgDesc[img_num].crc = 0;
+      imgDesc[img_num].numPgsComplete = 0;
+      imgDesc[img_num].reserved = 0;
+      imgDesc[img_num].size = 0;
+    }
+    
+    signal BlockWrite.eraseDone[img_num](error);
+  }
+
+  event void SubBlockWrite.syncDone[uint8_t img_num](error_t error)
+  {
+    signal BlockWrite.syncDone[img_num](error);
+  }
+
+  default event void BlockRead.readDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  default event void BlockRead.computeCrcDone[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+  default event void BlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  default event void BlockWrite.eraseDone[uint8_t img_num](error_t error) {}
+  default event void BlockWrite.syncDone[uint8_t img_num](error_t error) {}
+  
+  default command error_t SubBlockWrite.write[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t SubBlockWrite.erase[uint8_t img_num]() { return FAIL; }
+  default command error_t SubBlockWrite.sync[uint8_t img_num]() { return FAIL; }
+  default command error_t SubBlockRead.read[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t SubBlockRead.computeCrc[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+  default command storage_len_t SubBlockRead.getSize[uint8_t img_num]() { return 0; }
+  
+  command error_t Notify.enable() { return SUCCESS; }
+  command error_t Notify.disable() { return SUCCESS; }
+}
diff --git a/tos/lib/net/Deluge/FakeBlockReaderC.nc b/tos/lib/net/Deluge/FakeBlockReaderC.nc
new file mode 100644 (file)
index 0000000..117b118
--- /dev/null
@@ -0,0 +1,95 @@
+/* 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>
+ */
+
+generic module FakeBlockReaderC(uint32_t size)
+{
+  provides interface BlockRead;
+}
+
+implementation
+{
+  enum {
+    S_IDLE,
+    S_BUSY
+  };
+
+  storage_addr_t saddr;
+  uint8_t *oribuf;
+  uint8_t *sbuf;
+  storage_len_t slen;
+  uint8_t state = S_IDLE;
+
+  task void task_read()
+  {
+    while (slen > 0) {
+      *sbuf = saddr & 0xFF;
+      saddr++;
+      sbuf++;
+      slen--;
+    }
+
+    signal BlockRead.readDone(saddr, oribuf, slen, SUCCESS);
+    state = S_IDLE;
+  }
+
+  command error_t BlockRead.read(storage_addr_t addr,
+                                void* buf,
+                                storage_len_t len)
+  {
+    if (state != S_IDLE) {
+      return FAIL;
+    }
+
+
+    state = S_BUSY;
+    saddr = addr;
+    sbuf = buf;
+    oribuf = buf;
+    slen = len;
+    post task_read();
+    return SUCCESS;
+  };
+
+  task void task_computeCRC()
+  {
+    signal BlockRead.computeCrcDone(saddr, slen, 0, SUCCESS);
+  }
+
+  command error_t BlockRead.computeCrc(storage_addr_t addr,
+                                      storage_len_t len,
+                                      uint16_t crc)
+  {
+    saddr = addr;
+    slen = len;
+    post task_computeCRC();
+    return SUCCESS;
+  }
+
+  command storage_len_t BlockRead.getSize()
+  {
+    return size;
+  }
+}
diff --git a/tos/lib/net/Deluge/FakeBlockWriterC.nc b/tos/lib/net/Deluge/FakeBlockWriterC.nc
new file mode 100644 (file)
index 0000000..dfdb1f6
--- /dev/null
@@ -0,0 +1,39 @@
+/* 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>
+ */
+
+generic configuration FakeBlockWriterC(uint32_t size)
+{
+  provides interface BlockWrite;
+}
+
+implementation
+{
+  components LedsC, NoLedsC,
+             new FakeBlockWriterP(size);
+  
+  BlockWrite = FakeBlockWriterP;
+  FakeBlockWriterP.Leds -> NoLedsC;
+}
diff --git a/tos/lib/net/Deluge/FakeBlockWriterP.nc b/tos/lib/net/Deluge/FakeBlockWriterP.nc
new file mode 100644 (file)
index 0000000..0e1d946
--- /dev/null
@@ -0,0 +1,102 @@
+/* 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>
+ */
+
+generic module FakeBlockWriterP(uint32_t size)
+{
+  provides interface BlockWrite;
+  uses interface Leds;
+}
+
+implementation
+{
+  enum {
+    S_IDLE,
+    S_BUSY
+  };
+  
+  storage_addr_t saddr;
+  uint8_t *oribuf;
+  uint8_t *sbuf;
+  storage_len_t slen;
+  uint8_t state;
+  
+  task void task_write()
+  {
+    error_t error = SUCCESS;
+    
+    while (slen > 0) {
+      if (*sbuf != (saddr & 0xFF)) {
+        error = FAIL;
+call Leds.led2Toggle();
+      }
+      saddr++;
+      sbuf++;
+      slen--;
+    }
+    
+    signal BlockWrite.writeDone(saddr, oribuf, slen, error);
+    state = S_IDLE;
+  }
+  
+  command error_t BlockWrite.write(storage_addr_t addr,
+                                  void* buf,
+                                  storage_len_t len)
+  {
+    if (state != S_IDLE) {
+      return FAIL;
+    }
+    
+    state = S_BUSY;
+    saddr = addr;
+    sbuf = buf;
+    oribuf = buf;
+    slen = len;
+    post task_write();
+    return SUCCESS;
+  }
+  
+  task void task_erase()
+  {
+    signal BlockWrite.eraseDone(SUCCESS);
+  }
+  
+  command error_t BlockWrite.erase()
+  {
+    post task_erase();
+    return SUCCESS;
+  }
+  
+  task void task_sync()
+  {
+    signal BlockWrite.syncDone(SUCCESS);
+  }
+  
+  command error_t BlockWrite.sync()
+  {
+    post task_sync();
+    return SUCCESS;
+  }
+}
diff --git a/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManager.h b/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManager.h
new file mode 100644 (file)
index 0000000..5c0a597
--- /dev/null
@@ -0,0 +1,54 @@
+/* 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 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_REPROG 5
+#define SERIALMSG_DISS   6
+
+typedef nx_struct SerialReqPacket {
+  nx_uint8_t msg_type;
+  nx_uint8_t img_num;
+  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 data[0];
+} SerialReplyPacket;
+
+#endif
diff --git a/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerC.nc b/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerC.nc
new file mode 100644 (file)
index 0000000..b8a25f1
--- /dev/null
@@ -0,0 +1,65 @@
+/* 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>
+ */
+
+#include "AM.h"
+
+generic configuration FlashVolumeManagerC(am_id_t AMId)
+{
+#ifdef DELUGE  
+  provides interface Notify<uint8_t>;
+#endif
+  uses {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    interface StorageMap[uint8_t img_num];
+  }
+}
+
+implementation
+{
+  components new SerialAMSenderC(AMId),
+             new SerialAMReceiverC(AMId),
+             new FlashVolumeManagerP(),
+             NoLedsC, LedsC;
+  
+  FlashVolumeManagerP.BlockRead[0] = BlockRead[0];
+  FlashVolumeManagerP.BlockWrite[0] = BlockWrite[0];
+  FlashVolumeManagerP.StorageMap[0] = StorageMap[0];
+  FlashVolumeManagerP.BlockRead[1] = BlockRead[1];
+  FlashVolumeManagerP.BlockWrite[1] = BlockWrite[1];
+  FlashVolumeManagerP.StorageMap[1] = StorageMap[1];
+  FlashVolumeManagerP.SerialAMSender -> SerialAMSenderC;
+  FlashVolumeManagerP.SerialAMReceiver -> SerialAMReceiverC;
+  FlashVolumeManagerP.Leds -> NoLedsC;
+
+#ifdef DELUGE  
+  components NetProgC, new TimerMilliC();
+  FlashVolumeManagerP.NetProg -> NetProgC;
+  FlashVolumeManagerP.Timer -> TimerMilliC;
+  
+  Notify = FlashVolumeManagerP.Notify;
+#endif
+}
diff --git a/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerP.nc b/tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerP.nc
new file mode 100644 (file)
index 0000000..f31c716
--- /dev/null
@@ -0,0 +1,209 @@
+/* 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>
+ */
+
+#include "FlashVolumeManager.h"
+
+generic module FlashVolumeManagerP()
+{
+#ifdef DELUGE
+  provides interface Notify<uint8_t>;
+#endif
+  uses {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    interface StorageMap[uint8_t img_num];
+    interface AMSend as SerialAMSender;
+    interface Receive as SerialAMReceiver;
+    interface Leds;
+#ifdef DELUGE
+    interface NetProg;
+    interface Timer<TMilli> as Timer;
+#endif
+  }
+}
+
+implementation
+{
+  // States for keeping track of split-phase events
+  enum {
+    S_IDLE,
+    S_ERASE,
+    S_WRITE,
+    S_READ,
+    S_CRC,
+    S_REPROG,
+  };
+  
+  message_t serialMsg;
+  uint8_t buffer[TOSH_DATA_LENGTH];   // Temporary buffer for "write" operation
+  uint8_t img_num_reboot = 0xFF;       // Image number to reprogram
+  uint8_t state = S_IDLE;              // Manager state for multiplexing "done" events
+  
+  /**
+   * Replies to the PC request with operation results
+   */
+  void sendReply(error_t error, storage_len_t len)
+  {
+    SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg);
+    if (error == SUCCESS) {
+      srpkt->error = SERIALMSG_SUCCESS;
+    } else {
+      srpkt->error = SERIALMSG_FAIL;
+    }
+    call SerialAMSender.send(AM_BROADCAST_ADDR, &serialMsg, len);
+  }
+  
+  event void BlockRead.readDone[uint8_t img_num](storage_addr_t addr, 
+                               void* buf, 
+                               storage_len_t len, 
+                               error_t error)
+  {
+    if (state == S_READ) {
+      SerialReplyPacket *serialMsg_payload = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg);
+      if (buf == serialMsg_payload->data) {
+        state = S_IDLE;
+        sendReply(error, len + sizeof(SerialReplyPacket));
+      }
+    }
+  }
+  
+  event void BlockRead.computeCrcDone[uint8_t img_num](storage_addr_t addr, 
+                                     storage_len_t len, 
+                                     uint16_t crc, 
+                                     error_t error)
+  {
+    if (state == S_CRC) {
+      state = S_IDLE;
+      
+      if (error == SUCCESS) {
+        SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg);
+        srpkt->data[1] = crc & 0xFF;
+        srpkt->data[0] = (crc >> 8) & 0xFF;
+      }
+      sendReply(error, 2 + sizeof(SerialReplyPacket));
+    }
+  }
+  
+  event void BlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, 
+                                 void* buf, 
+                                 storage_len_t len, 
+                                 error_t error)
+  {
+    if (state == S_WRITE && buf == buffer) {
+      state = S_IDLE;
+      sendReply(error, sizeof(SerialReplyPacket));
+    }
+  }
+  
+  event void BlockWrite.eraseDone[uint8_t img_num](error_t error)
+  {
+    if (state == S_ERASE) {
+      state = S_IDLE;
+      sendReply(error, sizeof(SerialReplyPacket));
+    }
+  }
+  
+  event void BlockWrite.syncDone[uint8_t img_num](error_t error) {}
+  
+  event void SerialAMSender.sendDone(message_t* msg, error_t error) {}
+  
+  event message_t* SerialAMReceiver.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    error_t error = SUCCESS;
+    SerialReqPacket *srpkt = (SerialReqPacket *)payload;
+    SerialReplyPacket *serialMsg_payload =
+                              (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg);
+    
+    switch (srpkt->msg_type) {
+      case SERIALMSG_ERASE:    // === Erases a volume ===
+        state = S_ERASE;
+        error = call BlockWrite.erase[srpkt->img_num]();
+        break;
+      case SERIALMSG_WRITE:    // === Writes to a volume ===
+        state = S_WRITE;
+        memcpy(buffer, srpkt->data, srpkt->len);
+        error = call BlockWrite.write[srpkt->img_num](srpkt->offset,
+                                                      buffer,
+                                                      srpkt->len);
+        break;
+      case SERIALMSG_READ:     // === Reads a portion of a volume ===
+        state = S_READ;
+        error = call BlockRead.read[srpkt->img_num](srpkt->offset,
+                                                    serialMsg_payload->data,
+                                                    srpkt->len);
+        break;
+      case SERIALMSG_CRC:      // === Computes CRC over a portion of a volume ===
+        state = S_CRC;
+        error = call BlockRead.computeCrc[srpkt->img_num](srpkt->offset,
+                                                          srpkt->len, 0);
+        break;
+      case SERIALMSG_ADDR:     // === Gets the physical starting address of a volume ===
+       *(nx_uint32_t*)(&serialMsg_payload->data) =
+                             (uint32_t)call StorageMap.getPhysicalAddress[srpkt->img_num](0);
+       sendReply(SUCCESS, sizeof(SerialReplyPacket) + 4);
+        break;
+#ifdef DELUGE
+      case SERIALMSG_REPROG:   // === Reboots and reprograms ===
+        state = S_REPROG;
+        sendReply(SUCCESS, sizeof(SerialReplyPacket));
+        img_num_reboot = srpkt->img_num;
+       call Timer.startOneShot(1024);
+       break;
+      case SERIALMSG_DISS:     // === Starts disseminating a volume ===
+       signal Notify.notify(srpkt->img_num);   // Notifies Deluge to start disseminate
+       sendReply(SUCCESS, sizeof(SerialReplyPacket));
+       break;
+#endif
+    }
+    
+    // If a split-phase operation fails when being requested, signals the failure now
+    if (error != SUCCESS) {
+      state = S_IDLE;
+      sendReply(error, sizeof(SerialReplyPacket));
+    }
+    
+    return msg;
+  }
+
+#ifdef DELUGE
+  event void Timer.fired()
+  {
+    // Reboots and reprograms
+    call NetProg.programImgAndReboot(img_num_reboot);
+  }
+  
+  command error_t Notify.enable() { return SUCCESS; }
+  command error_t Notify.disable() { return SUCCESS; }
+#endif
+
+  default command error_t BlockWrite.write[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockWrite.erase[uint8_t img_num]() { return FAIL; }
+  default command error_t BlockWrite.sync[uint8_t img_num]() { return FAIL; }
+  default command error_t BlockRead.read[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockRead.computeCrc[uint8_t img_num](storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+
+  default command storage_addr_t StorageMap.getPhysicalAddress[uint8_t img_num](storage_addr_t addr) { return 0; }
+}
diff --git a/tos/lib/net/Deluge/Globals.nc b/tos/lib/net/Deluge/Globals.nc
new file mode 100644 (file)
index 0000000..685dd64
--- /dev/null
@@ -0,0 +1,57 @@
+/* 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>
+ */
+
+interface Globals
+{
+  command uint32_t getNumPubPktTrans();
+  command void setNumPubPktTrans(uint32_t val);
+  command void incNumPubPktTrans();
+
+  command uint32_t getNumRecvPageTrans();
+  command void setNumRecvPageTrans(uint32_t val);
+  command void incNumRecvPageTrans();
+
+  command uint32_t getAvgPubPktTransTime();
+  command void setAvgPubPktTransTime(uint32_t val);
+
+  command uint32_t getAvgRecvPageTransTime();
+  command void setAvgRecvPageTransTime(uint32_t val);
+
+  command uint32_t getNumPubPktRetrans();
+  command void setNumPubPktRetrans(uint32_t val);
+  command void incNumPubPktRetrans();
+
+  command uint32_t getNumPubHSRetrans();
+  command void setNumPubHSRetrans(uint32_t val);
+  command void incNumPubHSRetrans();
+
+  command uint32_t getNumRecvHSRetrans();
+  command void setNumRecvHSRetrans(uint32_t val);
+  command void incNumRecvHSRetrans();
+
+  command void* _getStartAddr();
+  command uint32_t _getSize();
+}
diff --git a/tos/lib/net/Deluge/GlobalsC.nc b/tos/lib/net/Deluge/GlobalsC.nc
new file mode 100644 (file)
index 0000000..5dde948
--- /dev/null
@@ -0,0 +1,72 @@
+/* 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>
+ */
+
+module GlobalsC
+{
+  provides interface Globals;
+}
+
+implementation
+{
+  struct {
+    uint32_t NumPubPktTrans;
+    uint32_t NumRecvPageTrans;
+    uint32_t AvgPubPktTransTime;
+    uint32_t AvgRecvPageTransTime;
+    uint32_t NumPubPktRetrans;
+    uint32_t NumPubHSRetrans;
+    uint32_t NumRecvHSRetrans;
+  } _g = {0, 0, 0, 0, 0, 0, 0};
+
+  command uint32_t Globals.getNumPubPktTrans() { return _g.NumPubPktTrans; }
+  command void Globals.setNumPubPktTrans(uint32_t val) { _g.NumPubPktTrans = val; }
+  command void Globals.incNumPubPktTrans() { _g.NumPubPktTrans++; }
+
+  command uint32_t Globals.getNumRecvPageTrans() { return _g.NumRecvPageTrans; }
+  command void Globals.setNumRecvPageTrans(uint32_t val) { _g.NumRecvPageTrans = val; }
+  command void Globals.incNumRecvPageTrans() { _g.NumRecvPageTrans++; }
+
+  command uint32_t Globals.getAvgPubPktTransTime() { return _g.AvgPubPktTransTime; }
+  command void Globals.setAvgPubPktTransTime(uint32_t val) { _g.AvgPubPktTransTime = val; }
+
+  command uint32_t Globals.getAvgRecvPageTransTime() { return _g.AvgRecvPageTransTime; }
+  command void Globals.setAvgRecvPageTransTime(uint32_t val) { _g.AvgRecvPageTransTime = val; }
+
+  command uint32_t Globals.getNumPubPktRetrans() { return _g.NumPubPktRetrans; }
+  command void Globals.setNumPubPktRetrans(uint32_t val) { _g.NumPubPktRetrans = val; }
+  command void Globals.incNumPubPktRetrans() { _g.NumPubPktRetrans++; }
+
+  command uint32_t Globals.getNumPubHSRetrans() { return _g.NumPubHSRetrans; }
+  command void Globals.setNumPubHSRetrans(uint32_t val) { _g.NumPubHSRetrans = val; }
+  command void Globals.incNumPubHSRetrans() { _g.NumPubHSRetrans++; }
+
+  command uint32_t Globals.getNumRecvHSRetrans() { return _g.NumRecvHSRetrans; }
+  command void Globals.setNumRecvHSRetrans(uint32_t val) { _g.NumRecvHSRetrans = val; }
+  command void Globals.incNumRecvHSRetrans() { _g.NumRecvHSRetrans++; }
+
+  command void* Globals._getStartAddr() { return &_g; }
+  command uint32_t Globals._getSize() { return sizeof(_g); }
+}
diff --git a/tos/lib/net/Deluge/ObjectTransfer.nc b/tos/lib/net/Deluge/ObjectTransfer.nc
new file mode 100644 (file)
index 0000000..e2d6be3
--- /dev/null
@@ -0,0 +1,36 @@
+/* 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>
+ */
+
+#include "DelugePageTransfer.h"
+
+interface ObjectTransfer
+{
+  command error_t publish(object_id_t new_objid, object_size_t new_size, uint8_t img_num);
+  command error_t receive(object_id_t new_objid, object_size_t new_size, uint8_t img_num);
+  event void receiveDone(error_t error);
+
+  command error_t stop();
+}
diff --git a/tos/lib/net/Deluge/ObjectTransferC.nc b/tos/lib/net/Deluge/ObjectTransferC.nc
new file mode 100644 (file)
index 0000000..9db303e
--- /dev/null
@@ -0,0 +1,80 @@
+/* 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>
+ */
+
+#include "DelugePageTransfer.h"
+
+configuration ObjectTransferC
+{
+  provides interface ObjectTransfer;
+  uses {
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+  }
+}
+
+implementation
+{
+  components ObjectTransferP, DelugePageTransferC;
+  
+  ObjectTransfer = ObjectTransferP;
+  BlockRead[0] = DelugePageTransferC.BlockRead[0];
+  BlockWrite[0] = DelugePageTransferC.BlockWrite[0];
+  BlockRead[1] = DelugePageTransferC.BlockRead[1];
+  BlockWrite[1] = DelugePageTransferC.BlockWrite[1];
+  ObjectTransferP.DelugePageTransfer -> DelugePageTransferC.DelugePageTransfer;
+  
+  components CrcP;
+  ObjectTransferP.Crc -> CrcP.Crc;
+  
+  components new AMSenderC(AM_DELUGEADVMSG) as SendAdvMsg, 
+             new AMReceiverC(AM_DELUGEADVMSG) as ReceiveAdvMsg,
+             new AMSenderC(AM_DELUGEREQMSG) as SendReqMsg, 
+             new AMReceiverC(AM_DELUGEREQMSG) as ReceiveReqMsg,
+             new AMSenderC(AM_DELUGEDATAMSG) as SendDataMsg, 
+             new AMReceiverC(AM_DELUGEDATAMSG) as ReceiveDataMsg;
+  
+  ObjectTransferP.SendAdvMsg -> SendAdvMsg;
+  ObjectTransferP.ReceiveAdvMsg -> ReceiveAdvMsg;
+  DelugePageTransferC.SendReqMsg -> SendReqMsg;
+  DelugePageTransferC.ReceiveReqMsg -> ReceiveReqMsg;
+  DelugePageTransferC.SendDataMsg -> SendDataMsg;
+  DelugePageTransferC.ReceiveDataMsg -> ReceiveDataMsg;
+  DelugePageTransferC.AMPacket -> SendDataMsg;
+  
+  ObjectTransferP.BlockWrite[0] = BlockWrite[0];
+  ObjectTransferP.BlockWrite[1] = BlockWrite[1];
+  
+  components MainC, LedsC, NoLedsC;
+  ObjectTransferP.Leds -> NoLedsC;
+  
+  components RandomC, new TimerMilliC() as Timer;
+  ObjectTransferP.Random -> RandomC;
+  ObjectTransferP.Timer -> Timer;
+  
+  // For collecting statistics
+//  components StatsCollectorC;
+//  ObjectTransferP.StatsCollector -> StatsCollectorC.StatsCollector;
+}
diff --git a/tos/lib/net/Deluge/ObjectTransferP.nc b/tos/lib/net/Deluge/ObjectTransferP.nc
new file mode 100644 (file)
index 0000000..fec6cd2
--- /dev/null
@@ -0,0 +1,337 @@
+/*
+ * "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."
+ *
+ * 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 "DelugePageTransfer.h"
+#include "DelugeMsgs.h"
+
+module ObjectTransferP
+{
+  provides interface ObjectTransfer;
+  uses {
+    interface Random;
+    interface Timer<TMilli> as Timer;
+    interface DelugePageTransfer;
+    interface Crc;
+    
+    interface AMSend as SendAdvMsg;
+    interface Receive as ReceiveAdvMsg;
+    
+    interface BlockWrite[uint8_t img_num];
+    
+    interface Leds;
+//  interface StatsCollector;
+  }
+}
+
+implementation
+{
+  // States
+  enum {
+    S_ERASE,
+    S_INITIALIZING_PUB,
+    S_INITIALIZING_RECV,
+    S_STARTED,
+    S_STOPPED,
+  };
+  
+  DelugeAdvTimer advTimers;
+  //DelugeNodeDesc nodeDesc;
+  uint8_t state = S_STOPPED;
+  
+  object_id_t cont_receive_new_objid;
+  object_size_t cont_receive_new_size;
+  uint8_t cont_receive_img_num;
+  
+  message_t pMsgBuf;
+  bool isBusy_pMsgBuf = FALSE;
+  DelugeObjDesc curObjDesc;
+  
+  void updateTimers()
+  {
+    //advTimers.timer = 0;
+  }
+  
+  void setupAdvTimer()
+  {
+    advTimers.timer = (uint32_t)0x1 << (advTimers.periodLog2 - 1);
+    advTimers.timer += call Random.rand16() & (advTimers.timer - 1);
+    advTimers.overheard = 0;
+    
+    call Timer.stop();
+    call Timer.startOneShot(advTimers.timer);
+  }
+  
+  void resetTimer()
+  {
+    if (advTimers.periodLog2 != DELUGE_MIN_ADV_PERIOD_LOG2) {
+      advTimers.periodLog2 = DELUGE_MIN_ADV_PERIOD_LOG2;
+      setupAdvTimer();
+    }
+  }
+  
+  task void signalObjRecvDone()
+  {
+    signal ObjectTransfer.receiveDone(SUCCESS);
+  }
+  
+  void setNextPage()
+  {
+    if (curObjDesc.numPgsComplete < curObjDesc.numPgs) {
+      call DelugePageTransfer.setWorkingPage(curObjDesc.objid, curObjDesc.numPgsComplete);
+      advTimers.newAdvs = DELUGE_NUM_NEWDATA_ADVS_REQUIRED;    
+      advTimers.overheard = 0;
+      resetTimer();
+    } else {
+      call DelugePageTransfer.setWorkingPage(DELUGE_INVALID_OBJID, DELUGE_INVALID_PGNUM);
+      post signalObjRecvDone();
+    }
+  }
+  
+//  bool isNodeDescValid(DelugeNodeDesc* tmpNodeDesc)
+//  {
+//    return (tmpNodeDesc->crc == crc16(tmpNodeDesc, 4 + sizeof(object_id_t) + 1));
+//  }
+  
+  bool isObjDescValid(DelugeObjDesc* tmpObjDesc)
+  {
+    return (tmpObjDesc->crc == call Crc.crc16(tmpObjDesc, sizeof(object_id_t) + sizeof(page_num_t))
+           && tmpObjDesc->crc != 0);
+  }
+  
+  void sendAdvMsg(uint16_t addr)
+  {
+    DelugeAdvMsg *pMsg = (DelugeAdvMsg *)(call SendAdvMsg.getPayload(&pMsgBuf));
+    
+    if (isBusy_pMsgBuf == FALSE) {
+      pMsg->sourceAddr = TOS_NODE_ID;
+      pMsg->version = DELUGE_VERSION;
+      //pMsg->type = (imagesLoaded) ? DELUGE_ADV_NORMAL : DELUGE_ADV_ERROR;
+      pMsg->type = DELUGE_ADV_NORMAL;
+      
+      // make sure node desc is valid
+//      if (!isNodeDescValid(&nodeDesc)) {
+//        memset(&nodeDesc, 0xff, sizeof(nodeDesc));
+//      }
+//      memcpy(&pMsg->nodeDesc, &nodeDesc, sizeof(DelugeNodeDesc));
+      
+      // make sure obj desc is valid
+//      if (!isObjDescValid(&curObjDesc)) {
+//        //curObjDesc.objid = objid;
+//      }
+      memcpy(&(pMsg->objDesc), &curObjDesc, sizeof(DelugeObjDesc));
+      
+      if (call SendAdvMsg.send(addr, &pMsgBuf, sizeof(DelugeAdvMsg)) == SUCCESS) {
+        //dbg(DBG_USR1, "DELUGE: Sent ADV_MSG(imgNum=%d)\n", imgDesc->imgNum);
+//call StatsCollector.msg_bcastReq();
+call Leds.led0Toggle();
+        isBusy_pMsgBuf = TRUE;
+      }
+    }
+  }
+  
+  /**
+   * Starts publisher
+   */
+  command error_t ObjectTransfer.publish(object_id_t new_objid, object_size_t new_size, uint8_t img_num)
+  {
+    call ObjectTransfer.stop();
+//call StatsCollector.startStatsCollector();
+    
+    state = S_INITIALIZING_PUB;
+    curObjDesc.objid = new_objid;
+    curObjDesc.numPgs = ((new_size - 1) / DELUGE_BYTES_PER_PAGE) + 1;   // Number of pages to transmit
+    curObjDesc.numPgsComplete = curObjDesc.numPgs;   // Publisher doesn't really care about this
+    curObjDesc.crc = call Crc.crc16(&curObjDesc, sizeof(object_id_t) + sizeof(page_num_t));
+    
+    if (state == S_INITIALIZING_PUB) {
+      resetTimer();
+    }
+    state = S_STARTED;
+    
+    call DelugePageTransfer.setImgNum(img_num);
+    call DelugePageTransfer.setWorkingPage(curObjDesc.objid, curObjDesc.numPgs);
+    
+    return SUCCESS;
+  }
+  
+  /**
+   * Resumes the process of preparing the receiver after the target volume is erased
+   */
+  void cont_receive() {
+    state = S_INITIALIZING_RECV;
+    curObjDesc.objid = cont_receive_new_objid;
+    curObjDesc.numPgs = ((cont_receive_new_size - 1) / DELUGE_BYTES_PER_PAGE) + 1;   // Number of pages to receive
+    curObjDesc.numPgsComplete = 0;
+    curObjDesc.crc = call Crc.crc16(&curObjDesc, sizeof(object_id_t) + sizeof(page_num_t));
+    
+    if (state == S_INITIALIZING_RECV) {
+      resetTimer();
+    }
+    state = S_STARTED;
+    
+    call DelugePageTransfer.setImgNum(cont_receive_img_num);
+    setNextPage();
+  }
+  
+  /**
+   * Starts receiver
+   */
+  command error_t ObjectTransfer.receive(object_id_t new_objid, object_size_t new_size, uint8_t img_num)
+  {
+    error_t error;
+    
+    call ObjectTransfer.stop();
+    state = S_STOPPED;
+//call StatsCollector.startStatsCollector();
+    
+    cont_receive_new_objid = new_objid;
+    cont_receive_new_size = new_size;
+    cont_receive_img_num = img_num;
+    
+    error = call BlockWrite.erase[img_num]();
+    if (error == SUCCESS) {
+      state = S_ERASE;
+    }
+    
+    return error;
+  }
+  
+  command error_t ObjectTransfer.stop()
+  {
+    call Timer.stop();
+    call DelugePageTransfer.stop();
+//call StatsCollector.stopStatsCollector();
+    
+    state = S_STOPPED;
+    curObjDesc.objid = DELUGE_INVALID_OBJID;
+    curObjDesc.numPgs = DELUGE_INVALID_PGNUM;
+    curObjDesc.numPgsComplete = DELUGE_INVALID_PGNUM;
+    
+    return SUCCESS;
+  }
+  
+  event void DelugePageTransfer.receivedPage(object_id_t new_objid, page_num_t new_pgNum)
+  {
+    if (new_objid == curObjDesc.objid && new_pgNum == curObjDesc.numPgsComplete) {
+      curObjDesc.numPgsComplete++;
+      curObjDesc.crc = call Crc.crc16(&curObjDesc, sizeof(object_id_t) + sizeof(page_num_t));
+      if (curObjDesc.numPgsComplete < curObjDesc.numPgs) {
+        setNextPage();
+      } else {
+        call DelugePageTransfer.setWorkingPage(curObjDesc.objid, curObjDesc.numPgsComplete);
+        post signalObjRecvDone();
+      }
+    }
+  }
+  
+  event void DelugePageTransfer.suppressMsgs(object_id_t new_objid)
+  {
+    if (new_objid == curObjDesc.objid) {
+      advTimers.overheard = 1;
+    }
+  }
+  
+  event void SendAdvMsg.sendDone(message_t* msg, error_t error)
+  {
+    isBusy_pMsgBuf = FALSE;
+  }
+  
+  event message_t* ReceiveAdvMsg.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    DelugeAdvMsg *rxAdvMsg = (DelugeAdvMsg*)payload;
+    DelugeObjDesc *cmpObjDesc = &(rxAdvMsg->objDesc);
+    bool isEqual = FALSE;
+    if (cmpObjDesc->objid != curObjDesc.objid) {
+      return msg;
+    }
+    
+    if (rxAdvMsg->version != DELUGE_VERSION 
+        //|| !isNodeDescValid(&rxAdvMsg->nodeDesc)
+        || state != S_STARTED) {
+      return msg;
+    }
+    
+    if (isObjDescValid(&(rxAdvMsg->objDesc)) && state == S_STARTED) {
+      // Their image is larger (They have something we need)
+      if (cmpObjDesc->numPgsComplete > curObjDesc.numPgsComplete) {
+        if ( advTimers.newAdvs == 0 ) {
+          call DelugePageTransfer.dataAvailable(rxAdvMsg->sourceAddr);
+        }
+      }
+      // Their image is smaller (They need something we have)
+      else if (cmpObjDesc->numPgsComplete < curObjDesc.numPgsComplete) {
+        advTimers.newAdvs = DELUGE_NUM_NEWDATA_ADVS_REQUIRED;
+      }      
+      // image is the same
+      else {
+        advTimers.overheard = 1;
+        isEqual = TRUE;
+      }
+      
+      if (!isEqual) {
+        resetTimer();
+      }
+    }
+    
+    return msg;
+  }
+    
+  event void Timer.fired()
+  {
+    updateTimers();
+    
+    if (advTimers.overheard == 0) {
+      sendAdvMsg(AM_BROADCAST_ADDR);
+    }
+    
+    if (call DelugePageTransfer.isTransferring())
+      advTimers.newAdvs = DELUGE_NUM_NEWDATA_ADVS_REQUIRED;
+    else if (advTimers.newAdvs > 0)
+      advTimers.newAdvs--;
+    
+    if (advTimers.newAdvs == 0 &&
+        advTimers.periodLog2 < DELUGE_MAX_ADV_PERIOD_LOG2) {
+      advTimers.periodLog2++;
+    }
+    
+    setupAdvTimer();
+  }
+  
+  default command error_t BlockWrite.erase[uint8_t img_num]() { return FAIL; }
+  event void BlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  event void BlockWrite.eraseDone[uint8_t img_num](error_t error)
+  {
+    if (state == S_ERASE) {
+      cont_receive();
+    }
+  }
+  event void BlockWrite.syncDone[uint8_t img_num](error_t error) {}
+}
diff --git a/tos/lib/net/Deluge/SerialStarterC.nc b/tos/lib/net/Deluge/SerialStarterC.nc
new file mode 100644 (file)
index 0000000..0d9855c
--- /dev/null
@@ -0,0 +1,34 @@
+/* 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 SerialStarterC { }
+
+implementation
+{
+  components SerialActiveMessageC, AutoStarterC;
+  
+  AutoStarterC.SplitControl -> SerialActiveMessageC;
+}
diff --git a/tos/lib/net/Deluge/StatsCollector.nc b/tos/lib/net/Deluge/StatsCollector.nc
new file mode 100644 (file)
index 0000000..4526686
--- /dev/null
@@ -0,0 +1,43 @@
+/* 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>
+ */
+
+interface StatsCollector
+{
+  command void stopStatsCollector();
+  command void startStatsCollector();
+  command void startPubPktTransTime();
+  command void endPubPktTransTime();
+  command void startRecvPageTransTime(uint8_t channel);
+  command void endRecvPageTransTime(uint8_t senderAddr);
+  command void incPub_numPktRetrans();
+  command void incNumRecvHSRetrans();
+  
+  command void startCCTime();
+  command void endCCTime();
+  
+  command void sendVariableReport(uint32_t value);
+  command void msg_bcastReq();
+}
diff --git a/tos/lib/net/Deluge/StatsCollectorC.nc b/tos/lib/net/Deluge/StatsCollectorC.nc
new file mode 100644 (file)
index 0000000..757610c
--- /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 Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+
+configuration StatsCollectorC
+{
+  provides {
+    interface StatsCollector;
+  }
+}
+
+implementation
+{
+  components GlobalsC, StatsCollectorP,
+    new CounterToLocalTimeC(TMilli),
+#ifdef TOSSIM
+    HilTimerMilliC,
+#else
+    new TransformCounterC(TMilli, uint32_t, T32khz, uint16_t, 5, uint32_t) as Transform,
+    Msp430Counter32khzC,
+#endif
+    new TimerMilliC() as Timer;
+
+#ifdef TOSSIM
+    StatsCollectorP.LocalTime -> HilTimerMilliC;
+#else
+  CounterToLocalTimeC.Counter -> Transform;
+  Transform.CounterFrom -> Msp430Counter32khzC;
+  StatsCollectorP.LocalTime -> CounterToLocalTimeC;
+#endif
+  
+  StatsCollectorP.Globals -> GlobalsC.Globals;
+  StatsCollector = StatsCollectorP.StatsCollector;
+  StatsCollectorP.Timer -> Timer;
+  
+  components SerialStarterC, new SerialAMSenderC(0);
+  StatsCollectorP.AMSend -> SerialAMSenderC;
+}
diff --git a/tos/lib/net/Deluge/StatsCollectorP.nc b/tos/lib/net/Deluge/StatsCollectorP.nc
new file mode 100644 (file)
index 0000000..551f76b
--- /dev/null
@@ -0,0 +1,203 @@
+/* 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>
+ */
+
+module StatsCollectorP
+{
+  provides {
+    interface StatsCollector;
+  }
+  uses {
+    interface LocalTime<TMilli> as LocalTime;
+    interface Globals;
+    interface Timer<TMilli> as Timer;
+    interface AMSend;
+  }
+}
+
+implementation
+{
+  enum {
+    TIMER = 0,
+    FORCED_START = 1,
+    FORCED_END = 2
+  };
+  
+  enum {
+    BROADCAST_REQ = 0,
+    START_RECV_DATA = 1,
+    END_RECV_DATA = 2
+  };
+  
+  typedef nx_struct StatsReport {
+    nx_uint8_t text[5];
+    nx_uint32_t NumPubPktTrans;
+    nx_uint32_t NumRecvPageTrans;
+    nx_uint32_t AvgPubPktTransTime;
+    nx_uint32_t AvgRecvPageTransTime;
+    nx_uint32_t NumPubPktRetrans;
+    nx_uint32_t NumRecvHSRetrans;
+  } StatsReport;
+  
+  typedef nx_struct StatusReport {
+    nx_uint8_t text[5];
+    nx_uint8_t flag;
+    nx_uint8_t channel;
+  } StatusReport;
+  
+  typedef nx_struct VariableReport {
+    nx_uint8_t text[5];
+    nx_uint32_t value;
+  } VariableReport;
+  
+  uint32_t startPubTime = 0;
+  uint32_t startRecvTime = 0;
+  uint32_t startCCTime = 0;   // Change channel
+  message_t stats_msg;
+  message_t status_msg;
+  message_t variable_msg;
+  void startTimer() {
+    if(call Timer.isRunning() == FALSE || call Timer.isOneShot() == TRUE) {
+      call Timer.startPeriodic(5000);
+    }
+  }
+  
+  void stopTimer() {
+    if(call Timer.isRunning() == TRUE) {
+      call Timer.stop();
+    }
+  }
+  
+  void sendStatsReport() {
+    StatsReport *report = (StatsReport *)call AMSend.getPayload(&stats_msg);
+
+    report->text[0] = 's';
+    report->text[1] = 't';
+    report->text[2] = 'a';
+    report->text[3] = 't';
+    report->text[4] = 's';
+    report->NumPubPktTrans = call Globals.getNumPubPktTrans();
+    report->NumRecvPageTrans = call Globals.getNumRecvPageTrans();
+    report->AvgPubPktTransTime = call Globals.getAvgPubPktTransTime();
+    report->AvgRecvPageTransTime = call Globals.getAvgRecvPageTransTime();
+    report->NumPubPktRetrans = call Globals.getNumPubPktRetrans();
+    report->NumRecvHSRetrans = call Globals.getNumRecvHSRetrans();
+    
+    call AMSend.send(AM_BROADCAST_ADDR, &stats_msg, sizeof(StatsReport));
+  }
+  
+  void sendStatusMsg(uint8_t flag, uint8_t channel) {
+    StatusReport *report = (StatusReport *)call AMSend.getPayload(&status_msg);
+    
+    report->text[0] = 's';
+    report->text[1] = 't';
+    report->text[2] = 't';
+    report->text[3] = 'u';
+    report->text[4] = 's';
+    report->flag = flag;
+    report->channel = channel;
+    
+    call AMSend.send(AM_BROADCAST_ADDR, &status_msg, sizeof(StatusReport));
+  }
+  
+  command void StatsCollector.sendVariableReport(uint32_t value) {
+    VariableReport *report = (VariableReport *)call AMSend.getPayload(&variable_msg);
+    
+    report->text[0] = 'r';
+    report->text[1] = 'e';
+    report->text[2] = 'p';
+    report->text[3] = 'r';
+    report->text[4] = 't';
+    report->value = value;
+    
+    call AMSend.send(AM_BROADCAST_ADDR, &variable_msg, sizeof(VariableReport));
+  }
+  
+  command void StatsCollector.msg_bcastReq() {
+    sendStatusMsg(BROADCAST_REQ, CC2420_DEF_CHANNEL);
+  }
+  
+  event void Timer.fired() {
+    sendStatsReport();
+  }
+  
+  event void AMSend.sendDone(message_t* pstats_msg, error_t error) { }
+  
+  command void StatsCollector.startStatsCollector()
+  {
+    startTimer();
+  }
+  
+  command void StatsCollector.stopStatsCollector()
+  {
+    stopTimer();
+    call Timer.startOneShot(500);
+    //sendStatsReport();   // Just in case
+  }
+  
+  command void StatsCollector.startPubPktTransTime()
+  {
+    startPubTime = call LocalTime.get();
+  }
+  command void StatsCollector.endPubPktTransTime()
+  {
+    uint32_t diff = (call LocalTime.get()) - startPubTime;
+    uint32_t temp = (call Globals.getAvgPubPktTransTime()) * (call Globals.getNumPubPktTrans());
+    call Globals.incNumPubPktTrans();
+    call Globals.setAvgPubPktTransTime((temp + diff) / (call Globals.getNumPubPktTrans()));
+  }
+  command void StatsCollector.startRecvPageTransTime(uint8_t channel)
+  {
+    startRecvTime = call LocalTime.get();
+    sendStatusMsg(START_RECV_DATA, channel);
+  }
+  command void StatsCollector.endRecvPageTransTime(uint8_t senderAddr)
+  {
+    uint32_t curTime = call LocalTime.get();
+    uint32_t temp = (call Globals.getAvgRecvPageTransTime()) * (call Globals.getNumRecvPageTrans());
+    call Globals.incNumRecvPageTrans();
+    call Globals.setAvgRecvPageTransTime((temp + (curTime - startRecvTime)) / (call Globals.getNumRecvPageTrans()));
+    sendStatusMsg(END_RECV_DATA, senderAddr);
+  }
+  
+  command void StatsCollector.incPub_numPktRetrans()
+  {
+    call Globals.incNumPubPktRetrans();
+  }
+  
+  command void StatsCollector.startCCTime() {
+    startCCTime = call LocalTime.get();
+  }
+  
+  command void StatsCollector.endCCTime() {
+    uint32_t diff = (call LocalTime.get()) - startCCTime;
+    call StatsCollector.sendVariableReport(diff);
+  }
+  
+  command void StatsCollector.incNumRecvHSRetrans() {
+    call Globals.incNumRecvHSRetrans();
+  }
+}
diff --git a/tos/lib/net/Deluge/extra/NetProg.h b/tos/lib/net/Deluge/extra/NetProg.h
new file mode 100644 (file)
index 0000000..b8624c0
--- /dev/null
@@ -0,0 +1,48 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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_H__
+#define __NETPROG_H__
+
+#include "NetProg_platform.h"
+
+#ifndef IDENT_UID_HASH
+#define IDENT_UID_HASH 0
+#endif
+
+static const uint32_t DELUGE_IMAGE_UID = IDENT_UID_HASH;
+
+typedef struct NetProg_TOSInfo {
+  uint16_t addr;
+  uint8_t  groupId;
+  uint16_t crc;
+} NetProg_TOSInfo;
+
+#endif
diff --git a/tos/lib/net/Deluge/extra/NetProg.nc b/tos/lib/net/Deluge/extra/NetProg.nc
new file mode 100644 (file)
index 0000000..5762cae
--- /dev/null
@@ -0,0 +1,57 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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."
+ *
+ */
+
+/**
+ * Top level interface for network programming integration with
+ * applications.
+ *
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+interface NetProg
+{
+
+  /**
+   * Reboot the node.
+   *
+   * @return  Does not return.
+   */
+  command error_t reboot();
+
+  /**
+   * Reboot into the image specified by <code>imgNum</code>. This
+   * assumes that an image has been downloaded into slot <code>imgNum</code>
+   * using Deluge.
+   *
+   * @param imgNum  Number of image to boot in to.
+   * @return        <code>FAIL</code> if the reboot command fails to 
+   *                complete due to an invalid imgNum or incomplete 
+   *                image, 
+   *                does not return, otherwise.
+   */
+  command error_t programImgAndReboot(uint8_t imgNum);
+
+}
diff --git a/tos/lib/net/Deluge/extra/NetProgC.nc b/tos/lib/net/Deluge/extra/NetProgC.nc
new file mode 100644 (file)
index 0000000..f889661
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * "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 NetProg;
+includes TOSBoot;
+
+configuration NetProgC {
+  provides {
+    interface NetProg;
+  }
+}
+
+implementation {
+
+  components MainC, InternalFlashC as IFlash, CrcP, 
+    DelugeStorageC, NetProgM;
+
+  NetProg = NetProgM;
+
+  MainC.SoftwareInit -> NetProgM.Init;
+  NetProgM.StorageMap[0] -> DelugeStorageC.StorageMap[0];
+  NetProgM.StorageMap[1] -> DelugeStorageC.StorageMap[1];
+  NetProgM.DelugeMetadata -> DelugeStorageC;
+  NetProgM.IFlash -> IFlash;
+  NetProgM.Crc -> CrcP;
+}
diff --git a/tos/lib/net/Deluge/extra/NetProgM.nc b/tos/lib/net/Deluge/extra/NetProgM.nc
new file mode 100644 (file)
index 0000000..998a5fd
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * "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 "AM.h"
+
+module NetProgM {
+  provides {
+    interface NetProg;
+    interface Init;
+  }
+  uses {
+    interface StorageMap[uint8_t img_num];
+    interface InternalFlash as IFlash;
+    interface Crc;
+    interface DelugeMetadata;
+  }
+}
+
+implementation {
+
+  uint16_t computeTosInfoCrc(NetProg_TOSInfo* tosInfo)
+  {
+    return call Crc.crc16(tosInfo, sizeof(NetProg_TOSInfo)-2);
+  }
+
+  void writeTOSinfo()
+  {
+    NetProg_TOSInfo tosInfo;
+    uint16_t crc;
+    call IFlash.read((uint8_t*)IFLASH_TOS_INFO_ADDR, &tosInfo, sizeof(tosInfo));
+    tosInfo.addr = TOS_NODE_ID;
+    tosInfo.groupId = TOS_AM_GROUP;
+    crc = computeTosInfoCrc(&tosInfo);
+    // don't write if data is already correct
+    if (tosInfo.crc == crc)
+      return;
+    tosInfo.crc = crc;
+    call IFlash.write((uint8_t*)IFLASH_TOS_INFO_ADDR, &tosInfo, sizeof(tosInfo));
+  }
+
+  command error_t Init.init()
+  {
+
+    NetProg_TOSInfo tosInfo;
+
+    call IFlash.read((uint8_t*)IFLASH_TOS_INFO_ADDR, &tosInfo, sizeof(tosInfo));
+
+    if (tosInfo.crc == computeTosInfoCrc(&tosInfo)) {
+      // TOS_AM_GROUP is not a variable in T2
+      //      TOS_AM_GROUP = tosInfo.groupId;
+      atomic TOS_NODE_ID = tosInfo.addr;
+    }
+    else {
+      writeTOSinfo();
+    }
+    return SUCCESS;
+  }
+  
+  command error_t NetProg.reboot()
+  {
+    atomic {
+      writeTOSinfo();
+      netprog_reboot();
+    }
+    return FAIL;
+  }
+  
+  command error_t NetProg.programImgAndReboot(uint8_t img_num)
+  {
+    tosboot_args_t args;
+    DelugeNodeDesc nodeDesc;
+    DelugeImgDesc *imgDesc;
+    
+    atomic {
+      writeTOSinfo();
+      
+      args.imageAddr = call StorageMap.getPhysicalAddress[img_num](0);
+      args.gestureCount = 0xff;
+      args.noReprogram = FALSE;
+      call IFlash.write((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
+      
+      // Write info about what img to disseminate after reboot
+      imgDesc = call DelugeMetadata.getImgDesc(img_num);
+      nodeDesc.uid = imgDesc->uid;
+      nodeDesc.imgNum = img_num;
+      call IFlash.write((uint8_t*)IFLASH_NODE_DESC_ADDR, &nodeDesc, sizeof(nodeDesc));
+      
+      // reboot
+      netprog_reboot();
+    }
+
+    // couldn't reboot
+    return FAIL;
+  }
+
+  default command storage_addr_t StorageMap.getPhysicalAddress[uint8_t img_num](storage_addr_t addr) { return 0xFFFFFFFF; }
+
+}
diff --git a/tos/lib/net/Deluge/extra/TOSBoot.h b/tos/lib/net/Deluge/extra/TOSBoot.h
new file mode 100644 (file)
index 0000000..ab5524b
--- /dev/null
@@ -0,0 +1,39 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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"
+
+typedef struct tosboot_args_t {
+  uint32_t imageAddr;
+  uint8_t  gestureCount;
+  bool     noReprogram;
+} tosboot_args_t;
+
+#endif
diff --git a/tos/lib/net/Deluge/extra/msp430/InternalFlashC.nc b/tos/lib/net/Deluge/extra/msp430/InternalFlashC.nc
new file mode 100644 (file)
index 0000000..a913bd7
--- /dev/null
@@ -0,0 +1,122 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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."
+ *
+ */
+
+/**
+ * InternalFlashC.nc - 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>
+ */
+
+includes InternalFlash;
+
+module InternalFlashC {
+  provides interface InternalFlash;
+}
+
+implementation {
+
+  enum {
+    IFLASH_OFFSET     = 0x1000,
+    IFLASH_SIZE       = 128,
+    IFLASH_SEG0_VNUM_ADDR = 0x107f,
+    IFLASH_SEG1_VNUM_ADDR = 0x10ff,
+    IFLASH_INVALID_VNUM = -1,
+  };
+
+  uint8_t chooseSegment() {
+    int8_t vnum0 = *(int8_t*)IFLASH_SEG0_VNUM_ADDR;
+    int8_t vnum1 = *(int8_t*)IFLASH_SEG1_VNUM_ADDR;
+    if (vnum0 == IFLASH_INVALID_VNUM)
+      return 1;
+    else if (vnum1 == IFLASH_INVALID_VNUM)
+      return 0;
+    return ( (int8_t)(vnum0 - vnum1) < 0 );
+  }
+
+  command error_t InternalFlash.write(void* addr, void* buf, uint16_t size) {
+
+    volatile int8_t *newPtr;
+    int8_t *oldPtr;
+    int8_t *bufPtr = (int8_t*)buf;
+    int8_t version;
+    uint16_t i;
+
+    addr += IFLASH_OFFSET;
+    newPtr = oldPtr = (int8_t*)IFLASH_OFFSET;
+    if (chooseSegment()) {
+      oldPtr += IFLASH_SIZE;
+    }
+    else {
+      addr += IFLASH_SIZE;
+      newPtr += IFLASH_SIZE;
+    }
+
+    FCTL2 = FWKEY + FSSEL1 + FN2;
+    FCTL3 = FWKEY;
+    FCTL1 = FWKEY + ERASE;
+    *newPtr = 0;
+    FCTL1 = FWKEY + WRT;
+    
+    for ( i = 0; i < IFLASH_SIZE-1; i++, newPtr++, oldPtr++ ) {
+      if ((uint16_t)newPtr < (uint16_t)addr || (uint16_t)addr+size <= (uint16_t)newPtr)
+       *newPtr = *oldPtr;
+      else
+       *newPtr = *bufPtr++;
+    }
+    version = *oldPtr + 1;
+    if (version == IFLASH_INVALID_VNUM)
+      version++;
+    *newPtr = version;
+    
+    FCTL1 = FWKEY;
+    FCTL3 = FWKEY + LOCK;
+
+    return SUCCESS;
+
+  }
+
+  command error_t InternalFlash.read(void* addr, void* buf, uint16_t size) {
+
+    addr += IFLASH_OFFSET;
+    if (chooseSegment())
+      addr += IFLASH_SIZE;
+
+    memcpy(buf, addr, size);
+
+    return SUCCESS;
+
+  }
+
+}
diff --git a/tos/lib/net/Deluge/extra/telos/NetProg_platform.h b/tos/lib/net/Deluge/extra/telos/NetProg_platform.h
new file mode 100644 (file)
index 0000000..365831a
--- /dev/null
@@ -0,0 +1,44 @@
+// $Id$
+
+/*                                                                     tab:2
+ *
+ *
+ * "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__
+
+enum {
+  IFLASH_TOS_INFO_ADDR = 0x60,  // 6 bytes
+  IFLASH_NODE_DESC_ADDR = 0x66, // 10 bytes
+};
+
+void netprog_reboot() {
+  WDTCTL = WDT_ARST_1_9; 
+  while(1);
+}
+
+#endif
diff --git a/tos/lib/net/Deluge/extra/telosb/InternalFlash.h b/tos/lib/net/Deluge/extra/telosb/InternalFlash.h
new file mode 100644 (file)
index 0000000..aa4f872
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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
new file mode 100644 (file)
index 0000000..ab860c0
--- /dev/null
@@ -0,0 +1,37 @@
+// $Id$
+
+/*                                                                     tab:4
+ *
+ *
+ * "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/telosb/TOSBoot_platform.h b/tos/lib/net/Deluge/extra/telosb/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..afc7693
--- /dev/null
@@ -0,0 +1,47 @@
+// $Id$
+
+/*                                                                     tab:2
+ * "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