#include <Arduino.h>
#include <Streaming.h>
#include <WiFlySerial.h>
#include <SoftwareSerial.h>

char ssid[] = "network_name";
char passphrase[] = "network_key";
char server_address[] = "192.168.0.1";
int server_port = 10000;

WiFlySerial wifly(2,3); 

void setup() {
  Serial << "Staring..." << endl;
  Serial.begin(9600);
  wifly.begin();
  connectToNetwork();  
}

void connectToNetwork(){
  //set authentication (passphrase encryption) mode
  //make sure you set this to the correct mode (WEP, WPA2, etc)
  wifly.setAuthMode(WIFLY_AUTH_WPA2_PSK);
  wifly.setDHCPMode(WIFLY_DHCP_ON); //turn on DHCP
  wifly.setJoinMode(WIFLY_JOIN_MANUAL); //join when directed
  wifly.setSSID(ssid) ; //set network ssid
  wifly.setPassphrase(passphrase); //set passphrase
  wifly.setRemotePort(server_port);

  wifly.join(); //attemp to join network and update device status
  wifly.getDeviceStatus();
}

void loop() {
  //if the wifly is connected to the network
  if(wifly.isifUp()){
    //if not yet connected to a server
    if(!wifly.isConnectionOpen())
    {
      //attempt to connect to the server
      wifly.openConnection(server_address);
      delay(1000); //give a little time before retrying
    }
    //otherwise, if we're already connected to a server
    else 
    {
      if ( wifly.isInCommandMode() ) {
        wifly.exitCommandMode();
      }
      
      //print out that we are sending data, read analog inputs 0 and 1, and
      //then send out the data over the wifly to the server
      Serial << "Connected and sending data to " << server_address << endl;
      wifly << "x: " << analogRead(0) << " y: " << analogRead(1) << " z: " << analogRead(2) << endl;
    } 
    delay(20); //wait 20ms between readings
    wifly.getDeviceStatus();
  }
  else{
    Serial << "wifi not up" << endl;
    connectToNetwork();
  }
}


