I am looking for a way to communicate either over TCP or HTTP between android and C# 2012. Here is what I have so far
JAVA CLIENT:
package com.example.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)this.findViewById(R.id.button1);
tc = (TextView) this.findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Thread th = new Thread(new Runnable() {
public void run() {
connect();
}
});
th.start();
}
});
}
private void connect() {
InetAddress[] server;
try {
server = InetAddress.getAllByName("192.168.1.100");
Socket socket = new Socket(server[0], 3975);
if (socket.isConnected()){
Log.d("connected", "connected");
}
PrintWriter w = null;
BufferedReader r = null;
w = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
w.println("test");
/*String m = null;
while ((m=r.readLine())!= null) {
w.write(m,0,m.length());
w.flush();
}*/
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
C# SERVER:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
public async void ServiceButtonClick(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
try
{
await listener.BindServiceNameAsync("3975");
lblMessage.Text = "We are listening for connections...";
}
catch (Exception ee)
{
lblMessage.Text = "Unable to bind service.. " + ee.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "We are connected to the client";
});
try
{
while (true)
{
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 1";
});
return;
}
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringlength);
if (stringLength != actualStringLength)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 2";
});
return;
}
string temp;
temp = reader.ReadString(actualStringLength);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "Client said - " + reader.ReadString(3);
});
}
}
catch (Exception e)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "ERROR: " + e.Message + " - " + e.Source + " - " + e.StackTrace;
});
}
}
}
Now when I click the button on the client, the socket is connected, but when I send data to the C# server from my phone, nothing shows up on the server. Is there anything I am doing wrong on the receiving or sending end? I am just trying to send basic strings over TCP.
Related
so what im actually trying to do is to comunicate with a DMX-Interface pluged to a PC/Host via an Xamarin Android App.
Allready got my Server running, works also with an console client i wrote first. So now I wrote the app,using the same Way as before, with a TCPClient and then writing the data via a stream.
Because I'm running the app in the emulator I use as IP 10.0.2.2 to connect, but I cannot establish a connection. The App crashes or I get a timeout exeption. Been trying and researching now for two days and now i'm desperate, so I attach my code here, hope anyone can help
Thanks, Johannes
App:
public class MainActivity : Activity
{
public Stream Stream;
TcpClient Client = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
//adding control elements from Resource.Layout.Main
Button at = FindViewById<Button>(Resource.Id.at);
Button enter = FindViewById<Button>(Resource.Id.enter);
Button thru = FindViewById<Button>(Resource.Id.thru);
Button all = FindViewById<Button>(Resource.Id.all);
Button one = FindViewById<Button>(Resource.Id.one);
Button two = FindViewById<Button>(Resource.Id.two);
Button three = FindViewById<Button>(Resource.Id.three);
Button four = FindViewById<Button>(Resource.Id.four);
Button five = FindViewById<Button>(Resource.Id.five);
Button six = FindViewById<Button>(Resource.Id.six);
Button seven = FindViewById<Button>(Resource.Id.seven);
Button eight = FindViewById<Button>(Resource.Id.eight);
Button nine = FindViewById<Button>(Resource.Id.nine);
Button zero = FindViewById<Button>(Resource.Id.zero);
Button comma = FindViewById<Button>(Resource.Id.comma);
Button connect = FindViewById<Button>(Resource.Id.connect);
Button clear = FindViewById<Button>(Resource.Id.clear);
at.Click += (o, e) =>
{
UpdateCmdLine("#");
};
clear.Click += (o, e) =>
{
FlushCmdLine();
};
enter.Click += (o, e) =>
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
ProcessData(cmdLine.Text);
FlushCmdLine();
};
thru.Click += (o, e) =>
{
UpdateCmdLine("/");
};
all.Click += (o, e) =>
{
UpdateCmdLine("#");
};
one.Click += (o, e) =>
{
UpdateCmdLine("1");
};
two.Click += (o, e) =>
{
UpdateCmdLine("2");
};
three.Click += (o, e) =>
{
UpdateCmdLine("3");
};
four.Click += (o, e) =>
{
UpdateCmdLine("4");
};
five.Click += (o, e) =>
{
UpdateCmdLine("5");
};
six.Click += (o, e) =>
{
UpdateCmdLine("6");
};
seven.Click += (o, e) =>
{
UpdateCmdLine("7");
};
eight.Click += (o, e) =>
{
UpdateCmdLine("8");
};
nine.Click += (o, e) =>
{
UpdateCmdLine("9");
};
zero.Click += (o, e) =>
{
UpdateCmdLine("0");
};
comma.Click += (o, e) =>
{
UpdateCmdLine(",");
};
connect.Click += (o, e) =>
{
try
{
TextView ip = FindViewById<TextView>(Resource.Id.ipField);
TextView port = FindViewById<TextView>(Resource.Id.portField);
TextView connectionStatus = FindViewById<TextView>(Resource.Id.connectedStatus);
Client = new TcpClient("10.0.2.2", 4711);
connectionStatus.Text = "Connected";
}
catch (System.Exception)
{
}
};
//implementing click functions
}
public void UpdateCmdLine(string update)
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text += update;
}
public void FlushCmdLine()
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text = "";
}
public int[] GetData(string channel, string value)
{
int[] data = new int[] {Int32.Parse(channel), Int32.Parse(value)};
return data;
}
public void SendData(int channel, int data)
{
if (Client.Connected)
{
Stream = Client.GetStream();
byte[] outgoingBytes = new byte[] {Convert.ToByte(channel),Convert.ToByte(data)};
Stream.Write(outgoingBytes,0,outgoingBytes.Length);
}
}
public void ProcessData(string cmdLine)
{
string[] divideStackedOps = cmdLine.Split(',');
foreach (string s in divideStackedOps)
{
if (s.Contains("/"))
{
string[] dividedThru = s.Split('/');
int channel1 = Int32.Parse(dividedThru[0]);
string[] dividedAt = dividedThru[1].Split('#');
int channel2 = Int32.Parse(dividedAt[0]);
int value = Int32.Parse(dividedAt[1]);
for (int e = channel2; e >= channel1; e--)
{
SendData(e, value);
}
}
else if (s.Contains("#"))
{
string[]dividedAll = s.Split('#');
int value = Int32.Parse(dividedAll[1]);
for (int e = 100; e > 0; e--)
{
SendData(e, value);
}
}
}
}
}
}
Server
public class DmxInterface
{
[DllImport("K8062D.dll")]
public static extern void StartDevice();
[DllImport("K8062D.dll")]
public static extern void SetData(int channel, int data);
[DllImport("K8062D.dll")]
public static extern void StopDevice();
[DllImport("K8062D.dll")]
public static extern void SetChannelCount(int count);
}
class Program
{
private static TcpListener Listener;
private static ArrayList Threads = new ArrayList();
public static Boolean ServerStopped;
public static void Main()
{
DmxInterface.StartDevice();
DmxInterface.SetChannelCount(10);
//Initialize Listener, start Listener
int port = 4711;
IPAddress ip = IPAddress.Parse("127.0.0.1");
Listener = new TcpListener(ip, port);
Listener.Start();
Console.WriteLine("Creating new listener on: "+ip+":"+port);
//Initialize MainServerThread, start MainServerThread
Console.WriteLine("Starting MainThread");
Thread mainThread = new Thread(Run);
mainThread.Start();
Console.WriteLine("Done");
while (!ServerStopped)
{
Console.WriteLine("Write 'stop' to stop Server...");
String cmd = "";
cmd = Console.ReadLine();
if (cmd.ToLower().Equals("stop"))
{
Console.WriteLine("stopping server");
ServerStopped = true;
}
else
{
Console.WriteLine("unknow command: " + cmd);
}
}
EndThreads(mainThread);
}
public static void EndThreads(Thread mainThread)
{
//stopping MainThread
mainThread.Abort();
Console.WriteLine("MainThread stopped");
//stopping all Threads
for (IEnumerator e = Threads.GetEnumerator(); e.MoveNext();)
{
//Getting next ServerThread
Console.WriteLine("Stopping the ServerThreads");
ServerThread serverThread = (ServerThread)e.Current;
//Stop it
serverThread.Stop = true;
while (serverThread.Running)
{
Thread.Sleep(1000);
}
}
//Stopping Listener
Listener.Stop();
Console.WriteLine("listener stopped");
Thread.Sleep(5000);
Console.Clear();
}
//opening a new ServerThread
public static void Run()
{
while (true)
{
Console.WriteLine("Listener waiting for connection wish");
//waiting for incoming connection wish
TcpClient client = Listener.AcceptTcpClient();
Threads.Add(new ServerThread(client));
}
}
}
class ServerThread
{
public bool Stop;
public bool Running;
private TcpClient client;
public ServerThread(TcpClient client)
{
this.client = client;
//starting new thread with run() function
Console.WriteLine("Starting new ServerThread");
new Thread(new ThreadStart(Run)).Start();
}
//threaded function
public void Run()
{
Stream stream = null;
Boolean gotstream = false;
Console.WriteLine("Reading incoming Data Stream");
Running = true;
while (!gotstream)
{
//making sure stream is not null to avoid exeption
if (client.GetStream() != null)
{
//getting stream, setting flag true
stream = client.GetStream();
gotstream = true;
}
}
Boolean loop = true;
byte[] incomingValues = new byte[] {255, 255};
Boolean gotData = false;
while (loop)
{
//checking if a remote host is still connected
if (client.Connected)
{
try
{
//reading Byte Array
stream.Read(incomingValues, 0, incomingValues.Length);
gotData = true;
}
catch (Exception e)
{
//catching exeptions
Console.WriteLine("Ooops, something wrent wrogn \n" + e);
loop = false;
}
if (gotData)
{
//converting bytes to int, sending DMX Values
int channel = Convert.ToInt32(incomingValues[0]);
int value = Convert.ToInt32(incomingValues[1]);
DmxInterface.SetData(channel, value);
Console.WriteLine("Received Data... \n Channel: " + channel + " Value: " + value);
}
}
else
{
//exiting loop if connection is lost
Console.WriteLine("connection lost");
Program.ServerStopped = true;
loop = false;
}
}
}
}
}
It is my first program on wifi direct so I made a simple program that just discover all nearby devices and then try to connect to one of them the discovery works fine and gets all the devices the problem is in the connection that always fails after using this function WiFiDirectDevice.FromIdAsync() it keeps paring for too long and then it fails always.
I was following the code on this microsoft tutorial: https://channel9.msdn.com/Events/Build/2015/3-98
Here is my code:
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App7
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DeviceInformationCollection DevicesFound;
WiFiDirectAdvertisementPublisher pub;
WiFiDirectConnectionListener listener;
CancellationTokenSource m_CancellationTokenSource;
private async void button_Click(object sender, RoutedEventArgs e)
{
String DeviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
DevicesFound = await DeviceInformation.FindAllAsync(DeviceSelector);
if(DevicesFound.Count>0)
{
connectedDeviceslist.ItemsSource = DevicesFound;
var dialog = new MessageDialog(DevicesFound[0].Name);
await dialog.ShowAsync();
}
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
int selectedIndex = connectedDeviceslist.SelectedIndex;
String deviceID = DevicesFound[selectedIndex].Id;
var selecetedDevice = DevicesFound[selectedIndex];
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16("1");
connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
m_CancellationTokenSource = new CancellationTokenSource();
var wfdDevice = await WiFiDirectDevice.FromIdAsync(selecetedDevice.Id, connectionParams).AsTask(m_CancellationTokenSource.Token);
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
}
catch(Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
});
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
pub = new WiFiDirectAdvertisementPublisher();
pub.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;
pub.Start();
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var ConnectionRequest = args.GetConnectionRequest();
var tcs = new TaskCompletionSource<bool>();
var dialogTask = tcs.Task;
var messageDialog = new MessageDialog("Connection request received from " + ConnectionRequest.DeviceInformation.Name, "Connection Request");
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand("Accept", null, 0));
messageDialog.Commands.Add(new UICommand("Decline", null, 1));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 1;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
});
var fProceed = await dialogTask;
if (fProceed == true)
{
var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
var wfdDeviceTask = tcsWiFiDirectDevice.Task;
// WriteToOutput("Connecting to " + ConnectionRequest.DeviceInformation.Name + "...");
WiFiDirectConnectionParameters ConnectionParams = new WiFiDirectConnectionParameters();
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
try
{
ConnectionParams.GroupOwnerIntent = 14;
tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id, ConnectionParams));
}
catch (Exception ex)
{
// WriteToOutput("FromIdAsync task threw an exception: " + ex.ToString());
}
});
WiFiDirectDevice wfdDevice = await wfdDeviceTask;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
/* m_ConnectedDevices.Add("dummy", wfdDevice);
WriteToOutput("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort);
StreamSocketListener listenerSocket = new StreamSocketListener();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);*/
}
else
{
/* // Decline the connection request
WriteToOutput("Connection request from " + ConnectionRequest.DeviceInformation.Name + " was declined");
ConnectionRequest.Dispose();*/
}
}
catch (Exception ex)
{
//WriteToOutput("FromIdAsync threw an exception: " + ex.ToString());
}
}
}
}
I having a little issue reading data from Nave32 Flight Controller, I'm able to send data to the card using the SerialDevice class but when the LoadAsync Method is call and there is no more data to read the app hung and does not move forward, there is not exception during the execution of the process. I look at the app state and there is a bunch a task block and I'm not sure why. See image below
UPDATE
Firmware source code is here
here is my example code
namespace Apps.Receiver
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.dataRecived.Text = DateTime.Now.ToString();
}
private async Task readAsync(SerialDevice serialPort)
{
string data = string.Empty;
using (var dataReaderObject = new DataReader(serialPort.InputStream))
{
try
{
dataReaderObject.InputStreamOptions = InputStreamOptions.None;
var hasData = true;
while (hasData)
{
var bytesRead = await dataReaderObject.LoadAsync(serialPort.DataBits);
if (bytesRead > 0)
data += dataReaderObject.ReadString(bytesRead);
else
hasData = false;
}
}
catch (Exception ex)
{
status.Text = "reading data fail: " + ex.Message;
closeDevice(serialPort);
}
}
dataRecived.Text = data;
}
private async void sendData_Click(object sender, RoutedEventArgs e)
{
var serialPort = await getSerialDevice("COM3");
if (dataToSend.Text.Length != 0)
{
using (var dataWriteObject = new DataWriter(serialPort.OutputStream))
{
try
{
if (dataToSend.Text.Equals("#", StringComparison.CurrentCultureIgnoreCase))
dataWriteObject.WriteString(dataToSend.Text);
else
dataWriteObject.WriteString(dataToSend.Text + "\n");
var bytesWritten = await dataWriteObject.StoreAsync();
if (bytesWritten > 0)
{
status.Text = dataToSend.Text + ", ";
status.Text += "bytes written successfully!";
}
await readAsync(serialPort);
}
catch (Exception ex)
{
status.Text = "writing data fail: " + ex.Message;
}
}
closeDevice(serialPort);
}
else
{
status.Text = "Enter the text you want to write and then click on 'WRITE'";
}
}
private void closeDevice(SerialDevice device)
{
device.Dispose();
device = null;
}
private async Task<SerialDevice> getSerialDevice(string portName)
{
var aqs = SerialDevice.GetDeviceSelector("COM3");
var devices = await DeviceInformation.FindAllAsync(aqs);
if (devices.Count == 0)
throw new Exception("Unablet to connect to device");
var serialPort = await SerialDevice.FromIdAsync(devices[0].Id);
if (serialPort == null)
throw new Exception("Unablet to Open to port " + portName);
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
return serialPort;
}
}
}
See this example, try if it helps doing it like this:
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}
I would like to upload file to wcf service from android. The service already open but every time connect to the service it fail, stuck at .connect().
After few minutes it throw Exception:
failed to connect to /10.16.2.56 (port 80): connect failed: ETIMEDOUT
(Connection timed out)
I configure my wcf side almost same as this, please help!
Here my code of android :
try
{
Bitmap bm = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost("http://10.16.2.37/wcf3/service1.svc/GetStream");
ByteArrayBody bab =new ByteArrayBody(data,"001.jpg");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("uploaded", bab);
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
System.out.println("2");
HttpResponse response = httpClient.execute(postRequest);
System.out.println("response");
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
System.out.println("Response: " + s);
}
}
catch (Exception e)
{
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
Its worked for me.
package databaseconnect.databaseconnect;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class MainActivity extends Activity {
private static String SOAP_ACTION = "http://example.com/IService1/InsertData";
private static String NAMESPACE = "http://example.com/";
private static String METHOD_NAME = "InsertData";
private static String URL = "http://example.com/Service1.svc?wsdl";
Button Save,Clear;
EditText name,mobile,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText);
mobile = (EditText) findViewById(R.id.editText2);
email = (EditText) findViewById(R.id.editText3);
Save=(Button)findViewById(R.id.button);
Clear=(Button)findViewById((R.id.clear));
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
Clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name.setText("");
mobile.setText("");
email.setText("");
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params)
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name", name.getText().toString());
request.addProperty("mobile", mobile.getText().toString());
request.addProperty("email", email.getText().toString());
//request.addProperty("name", "testuser");
// request.addProperty("mobile", "123456789");
//request.addProperty("email", "sample#google.com");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
envelope.setOutputSoapObject(request);
String res=null;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,180000);
androidHttpTransport.debug=true;
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (Exception e)
{
name.setText(e.toString());
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Specifically, I need to develop a Desktop app that pulls data from H7 Heart Rate Sensor in C# code.
I have searched everywhere and i cant find nothing to help me.
The closest i cam is with this video (https://www.youtube.com/watch?v=Jn05CU3mxzo&list=UUizfLH6Q2igGUyTWO1bH3YA) tutorial but still it didn't find my H7 Heart Rate Sensor.
namespace _123
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
InitializeComponent();
items = new List<string>();
}
private void bGo_Click(object sender, EventArgs e)//button
{
if (serverStarted)
{
updateUI("server aleredy started");
return;
}
if (rbClient.Checked) {
startScan();
}
else{
connectAsServer();
}
}
private void startScan() {
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan ()
{
updateUI("Starting scan...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan complet");
updateUI(devices.Length.ToString() + "devices discovered");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void connectAsServer()
{
Thread bluetoothServerTherad = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerTherad.Start();
}
private void connectAsClient()
{
}
Guid mUUID = new Guid("ECC037FD-72AE-AFC5-9213-CA785B3B5C63");
bool serverStarted = false;
private void ServerConnectThread()
{
//throw new NotImplementedException();
serverStarted = true;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exeption)
{
updateUI("Client has disconected!");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(deviceInfo.DeviceName + " was selected, attemting connect");
if (pairDevice())
{
updateUI("device paired..");
updateUI("starting conected thread");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start();
}
else
{
updateUI("pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attepting connnection");
client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
client.EndConnect(result);
Stream stream = client.GetStream();
stream.ReadTimeout = 1000;
while (true)
{
while (!ready) ;
stream.Write(message, 0, message.Length);
}
}
string myPin = "1234";
private bool pairDevice()
{
if (!deviceInfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
}
This question is old now but here is my answer. So if you have Polar H7 and you are trying to get the Heart rate then I would recommend follow this Bluetooth Low Energy sample and just run the code it should work fine.
After you run this sample click on start enumerating and it will give you list of all the Bluetooth device .
Then find Polar H7 and click on it.
Go to step 2 and hit Connect and choose characteristic and service and you are done.