TheThingsNetwork / arduino-device-lib

Arduino Library for TTN Devices
MIT License
208 stars 96 forks source link

API: Allow user to register function for downlink #23

Closed FokkeZB closed 8 years ago

FokkeZB commented 8 years ago

Receiving a response is not straight forward. You have to send to receive and sendBytes() only returns the length. Then you'll have to use ttn.downlinkPort and ttn.downlink to get the rest of the info.

The Wire library lets you register a function to be called when a message is received. This is a much more friendly API already, although the function still doesn't receive all info as arguments, which I think it should.

Current:

void loop() {
  // Send a byte
  byte buf[1];
  buf[0] = 20;
  int downlinkBytes = ttn.sendBytes(buf, 1);

  if (downlinkBytes > 0) {
    debugPrintLn("Received " + String(downlinkBytes) + " bytes on port " + String(ttn.downlinkPort) + ":")

    for (int i = 0; i < downlinkBytes; i++) {
      debugPrint(String(ttn.downlink[i]) + " ");
    }

    debugPrintLn();
  }

  delay(20000);
}

Proposed:

void setup() {
  // ..

  ttn.onMessage(receiveMessage);
}

void loop() {
  // send a byte to poll
  var poll = { x00 };
  ttn.sendByes(poll, 1);
}

void receiveEvent(const byte* buffer, int length, int port) {
    debugPrintLn("Received " + String(length) + " bytes on port " + String(port) + ":")

    for (int i = 0; i < downlinkBytes; i++) {
      debugPrint(String(buffer[i]) + " ");
    }

    debugPrintLn();
}