opportunistic-xbee/node/main/main.ino

101 lines
2.0 KiB
C++

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "packet.h" // Packet
#include "xbee_wrapper.h" // WBeeWrapper
// Peripherals
LiquidCrystal_I2C screen(0x27, 16, 2);
XBeeWrapper xbee = XBeeWrapper();
// ACTUAL DATA
uint8_t wave_id = 255; // last wave
uint8_t dist = 255; // actual distance
Packet recv;
Packet send;
void setup() {
Serial.begin(38400);
Serial.println("+ ready");
screen.begin();
screen.backlight();
xbee.begin(38400);
}
void loop() {
delay(500);
// 1. ignore if no received data
if( xbee.receive(recv) != XBWRECV_OK )
return;
uint8_t opcode = recv.getOpcode();
// DISCOVER REQUEST
if( opcode == 0 ) {
Serial.print("+ discover(");
Serial.print(recv.getSender());
Serial.print(", ");
Serial.print(recv.getWave());
Serial.print(", ");
Serial.print(recv.getDist());
Serial.println(")");
if( recv.getWave() != wave_id ){
wave_id = recv.getWave();
dist = recv.getDist()+1;
recv.setDist(dist);
Serial.print(" + wave = ");
Serial.println(wave_id);
Serial.print(" + dist = ");
Serial.println(dist);
send.setOpcode(0);
send.setWave(wave_id);
send.setDist(dist);
send.setSender(42);
xbee.broadcast(send);
Serial.print(" + send discover(");
Serial.print(send.getSender());
Serial.print(", ");
Serial.print(send.getWave());
Serial.print(", ");
Serial.print(send.getDist());
Serial.println(")");
}
// MESSAGE DATA
} else {
Serial.print("+ message(");
Serial.print(recv.getDist());
Serial.print(", ");
Serial.print(recv.getTTL());
Serial.print(", ");
Serial.print(recv.getSize());
Serial.println(")");
// propagation
if( recv.getTTL() > 0 && recv.getDist() <= dist ){
send.setOpcode(1);
send.setTTL(recv.getTTL()-1);
send.setDist(dist);
send.setData(recv.getData(), recv.getSize());
xbee.broadcast(send);
Serial.print(" + send message(");
Serial.print(recv.getDist());
Serial.print(", ");
Serial.print(recv.getTTL());
Serial.print(", ");
Serial.print(recv.getSize());
Serial.println(")");
}
}
}