Again, this is largely based on the sparkfun tutorial, but I've removed the delays with "waits for response". This speeds things up and is easier to error check.
www.sparkfun.com/commerce/tutorial_info.php
/*
Send the correct commands to connect to a wireless network using the parameters used on construction
*/
void WiFly::AutoConnect()
{
delay(DEFAULT_TIME_TO_READY);
FlushRX();
// Enter command mode
EnterCommandMode();
// Reboot to get device into known state
WriteToWiFlyCR("reboot");
WaitUntilReceived("*Reboot*");
WaitUntilReceived("*READY*");
FlushRX();
// Enter command mode
EnterCommandMode();
// turn off auto joining
WriteToWiFlyCR("set wlan join 0");
WaitUntilReceived(AOK, ERR);
// Set authentication level to
WriteToWiFly("set w a ");
WriteToWiFlyCR(auth_level);
WaitUntilReceived(AOK, ERR);
// Set authentication phrase to
WriteToWiFly("set w p ");
WriteToWiFlyCR(m_password);
WaitUntilReceived(AOK, ERR);
WriteToWiFly("set i l ");
WriteToWiFlyCR(port_listen);
WaitUntilReceived(AOK, ERR);
// Deactivate remote connection automatic message
WriteToWiFlyCR("set comm remote 0");
WaitUntilReceived(AOK, ERR);
// Join wireless network
WriteToWiFly("join ");
WriteToWiFlyCR(m_network);
delay(DEFAULT_TIME_TO_JOIN);
bool ok = WaitUntilReceived("IP=");
delay(DEFAULT_TIME_TO_WAIT);
FlushRX();
if(ok == false)
{
m_printer->print("Failed to associate with '");
m_printer->print(m_network);
m_printer->println("'\n\rRetrying...");
FlushRX();
AutoConnect();
}
else
{
m_printer->println("Associated!");
ExitCommandMode();
}
// TODO save this configuration
}
/*
Enter command mode by sending: $$$
Characters are passed until this exact sequence is seen. If any bytes are seen before these chars, or
after these chars, in a 1 second window, command mode will not be entered and these bytes will be passed
on to other side.
*/
void WiFly::EnterCommandMode()
{
FlushRX();
delay(1000); // wait 1s as instructed above
m_printer->println("Entering command mode.");
WriteToWiFly("$$$");
WaitUntilReceived("CMD");
}
/*
exit command mode
send the "exit" command and await the confirmation result "EXIT"
*/
void WiFly::ExitCommandMode()
{
WriteToWiFlyCR("exit");
WaitUntilReceived("EXIT");
}