task main ()
{
  // initialise the port, etc
  RS485initLib();
  displayTextLine(0, "Stat: disconnected");
  displayTextLine(2, "-------------------");

  N2WchillOut();
  N2WsetDebug(true);
  N2WchillOut();

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

  // Delete any pre-existing custom profiles and reset the device
  N2WDelete();
  N2WchillOut();
  N2WReset();
  sleep(4000);

  // enable DHCP
  if (useDHCP)
  {
    N2WsetDHCP(true);
  }
  else
  {
    N2WsetDHCP(false);
    N2WchillOut();
    N2WsetIPAddress(ipaddress);
    N2WchillOut();
    N2WsetMask(netmask);
    N2WchillOut();
    N2WsetDNS1(DNS1);
    N2WchillOut();
    N2WsetDNS2(DNS2);
    N2WchillOut();
    N2WsetGateway(gateway);
  }

  sleep(100);
  // Enable or disable AdHoc
  N2WsetAdHoc(useAdHoc);
  sleep(100);
  // SSID to connect to
  N2WsetSSID(ssid);
  sleep(100);

  if (useWPA)
    N2WSecurityWPAPassphrase(passphrase);
  else if (useWPA2)
    N2WSecurityWPA2Passphrase(passphrase);
  else if (useWEP104)
    N2WSecurityWEP104(passphrase);
  else if (useOpen)
    N2WSecurityOpen();

  displayTextLine(0, "Stat: Calculating");
  displayTextLine(3, "This can take up");
  displayTextLine(4, "to 30 seconds");
  sleep(100);

  // Save this profile to the custom profile
  N2WSave();
  sleep(100);
  // Load the custom profile
  N2WLoad();

  sleep(100);
  N2WConnect(true);
  displayTextLine(0, "Stat: Connecting");

  while (!N2WConnected())
    sleep(500);

  sleep(3000);

  N2WgetIP(ipaddress);
  displayTextLine(3, "My IP address is");
  displayTextLine(4, ipaddress);
  displayTextLine(0, "Stat: Configured");
  N2WchillOut();
  N2WSave();
  playSound(soundBeepBeep);
  while(true) sleep(1);
}
task main ()
{
	ubyte type;
	ubyte ID;
	ubyte state;
	ubyte value;
	string dataString;
	string tmpString;

	// initialise the port, etc
	RS485initLib();

	StartTask(updateScreen);

	// Disconnect if already connected
	N2WDisconnect();
	N2WchillOut();
	wait1Msec(1000);
  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(100);
	wait1Msec(1000);

	connStatus = "connected";
	PlaySound(soundBeepBeep);

	wait1Msec(3000);
	N2WgetIP(IPaddress);

	wait1Msec(1000);
	//                123456789012345
	dataStrings[0] = "Tch | Snr | Clr";
	//                on  | 011 |   1"
	while (true)
	{
		if (N2WreadWS(type, ID, state, value))
		{
			writeDebugStreamLine("btn: %d, state: %d", ID, state);
			switch (ID)
			{
			case 1: doStraight(state); break;
			case 3: doRight(state); break;
			case 4: doStop(state); break;
			case 5: doLeft(state); break;
			case 7: doReverse(state); break;
			case 9: doAction(state); break;
			case 11: handleColour(state); break;
			default: break;
			}
		}

		// All values are only updated when they've changed.
		// This cuts backs drastically on the number of messages
		// that have to be sent to the NXT2WIFI

		// Fetch the state of the Touch Sensor
		// This value is displayed by field 0 (in0) on the page
		currTouchState = SensorBoolean[TOUCH];
		if (currTouchState != prevTouchState)
		{
		  memset(data, 0, sizeof(data));
			data[0] = (currTouchState) ? '1' : '0';
			N2WwriteWS(1, 0, data, 2);
			prevTouchState = currTouchState;
			N2WchillOut();
		}

		// Fetch the currently detected colour.
		// This value is displayed by field 1 (in1) on the page
		currDetectedColour = SensorValue[COLOUR];
		if (currDetectedColour != prevDetectedColour)
		{
			sprintf(dataString, "%d", currDetectedColour);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 1, data, strlen(dataString));
			prevDetectedColour = currDetectedColour;
			N2WchillOut();
		}

		// Fetch the distance detected by the sonar sensor
		// This value is displayed by field 2 (in2) on the page
		currSonarDistance = SensorValue[SONAR];
		if (currSonarDistance != prevSonarDistance)
		{
			sprintf(dataString, "%d", currSonarDistance);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 2, data, strlen(dataString));
			prevSonarDistance = currSonarDistance;
			N2WchillOut();
		}

		// Fetch the tacho count for motor A
		// This value is displayed by field 3 (in3) on the page
		currEncMotorA = nMotorEncoder[MOT_ACTION];
		if (currEncMotorA != prevEncMotorA)
		{
			sprintf(dataString, "%d", currEncMotorA);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 3, data, strlen(dataString));
			prevEncMotorA = currEncMotorA;
			N2WchillOut();
		}

		// Fetch the tacho count for motor B
		// This value is displayed by field 4 (in4) on the page
		//currEncMotorB = nMotorEncoder[MOT_LEFT];
		if (currEncMotorB != prevEncMotorB)
		{
			sprintf(dataString, "%d", currEncMotorB);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 4, data, strlen(dataString));
			prevEncMotorB = currEncMotorB;
			N2WchillOut();
		}

		// Fetch the tacho count for motor C
		// This value is displayed by field 5 (in5) on the page
		currEncMotorC = nMotorEncoder[MOT_RIGHT];
		if (currEncMotorC != prevEncMotorC)
		{
			sprintf(dataString, "%d", currEncMotorC);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 5, data, strlen(dataString));
			prevEncMotorC = currEncMotorC;
			N2WchillOut();
		}

		// Fetch the current voltage level.  The average one
		// works best, the other one jumps around too much.
		// This value is displayed by field 6 (in6) on the page

		currBatteryLevel = nAvgBatteryLevel;
		if (currBatteryLevel != prevBatteryLevel)
		{
			sprintf(dataString, "%d", currBatteryLevel);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 6, data, strlen(dataString));
			prevBatteryLevel = currBatteryLevel;
			N2WchillOut();
		}

		sprintf(dataStrings[2], "A: %d", currEncMotorA);
		sprintf(dataStrings[3], "B: %d", currEncMotorB);
		sprintf(dataStrings[4], "C: %d", currEncMotorC);
	  sprintf(tmpString, "%s | %3d", (currTouchState == 0) ? "off" : "on ", currSonarDistance);
		sprintf(dataStrings[1], "%s | %3d", tmpString, currDetectedColour);
	}
}
task main ()
{
    int index;
    // port to use for the socket
    int BOFHport = 6666;
    string dataString;

    // get our bluetooth name
    getFriendlyName(dataString);

    int avail = 0;

    nNxtButtonTask = -2;
    StartTask(updateScreen);

    // initialise the port, etc
    RS485initLib();

    memset(RS485rxbuffer, 0, sizeof(RS485rxbuffer));
    memset(RS485txbuffer, 0, sizeof(RS485txbuffer));

    N2WchillOut();

    // Disconnect if already connected
    N2WDisconnect();
    N2WchillOut();

    // if a custom profile exists, use that instead
    if (N2WCustomExist())
    {
        N2WLoad();
    }
    else
    {
        // enable DHCP
        N2WsetDHCP(true);
        wait1Msec(100);
        // Disable adhoc
        N2WsetAdHoc(false);
        wait1Msec(100);
        // SSID to connect to
        N2WsetSSID("YOURWIFINETWORK");
        wait1Msec(100);
        // The passphrase to use
        N2WSecurityWPA2Passphrase("YOURWIFIPASSPHRASE");
        wait1Msec(100);
        // Save this profile to the custom profile
        N2WSave();
        wait1Msec(100);
        // Load the custom profile
        N2WLoad();
    }

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

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

    connStatus = "connected";
    PlaySound(soundBeepBeep);

    wait1Msec(3000);
    N2WgetIP(IPaddress);

    wait1Msec(1000);

    // 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();
        }
        // Wait a bit
        wait1Msec(50);
    }
}
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);
  }
}
task main ()
{
	ubyte type;
	ubyte ID;
	ubyte state;
	ubyte value;
	string dataString;
	string tmpString;

	// initialise the port, etc
	RS485initLib();

	StartTask(updateScreen);

	// Disconnect if already connected
	N2WDisconnect();
	N2WchillOut();
	wait1Msec(1000);
	// enable DHCP
	N2WsetDHCP(true);
	wait1Msec(100);
	// Disable adhoc
	N2WsetAdHoc(false);
	wait1Msec(100);

	// Network Configuration
	N2WsetMask("255.255.255.0");
	wait1Msec(100);
	N2WsetGateway("10.0.0.138");
	wait1Msec(100);
	N2WsetDNS1("8.8.8.8");
	wait1Msec(100);
	N2WsetDNS2("8.8.4.4");
	wait1Msec(100);
	N2WsetNetbiosName("NXT2WIFI1");
	wait1Msec(100);

	// SSID to connect to
	N2WsetSSID("test");
	wait1Msec(100);
	// The passphrase to use
	N2WSecurityWPA2Passphrase("pwasde08");
	wait1Msec(100);
	// Save this profile to the custom profile
	N2WSave();
	wait1Msec(500);
	// Load the custom profile
	N2WLoad();
	wait1Msec(100);

	N2WConnect(true);
	connStatus = "connecting";

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

	connStatus = "connected";
	PlaySound(soundBeepBeep);

	wait1Msec(3000);
	N2WgetIP(IPaddress);

	wait1Msec(1000);
	//                123456789012345
	dataStrings[0] = "Tch | Snr | Clr";
	//                on  | 011 |   1"
	while (true)
	{
		if (N2WreadWS(type, ID, state, value))
		{
			writeDebugStreamLine("btn: %d, state: %d", ID, state);
			switch (ID)
			{
			case 1: doStraight(state); break;
			case 3: doRight(state); break;
			case 4: doStop(state); break;
			case 5: doLeft(state); break;
			case 7: doReverse(state); break;
			case 9: doAction(state); break;
			case 11: handleColour(state); break;
			default: break;
			}
		}

		// All values are only updated when they've changed.
		// This cuts backs drastically on the number of messages
		// that have to be sent to the NXT2WIFI

		// Fetch the state of the Touch Sensor
		// This value is displayed by field 0 (in0) on the page
		currTouchState = SensorValue[TOUCH];
		if (currTouchState != prevTouchState)
		{
			sprintf(dataString, "%d", currTouchState);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 0, data, strlen(&data));
			prevTouchState = currTouchState;
			N2WchillOut();
		}

		// Fetch the currently detected colour.
		// This value is displayed by field 1 (in1) on the page
		currDetectedColour = SensorValue[COLOUR];
		if (currDetectedColour != prevDetectedColour)
		{
			sprintf(dataString, "%d", currDetectedColour);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 1, data, strlen(dataString));
			prevDetectedColour = currDetectedColour;
			N2WchillOut();
		}

		// Fetch the distance detected by the sonar sensor
		// This value is displayed by field 2 (in2) on the page
		currSonarDistance = SensorValue[SONAR];
		if (currSonarDistance != prevSonarDistance)
		{
			sprintf(dataString, "%d", currSonarDistance);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 2, data, strlen(dataString));
			prevSonarDistance = currSonarDistance;
			N2WchillOut();
		}

		// Fetch the tacho count for motor A
		// This value is displayed by field 3 (in3) on the page
		currEncMotorA = nMotorEncoder[MOT_ACTION];
		if (currEncMotorA != prevEncMotorA)
		{
			sprintf(dataString, "%d", currEncMotorA);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 3, data, strlen(dataString));
			prevEncMotorA = currEncMotorA;
			N2WchillOut();
		}

		// Fetch the tacho count for motor B
		// This value is displayed by field 4 (in4) on the page
		currEncMotorB = nMotorEncoder[MOT_LEFT];
		if (currEncMotorB != prevEncMotorB)
		{
			sprintf(dataString, "%d", currEncMotorB);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 4, data, strlen(dataString));
			prevEncMotorB = currEncMotorB;
			N2WchillOut();
		}

		// Fetch the tacho count for motor C
		// This value is displayed by field 5 (in5) on the page
		currEncMotorC = nMotorEncoder[MOT_RIGHT];
		if (currEncMotorC != prevEncMotorC)
		{
			sprintf(dataString, "%d", currEncMotorC);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 5, data, strlen(dataString));
			prevEncMotorC = currEncMotorC;
			N2WchillOut();
		}

		// Fetch the current voltage level.  The average one
		// works best, the other one jumps around too much.
		// This value is displayed by field 6 (in6) on the page

		currBatteryLevel = nAvgBatteryLevel;
		if (currBatteryLevel != prevBatteryLevel)
		{
			sprintf(dataString, "%d", currBatteryLevel);
			memcpy(data, dataString, strlen(dataString));
			N2WwriteWS(1, 6, data, strlen(dataString));
			prevBatteryLevel = currBatteryLevel;
			N2WchillOut();
		}

		sprintf(dataStrings[2], "A: %d", currEncMotorA);
		sprintf(dataStrings[3], "B: %d", currEncMotorB);
		sprintf(dataStrings[4], "C: %d", currEncMotorC);
	sprintf(tmpString, "%s | %3d", (currTouchState == 0) ? "off" : "on ", currSonarDistance);
		sprintf(dataStrings[1], "%s | %3d", tmpString, currDetectedColour);
	}
}
task main() {
  string mac;
  string IP;

  eraseDisplay();
  nxtDisplayTextLine(0, "NXT2WIFI SETUP" );
  nxtDisplayTextLine(7, "IP   SETUP   MAC" );

  nNxtButtonTask = -2;

  // initialise the port, etc
  RS485initLib();

  memset(RS485rxbuffer, 0, sizeof(RS485rxbuffer));
  memset(RS485txbuffer, 0, sizeof(RS485txbuffer));

  // Disconnect if already connected


  N2WsetDebug(true); // enable debug stream on computer terminal


  while(true)
  {
		// PRESS RIGHT BUTTON TO RETRIEVE MAC ADDRESS
		if (nNxtButtonPressed == kRightButton)
		{
			N2WgetMAC(mac);
			nxtDisplayTextLine(4, mac);
			// Debounce button
			while (nNxtButtonPressed != kNoButton) EndTimeSlice();
		}
		// PRESS RIGHT BUTTON TO TEST NETWORK CREATION AND CONNECTIVITY
		if (nNxtButtonPressed == kEnterButton)
		{
			N2WDisconnect();
			N2WchillOut();
			N2WDelete();
			CreateCustomWIFI();
			N2WchillOut();

			N2WConnect(true);  // connect to custom profile
			wait1Msec(1000);

			nxtDisplayTextLine(3, "Connecting...");
			while (!N2WConnected())
			  wait1Msec(1000);

			nxtDisplayTextLine(3, "Connected!");
			PlayTone(523, 90);  // C5
			wait1Msec(100);
			PlayTone(659,90);   // E5
			wait1Msec(100);
			PlayTone(784,90);
			wait1Msec(100);
			N2WgetIP(IP);
			nxtDisplayTextLine(4, IP);
			while (nNxtButtonPressed != kNoButton) EndTimeSlice();
		}
	  // PRESS LEFT BUTTON TO RETRIEVE IP ADDRESS
		if (nNxtButtonPressed == kLeftButton)
		{
			N2WgetIP(IP);
			nxtDisplayTextLine(4, IP);
			while (nNxtButtonPressed != kNoButton) EndTimeSlice();
		}
	}
}
task main ()
{
  string BOFHserver = "192.168.0.100"; // Linux VM
  int BOFHport = 6666;
  string dataString;
  getFriendlyName(dataString);

  int avail = 0;

  nNxtButtonTask = -2;
  StartTask(updateScreen);

  // initialise the port, etc
  RS485initLib();

  memset(RS485rxbuffer, 0, sizeof(RS485rxbuffer));
  memset(RS485txbuffer, 0, sizeof(RS485txbuffer));

  // Disconnect if already connected
  N2WDisconnect();
  N2WchillOut();

  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);

  wait1Msec(1000);


  while (true)
  {
    while (nNxtButtonPressed != kEnterButton) EndTimeSlice();
    while (nNxtButtonPressed != kNoButton) EndTimeSlice();
    if (N2WTCPOpenClient(1, BOFHserver, BOFHport)) {
      data[0] = 0x0A;
      N2WTCPWrite(1, data, 1);
      txbytes++;
      // How many bytes are available in the buffers?
	    avail = N2WTCPAvail(1);
	    if (avail > 0)
	    {
	      sizeOfReceivedData = avail;
	      rxbytes += avail;
	      N2WchillOut();
	      // read the current buffer
	      N2WTCPRead(1, avail);
	      processData();
	      for (int i = 0; i < avail; i++)
	      {
	        writeDebugStream("%c", RS485rxbuffer[i]);
	      }
	      writeDebugStreamLine("");
	    }
	    // Wait a bit
      N2WchillOut();
      // Disconnect
      N2WTCPClose(1);
    }
  }
}