+#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;
+
+enum {
+ MY_COLLECTION_ID = NEW_COLLECTION_CLIENT_ID(), // Gets a collection sender instance
+};
+
+void tosthread_main(void* arg)
+{
+ local.interval = DEFAULT_INTERVAL;
+ local.id = TOS_NODE_ID;
+ local.version = 0;
+
+ while ( amRadioStart() != SUCCESS );
+ while ( collectionRoutingStart() != SUCCESS );
+
+ collectionSetCollectionId(MY_COLLECTION_ID, AM_OSCILLOSCOPE); // Associates the collection sender
+ // with AM_OSCILLOSCOPE collection ID
+
+ if (local.id % 500 == 0) {
+ while ( amSerialStart() != SUCCESS );
+ collectionSetRoot();
+ for (;;) {
+ // Waits for incoming packets with AM_OSCILLOSCOPE collection ID
+ if (collectionReceive(&recvbuf, 0, AM_OSCILLOSCOPE) == SUCCESS) {
+ oscilloscope_t *recv_o = (oscilloscope_t *) collectionGetPayload(&recvbuf, sizeof(oscilloscope_t));
+ oscilloscope_t *send_o = (oscilloscope_t *) serialGetPayload(&sendbuf, sizeof(oscilloscope_t));
+ memcpy(send_o, recv_o, sizeof(oscilloscope_t));
+ amSerialSend(AM_BROADCAST_ADDR, &sendbuf, sizeof(local), AM_OSCILLOSCOPE);
+ report_received();
+ }
+ }
+ } else {
+ uint16_t var;
+
+ for (;;) {
+ if (reading == NREADINGS) {
+ oscilloscope_t *o = (oscilloscope_t *) collectionGetPayload(&sendbuf, sizeof(oscilloscope_t));
+ if (o == NULL) {
+ fatal_problem();
+ return;
+ }
+ memcpy(o, &local, sizeof(local));
+ if (collectionSend(&sendbuf, sizeof(local), MY_COLLECTION_ID) == SUCCESS) {
+ local.count++;
+ 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();
+}