Connect PC and Android phone with bluetooth(c#) - c#

I am trying to connect my computer with android phone to transmit some data. For computer programming language i have chosen c#.
On computer the code looks like this:
var wantedAddress="303926627f06";
var addr = BluetoothAddress.Parse(wantedAddress);
var cli = new BluetoothClient();
cli.Connect(addr, new Guid("{00001101-0000-1000-8000-00805f9b34fb}"));
And on a android phone code looks like:
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BluetoothAdapter btAdapter= BluetoothAdapter.getDefaultAdapter();
private BluetoothServerSocket server=btAdapter.listenUsingRfcommWithServiceRecord("App name",uuid);
while(isRunning)
{
try {
BluetoothSocket socket=server.accept();
} catch (IOException e) {
isRunning=false;
e.printStackTrace();
}
}
After trying to connect to the phone i get this error:
SocketException:
The requested address is not valid in its context 303926627F06:0000110100001000800000805f9b34fb
Does anyone know what is wrong?
Thank you for help!
Jure

See error codes at https://32feet.codeplex.com/wikipage?title=Errors So that suggests that the client is not finding the server with the expected UUID running on the target device. Now why...
If you use 32feet.NET SdpBrowser sample and list all the SDP Services "(over L2CAP)" what do you see?
Are you connecting to the correct device address?

Related

Reading Data from a Scanner Connected Through Serial Port

I have an AspNetCore app that i am developing, I have to connect a barcode/Qr code scanner to the client computer, and I have to get the data on the server side and use the data for validation and pass the result to the client side.
Right now, I connected the scanner through Serial Port and can read the data from the barcode/Qr codes, but I think this is because the client/server is being run on the same computer now since I'm developing it.
I would like to ask that after I deploy the app, is there is a way to get the data on the server side after the Qr code/barcode have been scanned on the client side?
Below is my current code which i use to access the data through the serial port.
I created an instance of the serial port and leave it open so that qr codes/barcodes can be scanned continuously
static SerialPort _serialPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
public ActionResult SelectedPN(String nameobj)
{
pn_No= nameobj;
_serialPort.WriteTimeout = 500;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_Data);
if (!_serialPort.IsOpen)
{
try
{
_serialPort.Open();
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
}
When data is received, the Action method which will process the data is called _serialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_Data);
And below is the function
public void mySerialPort_Data(object sender, SerialDataReceivedEventArgs e)
{
if (_serialPort.ReadExisting() != null)
{
newpageList = _db.Categories1;
string data = _serialPort.ReadExisting();
barcode = data.Split(";");
codeValue = barcode[0].Substring(barcode[0].IndexOf(":") + 1);
GetCurrent();
//SelectedPN(pn_No);
}
//_serialPort.Close();
}
This solution works now in development, but I am concerned about when I publish the app. The client and server won't be on the same computer, so this approach probably won't work.
Any help/suggestion would be greatly appreciated.

Receiving data via bluetooth to c# program

I'm using inTheHand library (32feet.NET).
I have a device with bluetooth enabled and I want to connect with the device to my computer and than send data from the device to computer. I then want to catch that information with my program and process it.
The device will send me 3 variables (all 3 float).
How do I catch that information with bluetooth? I never worked with bluetooth on a computer before.
I tried like this post said:
Pair bluetooth devices to a computer with 32feet .NET Bluetooth library
But don't know what I'm doing, so I can't make it work.
I'm using Visual Studio 2017 and Windows 10. I heard there are problems for Windows 10 and authenticating bluetooth devices.
Thanks for all the help!
UPDATE:
static string domaciaddress = "MY_ADDRESS";
static string tujadress = "DEVICE_ADDRESS";
//reciever
private static BluetoothEndPoint EP = new BluetoothEndPoint(BluetoothAddress.Parse(domaciaddress), BluetoothService.BluetoothBase);
private static BluetoothClient BC = new BluetoothClient(EP);
//sender
private static BluetoothDeviceInfo BTDevice = new BluetoothDeviceInfo(BluetoothAddress.Parse(tujadress));
private static NetworkStream stream = null;
static void neke231(string[] args)
{
string paircode = "paircode";
if (BluetoothSecurity.PairRequest(BTDevice.DeviceAddress, paircode))
{
Console.WriteLine("PairRequest: OK");
if (BTDevice.Authenticated)
{
Console.WriteLine("Authenticated: OK");
BC.SetPin(paircode);
BC.BeginConnect(BTDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), BTDevice);
}
else
{
Console.WriteLine("Authenticated: No");
}
}
else
{
Console.WriteLine("PairRequest: No");
}
Console.ReadLine();
}
I now connect to my bluetooth like this. But I still don't know how to get those 3 floats that my device sends, and save it here in float, so I can later in program use them.
EDIT:
This code in fact doesn't work exactly... I don't know why, but it won't connect to android phone. When I run program instead of getting what I write into console, I get only BluetoothGetDeviceInfo returned: 0x80070057

Bluetooth file transfer for Xamarin.Android

I'm trying to connect and send a file from android device to a PC or another smartphone with Xamarin.Android via Bluetooth.
Connection is estabilished, but it doesn't send the file. It doesn't seems to work since there are no exceptions.
int bufferSize = (int)sourceStream.Length;
byte[] byteArray=File.ReadAllBytes("/sdcard/test.txt");
BluetoothSocket socket = device.CreateInsecureRfcommSocketToServiceRecord(UUID.FromString("00001105-0000-1000-8000-00805f9b34fb"));
try
{
await socket.ConnectAsync();
Stream oStream = socket.OutputStream;
oStream.Write(byteArray, 0, bufferSize);
}
catch (Exception ex)
{
//some catching
}
Beside that, do you know any tutorial out there?
I do not know what your receiving code looks like, but you can use the built-in Android BlueTooth Intent.ActionSend Sharing app to start the transfer:
var photoAsset = Assets.OpenFd ("BusinessCard.png");
var javaIOFile = new Java.IO.File (photoAsset.ToString ());
var sendIntent = new Intent (Intent.ActionSend);
sendIntent.SetType ("image/*");
sendIntent.SetComponent (new ComponentName ("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
sendIntent.PutExtra (Intent.ExtraStream, Android.Net.Uri.FromFile (javaIOFile));
StartActivity (sendIntent);
Of course the receiver would have to have their BlueTooth on and accept the connection/transfer.

how can I make a socket connection non-locally?

I tried to search for similar questions but I couldn't since I don't know how to pronounce this question.
My server codes for connection is...
server_Listener = new TcpListener(7778);
server_Listener.Start();
while (true)
{UserSocket user = new UserSocket();
try
{
user.client = server_Listener.AcceptSocket();
}
catch
{
break;
}
if (user.client.Connected)
{
user.server_isClientOnline = true;
this.BeginInvoke((MethodInvoker)(delegate()
{
textBox1.AppendText("client connected\n");
}));
user.server_netStream = new NetworkStream(user.client);
the UserSocket class has a Socket(variable name client), and a netStream (server_netStream) to get to receive and send packet data from clients.
My Question is, this works just fine on local connections, but it doesn't work non-locally.
I tried to access to this server using my laptop, and my friend's, but non of them worked.
Not an error although... but it just couldn't receive the connection.
Are my codes wrong? or are there a new way of getting connection non-locally?
It could be the firewall on your machine or some other issue on your network. You might want to try Wireshark (http://www.wireshark.org/) and see if you can glean any information that way.

How to detect Windows Mobile 5 Device Serial Number? (.NET CF 3.5)

We have several devices where I work (mostly Datalogic 4420 Falcon), and someone is always leaving one off the base. The battery runs dry, then they bring them back to get setup all over. (There's supposed to be a way to configure a file on the SD card to reload upon such an error, but it doesn't work very well)
When someone saves changes on the device (using my app that writes data to the SQL Server), the Serial Number is sent along with it so we can track what devices are in use where.
Each device has a Serial Number, and I have to physically (i.e. manually) write that into the Device name field, which I can read. Working code here if anyone wants to know how:
static string deviceId = null;
public static string DeviceName {
get {
if (String.IsNullOrEmpty(deviceId)) {
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Ident", true)) {
try {
deviceId = key.GetValue("Name", "[Unnamed]").ToString();
} catch (Exception e) {
ErrorWrapper("GetDeviceName", e);
deviceId = Dns.GetHostName();
} finally {
key.Flush();
key.Close();
}
}
}
return deviceId;
}
}
I do not like the manual (i.e. Fat Finger prone) Serial Number entry. Is there some call to query the device's Serial Number, or is that vendor specific?
Datamax does make an SDK that is specific to their devices, but we don't want our applications tied down to any one manufacturer (we are already tied down to VS2008).
I'd start by trying to P/Invoke to get the device ID (KerneIoControl with IOCTL_HAL_GET_DEVICEID) and see if it matches the serial number you're after. Here's an example.
I don't know about your Datalogic 4420 Falcon device, but I work with Intermec CK30 & CK60 and I have their itc50.dll file.
Here is snippet:
[DllImport("itc50.dll")]public static extern int ITCGetSerialNumber(StringBuilder Snumber, int buffSize);
StringBuilder hwSN = new StringBuilder(12);
if (ITCGetSerialNumber(hwSN, hwSN.Capacity) >= 0)
{
;
;
}

Categories

Resources