 }
 
 // log text to USART and toggle LED
-static void init_func (osjob_t* job) {
+static void tx_func (osjob_t* job) {
   // say hello
-  Serial.println("TX");
-  Serial.flush();
   tx("Hello, world!", txdone_func);
-  // reschedule job every second
-  os_setTimedCallback(job, os_getTime() + sec2osticks(1), init_func);
+  // reschedule job every 1000-1500ms, unless packets are received, then
+  // rx_func will reschedule more often
+  os_setTimedCallback(job, os_getTime() + ms2osticks(1000 + random(500)), tx_func);
 }
-
-osjob_t initjob;
 
 // application entry point
 void setup() {

void onEvent (ev_t ev) {
}

// Transmit the given string and call the given function afterwards
void tx(const char *str, osjobcb_t func) {
  os_radio(RADIO_RST); // Stop RX first
  delay(1); // Wait a bit, without this os_radio below asserts
  LMIC.dataLen = 0;
  while (*str)
    LMIC.frame[LMIC.dataLen++] = *str++;
  LMIC.osjob.func = func;
  os_radio(RADIO_TX);
}

// Enable rx mode and call func when a packet is received
void rx(osjobcb_t func) {
  LMIC.osjob.func = func;
  // Enable RX continuously
  os_radio(RADIO_RXON);
}

static void rx_func (osjob_t* job) {
  Serial.print("RX ");
  Serial.print(LMIC.dataLen);
  Serial.println(" bytes");
  Serial.write(LMIC.frame, LMIC.dataLen);
  Serial.println();
}

static void txdone_func (osjob_t* job) {

  delay(1000);
  #endif

  #ifdef LED_RED
  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);
  digitalWrite(LED_RED, LOW);
  digitalWrite(LED_GREEN, HIGH);
  digitalWrite(LED_BLUE, HIGH);
  #else
  pinMode(LED_BUILTIN, OUTPUT);
  #endif

  // initialize runtime env
  os_init();

  // Set up these settings once, and use them for both TX and RX

  // Use the ping settings. In 868Mhz, this is F6 frequency which allows
  // 10% duty cycle and the most tx power (27dBm). In 868 this is
  // channel 0, which allows up to 30dBm.
  LMIC.datarate = DR_PING;
  LMIC.freq = FREQ_PING;
  LMIC.txpow = 27;
  LMIC.rps = updr2rps(LMIC.datarate);

  Serial.println("Started");
  Serial.flush();

  // setup initial job
  os_setCallback(&txjob, tx_func);
}

void loop() {
