/*
Copyright 2003/2004, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.
Contributors: Bjoern Lichtblau

For documentation and questions please use the web site
http://www.http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include "ScatterWeb.Scanner.h"

#define     IDLE                  (0)
#define     SCANNING              (1)
#define     MAX_SCANNED_DEVICES   (30)
#define     SCAN_INTERVAL         (512)  // half second
#define     SCAN_RETRIES          (3)

UINT8 scannerState;
UINT16 scannedDevices[MAX_SCANNED_DEVICES];
UINT8 scannedDevicesIndex;
UINT8 scannerRetries;

void scanner_resend(); // private forward declaration

void send_SCAN(){
  packet_t packet;
  packet.to = BROADCAST;
  packet.type = SCAN_PACKET;
  packet.header = 0;
  packet.header_length = 0;
  packet.data = (UINT8*) scannedDevices;
  packet.data_length = scannedDevicesIndex * 2; // *2 because they are ints!
  Net_send(&packet, 0);
}

void scanner_resend(){
  if(scannerState == SCANNING && scannerRetries >= SCAN_RETRIES){
        scannerState = IDLE;
        Comm_print("OK %i devices scanned\r\n", scannedDevicesIndex);
  }
  else {
    send_SCAN();
    scannerRetries++;
    Timers_add(SCAN_INTERVAL, scanner_resend, 0xFFFF);   
  }
}

COMMAND(scn, SERIALONLY){ Scanner_startScan(); }     ///< Starts a scan.

bool Scanner_replyHandler() {
  if(scannerState != IDLE && scannedDevicesIndex<MAX_SCANNED_DEVICES){
    UINT16 i;
    scannerRetries = 0;
    if(Timers_remove(scanner_resend, 0xFFFF)!=0){
      Timers_add(SCAN_INTERVAL, scanner_resend, 0xFFFF);    
    }
    else Comm_log(LOW, "SCANNER: scannerState!=IDLE but no timer found in handle_SCAN_REPLY!\r\n");
    for(i=0; i<scannedDevicesIndex; i++){
      if(scannedDevices[i] == rxPacket.from) return True; // dont handle if we already had that device in this scan  
    }
    scannedDevices[scannedDevicesIndex] = rxPacket.from;
    scannedDevicesIndex++;
  }
  Comm_print("! %i:", rxPacket.from);
  printImageData((imageData_t*) rxPacket.data);
  return True;
}

void Scanner_begin() {
  Scanner_sendReply(BROADCAST);
}

bool Scanner_init() {
  scannerState = IDLE;
  return Timers_add(1000, Scanner_begin, 0xFFFF);
}

bool Scanner_startScan() {  
  UINT16 i;
  // return if already scanning
  if(scannerState != IDLE) return False;
  // clear scannedDevices and other variables
  for(i=0; i<MAX_SCANNED_DEVICES; i++) scannedDevices[i] = 0;
  scannedDevicesIndex = 0;
  scannerRetries = 0;
  // send scan packet
  scannerState = SCANNING;  
  send_SCAN();    
  return Timers_add(SCAN_INTERVAL, scanner_resend, 0xFFFF);
}

bool Scanner_scanHandler(){
  UINT16* ids;
  UINT16 i;
  ids = (UINT16*) rxPacket.data;
  for(i=0; i<rxPacket.data_length / 2; i++){
    if(ids[i] == Configuration.id) return True;  
  }
  return Scanner_sendReply(rxPacket.from);
}

bool Scanner_sendReply(UINT16 dest) {
  packet_t p;
  p.to = dest;                          p.type = SCAN_REPLY_PACKET; 
  p.header = 0;                         p.header_length = 0;
  p.data = (UINT8*) &imageData; p.data_length = sizeof(imageData_t);
  return Net_send(&p, NULL);
}
