+#include "tosthread_amradio.h"
+#include "tosthread_amserial.h"
+#include "tosthread_leds.h"
+#include "tosthread_collection.h"
+#include "tosthread_sinesensor.h"
+#include "MultihopOscilloscope.h"
+
+void fatal_problem();
+void report_problem();
+void report_sent();
+void report_received();
+
+oscilloscope_t local;
+uint8_t reading = 0; /* 0 to NREADINGS */
+message_t sendbuf;
+message_t recvbuf;
+
+void tosthread_main(void* arg) {
+ local.interval = DEFAULT_INTERVAL;
+ local.id = TOS_NODE_ID;
+ local.version = 0;
+
+ while ( amRadioStart() != SUCCESS );
+ while ( collectionRoutingStart() != SUCCESS );
+
+ if (local.id % 500 == 0) {
+ while ( amSerialStart() != SUCCESS);
+ collectionSetRoot();
+ for (;;) {
+ if ( collectionReceive(&recvbuf, 0, AM_OSCILLOSCOPE) == SUCCESS) {
+ amSerialSend(AM_BROADCAST_ADDR, &recvbuf, sizeof(local), AM_OSCILLOSCOPE);
+ report_received();
+ }
+ }
+ } else {
+ uint16_t var;
+
+ for (;;) {
+ if (reading == NREADINGS) {
+ oscilloscope_t *o = o;
+ o = (oscilloscope_t *) collectionGetPayload(&sendbuf, sizeof(oscilloscope_t));
+ if (o == NULL) {
+ fatal_problem();
+ return;
+ }
+ memcpy(o, &local, sizeof(local));
+ if (collectionSend(&sendbuf, sizeof(local), AM_OSCILLOSCOPE) == SUCCESS) {
+ report_sent();
+ } else {
+ report_problem();
+ }
+
+ reading = 0;
+ }
+
+ if (sinesensor_read(&var) == SUCCESS) {
+ local.readings[reading++] = var;
+ }
+
+ tosthread_sleep(local.interval);
+ }
+ }
+}
+
+// Use LEDs to report various status issues.
+void fatal_problem() {
+ led0On();
+ led1On();
+ led2On();
+}