I’ll put the full solution on Codeshare later but for now I thought I would post the base code I used to connect to my Android Galaxy Tab 2 Tablet using a WiFi connection.
I do not own (Or even want) a cell phone, so I have no idea if the code will work with one.
Not much error checking for now because the current code is only for testing if messages can be sent and received. As a note: I have used Bluetooth and the WiFi seems faster but we’ll see…
using System;
using System.IO;
using System.Collections;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Socket = System.Net.Sockets.Socket;
using GHI.Premium.Net;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
//IMPORTANT: YOU WILL NEED TO ENTER YOUR SSID and SECURITY KEY
//Using GHI .NET Micro Framework 4.2
// I guess I'm a client when connecting to my Android Galaxy Tab 2 Tablet
namespace AndroidWifiSpider
{
public partial class Program
{
//Your choice...
//static bool useDebug = true;
bool useDebug = false;
bool useOnce = true; //Allow button to connect to TCP only one time
Font MyFont = Resources.GetFont(Resources.FontResources.NinaB);
string ssid = "xxxxxxxxxx"; // <<<<< You need to enter your SSID here
string PassKey = "xxxxxxxx"; // <<<<< You need to enter your Password/Key here
//This is my Android Tablet
int port = 8080; // <<<<< Enter port to use here
string ip = "192.168.2.2"; // <<<<< Enter IP to use here
System.Threading.Timer Readtimer;
//Short text messages used. We are not reading/writing files
const int buffsize = 128; //Size for your needs
byte[] readbuff = new byte[buffsize];
byte[] data;
Socket AndroidSocket;
IPEndPoint ipep;
Thread ReceiveDataThread; //Not using for now
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{
multicolorLed.GreenBlueSwapped = true; //If needed - I need it
multicolorLed.TurnRed();
//Begin StartWIFI() only after pressing the Startbutton
Startbutton.ButtonPressed += new GTM.GHIElectronics.Button.ButtonEventHandler(Startbutton_ButtonPressed);
display_T35.SimpleGraphics.AutoRedraw = true;
display_T35.SimpleGraphics.BackgroundColor = GT.Color.LightGray;
display_T35.SimpleGraphics.DisplayText("Press start button to begin WiFi", MyFont, Colors.Black, 5, 3);
}
//
//Allow access for deploy/debug if this application hangs in a endless loop.
//If app hangs you can reset the main board and then deploy/debug
private void Startbutton_ButtonPressed(Button sender, Button.ButtonState state)
{
//Allow button press only one time
if (useOnce) //If true
{
useOnce = false;
display_T35.SimpleGraphics.Clear();
display_T35.SimpleGraphics.DisplayText("Starting WiFi - Using: " + ip +
" Port " + port.ToString(), MyFont, Colors.Red, 3, 10);
//WiFi begin
StartWIFI();
}
else
{
//If not the first button press
return;
}
}
//
// Your router SSID and PassKey need to be set for this method
void StartWIFI()
{
wifi_RS21.Interface.Open();
if (!wifi_RS21.Interface.NetworkInterface.IsDhcpEnabled)
wifi_RS21.Interface.NetworkInterface.EnableDhcp();
wifi_RS21.Interface.WirelessConnectivityChanged +=
new WiFiRS9110.WirelessConnectivityChangedEventHandler(Interface_WirelessConnectivityChanged);
wifi_RS21.Interface.NetworkAddressChanged +=
new WiFiRS9110.NetworkAddressChangedEventHandler(Interface_NetworkAddressChanged);
WiFiRS9110.AssignNetworkingStackTo(wifi_RS21.Interface);
try
{
WiFiNetworkInfo[] ScanResp = wifi_RS21.Interface.Scan(ssid);
//Use to Scan for all SSID's
//WiFiNetworkInfo[] ScanResp = wifi_RS21.Interface.Scan( );
if (ScanResp != null && ScanResp.Length > 0)
{
//Your passkey needed here
wifi_RS21.Interface.Join(ScanResp[0], PassKey);
if (useDebug) { Debug.Print("Connected to Wireless network - " + ssid); }
}
else
{
if (useDebug) { Debug.Print("Failed to connect to Wireless network - " + ssid); }
}
}
catch (Exception e)
{
Debug.Print("!!Exception : " + e.Message);
}
ipep = new IPEndPoint(IPAddress.Parse(ip), port);
AndroidSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Exception on Connect(ipep) if a delay is not used?
//Exception using 1000, 2000,
//3000 seemed to work without an exception,, So I'll use 4000 ;>)
Thread.Sleep(4000);
AndroidSocket.Connect(ipep);
//Inform user that connection was successful
multicolorLed.TurnGreen();
//Send a greeting message to the Android device
data = Encoding.UTF8.GetBytes("Hello from the Fez Spider.");
//Send greeting to the Android Tablet
AndroidSocket.Send(data);
//ReceiveDataThread = new Thread(ReceiveData);
//ReceiveDataThread.Start();
Readtimer = new Timer(new TimerCallback(ReceiveData), null, 100, 500);
Thread.Sleep(Timeout.Infinite);
}
//
//This method needs a test of some kind to see if the socket is still available......
public void ReceiveData(object obj)
{
byte[] readbuff = new byte[buffsize];
AndroidSocket.Receive(readbuff);
char[] chars = new System.Text.UTF8Encoding().GetChars(readbuff);
string dataReceived = String.Empty;
for (int i = 0; i < chars.Length; i++)
{
dataReceived += chars[i];
}
display_T35.SimpleGraphics.Clear();
display_T35.SimpleGraphics.DisplayText(dataReceived, MyFont, Colors.Black, 2, 3);
if (useDebug) { Debug.Print(dataReceived); }
//Test - Echo received text back to the Android
byte[] echo = new byte[buffsize];
echo = Encoding.UTF8.GetBytes("Echo: " + dataReceived);
//SocketException ErrorCode WSAESHUTDOWN 10058 Cannot send after socket shutdown.
//Send bytes to Android
AndroidSocket.SendTo(echo, ipep);
}
void Interface_WirelessConnectivityChanged(object sender, WiFiRS9110.WirelessConnectivityEventArgs e)
{
//Your code here
}
//
void Interface_NetworkAddressChanged(object sender, EventArgs e)
{
//Your code here
}
//
} //end class
} //end namespace
ADDED COMMENT: Does anyone know why the long delay is needed brfore AndroidSocket.Connect(ipep); ???
Everyone have a GREAT DAY!!