void startDemon() {
  DWIFIClose();
  sleep(500);
  DWIFITCPOpenServer(80);
  RS485clearRead();
  parseInput();
}
void startWifi() {
  while (true) {
	  configureWiFi();
	  set_verbose(false);
	  RS485clearRead();
	  wait1Msec(100);
	  startDemon();
	}
}
void configureWiFi(char *_ssid, char *_key)
{
  short len;
  RS485clearRead();      // Clear out the buffer and test TX/RX.
  sleep(1000);          // Must be run first!
  DWIFIsetEcho(false);     // Must be run first!
  sleep(1000);          // Must be run first!
  RS485clearRead();
  eraseDisplay();
  DWIFIsetSWControl();  // Must be run first!
  RS485clearRead();
  DWIFIsetVerbose(false);
  sleep(100);
  RS485clearRead();
  RS485read(RS485rxbuffer, len);
  DWIFIsetSSID(_ssid);
  DWIFIsetDHCP(true);
  DWIFIsetWPAPSK(_ssid, _key);
  sleep(20000);
  DWIFIsaveConfig();
}
task main()
{
  char *ssid = "YOURSSID";
  char *wpa_psk = "YOURWPAEY";

  writeDebugStreamLine("ssid: %s", ssid);
  writeDebugStreamLine("psk: %s", wpa_psk);
  short len = 100;
  eraseDisplay();
  bNxtLCDStatusDisplay = true; // Enable top status line display
  writeDebugStream("Scanning for wifi sensor: ");

  // You can play with these to see if they work for you.
  // I tend to use the 460800 rate as it's the fastest speed
  // that I can use reliably.
  //DWIFIsetBAUDRate(9600);
  DWIFIsetBAUDRate(230400);

  DWIFIsetWPAPSK((char *)ssid, (char *)wpa_psk);
  // set_verbose(false);
  // Receive();
  sleep(100);
  playSound(soundBeepBeep);
  //time1[T1] = 0;
  //while (time1[T1] < 30000)
  //{
  //  RS485read(RS485rxbuffer, len, 100);
  //  sleep(500);
  //}
  startDemon();

  sleep(1000);
  RS485clearRead();
  SensorType[COLOUR] = sensorColorNxtRED;
  RS485clearRead();
  parseInput();

  startDemon();
}
void startDemon() {
  time1[T2] = 0;
  while (true) {
    if (time1[T2] > 1200000)
      return;
    SensorType[COLOUR] = sensorCOLORNONE;
    PlaySound(soundBlip);
    closeAllConns();
    wait1Msec(500);
	  startListen(80);
	  SensorType[COLOUR] = sensorCOLORRED;
	  RS485clearRead();
	  parseInput();
	}
}
void genResponse(int cid) {
  int power = motor[motorA];
  float temp = 0.0;
  string tmpString;
  int index = 0;
  ubyte linebuff[20];
  StringFromChars(tmpString, rxbuffer);
  index = StringFind(tmpString, "/");
  StringDelete(tmpString, 0, index);
  index = StringFind(tmpString, "HTTP");
  StringDelete(tmpString, index, strlen(tmpString));
  writeDebugStreamLine("Request:%s", tmpString);
  nxtDisplayTextLine(2, "Request: ");
  nxtDisplayTextLine(3, tmpString);
  if (StringFind(tmpString, "MOTA") > 0) {
    StringDelete(tmpString, 0, 6);
    index = StringFind(tmpString, " ");
  if (index > -1)
      StringDelete(tmpString, index, strlen(tmpString));
    //power = RC_atoix(tmpString);
    power = clip(atoi(tmpString), -100, 100);
    writeDebugStreamLine("Power:%d", power);
  } else {
    writeDebugStreamLine("NO POWER: %s", tmpString);
  }

  sendHeader(cid);
  while(nxtHS_Status == HS_SENDING) wait1Msec(5);

  wait1Msec(100);

  index = 0;
  linebuff[0] = 27; // escape;
  linebuff[1] = 'S'; // the CID;
  linebuff[2] = (ubyte)cid + 48; // the CID;
  index = RS485appendToBuff(RS485txbuffer, index, linebuff, 3);
  StringFormat(tmpString, "MotorA=%d\n", power);
  memcpy(linebuff, tmpString, strlen(tmpString));
  index = RS485appendToBuff(RS485txbuffer, index, linebuff, strlen(tmpString));
  DTMPreadTemp(DTMP, temp);
  StringFormat(tmpString, "Temp: %2.2f C", temp);
  memcpy(linebuff, tmpString, strlen(tmpString));
  index = RS485appendToBuff(RS485txbuffer, index, linebuff, strlen(tmpString));
  linebuff[0] = 27; // escape;
  linebuff[1] = 'E'; // the CID;
  index = RS485appendToBuff(RS485txbuffer, index, endmarker, 2);
  RS485write(RS485txbuffer, index);
  if (power != 0) nMotorEncoderTarget[motorA] = 2000;
  motor[motorA] = power;
  if (power > 0)
    SensorType[COLOUR] = sensorCOLORGREEN;
  else if (power < 0)
    SensorType[COLOUR] = sensorCOLORBLUE;
  else if (nMotorRunState[motorA] == runStateIdle)
    SensorType[COLOUR] = sensorCOLORRED;
  else
    SensorType[COLOUR] = sensorCOLORRED;
  wait1Msec(300);
  RS485clearRead();
  closeConn(1);
  memset(RS485rxbuffer, 0, sizeof(RS485rxbuffer));
  //wait1Msec(100);
  RS485read(RS485rxbuffer, sizeof(RS485rxbuffer));
  //clear_read_buffer();
}
task main ()
{
  int index;
  // port to use for the socket
  int BOFHport = 6666;
  string dataString;

  // get our bluetooth name
  getFriendlyName(dataString);

  int avail = 0;

  StartTask(updateScreen);

  // initialise the port, etc
  RS485initLib();
  N2WchillOut();
  N2WsetDebug(true);
  N2WchillOut();

  // Disconnect if already connected
  N2WDisconnect();
  wait1Msec(100);

  if (!N2WCustomExist())
  {
    StopTask(updateScreen);
    wait1Msec(50);
    eraseDisplay();
    PlaySound(soundException);
    nxtDisplayCenteredBigTextLine(1, "ERROR");
    nxtDisplayTextLine(3, "No custom profile");
    nxtDisplayTextLine(4, "configured!!");
    while(true) EndTimeSlice();
  }

  N2WLoad();
  wait1Msec(100);
  N2WConnect(true);
  connStatus = "connecting";

  while (!N2WConnected())
    wait1Msec(1000);

  connStatus = "connected";
  PlaySound(soundBeepBeep);

  wait1Msec(3000);
  N2WgetIP(IPaddress);
  memcpy(dataStrings[4], IPaddress, strlen(IPaddress) + 1);

  wait1Msec(1000);

  N2WTCPClose(0);
  N2WchillOut();
  RS485clearRead();
  N2WchillOut();
  // Open a listening socket on port 6666
  if (!N2WTCPOpenServer(1, BOFHport))
  {
    writeDebugStreamLine("Err open port %d", BOFHport);
    PlaySound(soundException);
    while(bSoundActive) EndTimeSlice();
    StopAllTasks();
  }

  while (true)
  {
    // Check if anyone has sent us anything
    avail = N2WTCPAvail(1);
    if (avail > 0)
    {
      rxbytes += avail;
      N2WchillOut();


      PlaySound(soundFastUpwardTones);

      // Read what the client sent us
      sprintf(dataStrings[0], "%d bytes from", avail);
      N2WTCPRead(1, avail);
      N2WchillOut();

      // Get the MAC address of the client
      dataStrings[2] = "Remote MAC:";
      N2WTCPClientMAC(1, dataStrings[3]);

      writeDebugStream("MAC: ");
      writeDebugStreamLine(dataStrings[3]);
      N2WchillOut();

      // check the IP address of the client
      N2WTCPClientIP(1, dataStrings[1]);
      N2WchillOut();

      // Send back a hearty "Hi there, <IP>!"
      index = 0;
      returnMsg = "Hi there, ";
      index = RS485appendToBuff(buffer, index, returnMsg);
      index = RS485appendToBuff(buffer, index, dataStrings[1]);
      returnMsg = "\n";
      index = RS485appendToBuff(buffer, index, returnMsg);
      txbytes += index;
      N2WTCPWrite(1, (tHugeByteArray)buffer, index);
      N2WchillOut();

      // Terminate the connection to the client
      N2WTCPDetachClient(1);
      N2WchillOut();
      wait1Msec(1000);
	  }
	  // Wait a bit
    wait1Msec(50);
  }
}