32Feet.NET. How to pair PC with a device? - bluetooth

I write an application for Windows Form. I have a problem with pairing a device with PC. Now the program works next way: switch on the divece, start the program, add divece to Bluetooth device, push connect button. I use the next functions:
public BluetoothClient client = new BluetoothClient();
public string selectedItem { get; set; }
public BluetoothDeviceInfo[] AllDevices;
public void GetDevices()
{
AllDevices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if(Device.DeviceName.Contains("Kortes"))
onSetDevices(Device.DeviceName); // event to get device name and add it to ComoBox element on form
}
onSetProgress(); // event, that all devices were found, set progress bar and etc.
}
public void GoConnect()
{
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if (Device.DeviceName.Equals(selectedItem)) // item from ComboBox
{
if (!client.Connected)
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
break;
}
else
{
MessageBox.Show("Choose the device");
}
}
}
private void BluetoothClientConnectCallback(IAsyncResult ar)
{
//Have no problem with this
}
These functions work very well. I can find and connect with needed device. But the problem is that firstly I need to add my device to Bluetooth device in OS and enter PIN code. How can I improve my code to solve this problem?
I don't want to add device. I want to work with it directly. Which methods can I use to enter PIN code programmatically? The program must work the next way: switch on the device, start the program, and push connect button.

You are trying to connect without pairing.Your code is not working because you have to pair before connecting.
replace
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
by
BluetoothSecurity.PairRequest(Device.DeviceAddress,"123456");
Check out http://mrbikash.com/bluetooth-discovery-pairing-32feet-net/#pairing for a more detailed explanation.

Related

Android Studio - Cannot Connect to Bluetooth Device

Well, I have everything set up to create a connection to another bluetooth device.
I have a ListView that shows me devices that are paired to my bluetooth device and when I click on the desired device within the listView it should connect to it, but somehow the connection is not being established.
Here is a sample of my paired devices List:
public void getPairedDevices(){
pairedDevices = myBluetoothAdapter.getBondedDevices();
pairedDevices_ArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
if(pairedDevices.size()>0){
for(BluetoothDevice device : pairedDevices){
pairedDevices_ArrayAdapter.add(device.getName()+"\n"+device.getAddress());
}
}
pairedDevices_ListView.setAdapter(pairedDevices_ArrayAdapter);
pairedDevices_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String i = ((TextView) view).getText().toString();
String address = i.substring(i.length() - 17);
deviceToConnectTo = myBluetoothAdapter.getRemoteDevice(address);
connectToDevice(deviceToConnectTo);
}
});
}
And here is my connectToDevice() void:
public void connectToDevice(BluetoothDevice device){
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
myBluetoothAdapter.cancelDiscovery();
} catch (IOException e){}
try{
mmSocket.connect();
} catch (IOException e){
showMsg("Error Connecting to device");
try{
mmSocket.close();
} catch (IOException exception){}
}
}
showMsg is basically a Toast.makeText, it keeps giving me "
Error Connecting to device
toast message, which means that somehow it was impossible to connect.
Can someone tell me why?
I'm using API level 10 and trying to connect to HC-05 Bluetooth Module.
Ok, it seems I managed to fix the problem of not connecting to the HC-05 Bluetooth module. The problem was the UUID I was using.
I changed the UUID to:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
It's used to bluetooth serial boards such as HC-05.

Internet Connectivity Listener in Xamarin.Forms

I am new in Xamarin.Forms and I want to check internet connectivity status in iOS and Android app. In fact using CrossConnectivity Plugins I am able to check internet connectivity successfully but It is not working as Listener. For example, When I open my app and internet connection is not there then it shows me message that "No internet connection" and now if I ON my mobile data then also it shows me same message. I am using below code for this:
string isConnected=CrossConnectivity.Current.IsConnected?"Connected":"No Connection";
My app is not able to listen the changing status of internet connectivity in middle something.
Using the plugin CrossConnectivity, you need to listen to changes via the event ConnectivityChanged, so in your page, or your App class, add this code to write an event handler:
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
//your implementation
this.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};
I have the solution for Android but i haven't started working on ios part
(better than nothing ;)
First Create a broadcastReceiver
public class Localize: BroadcastReceiver
{
public static Context context;
public Localize(Context ctx)
{
context = ctx;
}
public override void OnReceive (Context context, Intent intent)
{
isNetworkAvailable (context);
}
public void isNetworkAvailable(Context context)
{
Boolean state = false;
ConnectivityManager connectivity = (ConnectivityManager)
context.GetSystemService(Context.ConnectivityService);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.GetAllNetworkInfo();
foreach (NetworkInfo nwork in info)
{
if (nwork.GetState () == NetworkInfo.State.Connected) {
ConnectionDetected();//Execute your fonction here
break;
}
}
}
}
Then register your broadcastreceiver with intent in your activity (in MainActivity for example)
IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
receiver = new Localize(this);
RegisterReceiver(receiver, filter);
This should work as long as your application is running.. If you want a service that runs even if your App is killed you should create a service and then register broadcastReceiver in your service..
CrossConnectivity.Current.IsReachable("localhost");
this also works if you download package. I haven't tested it thoroughly

Listbox not always adding item using Windows Azure MobileServiceCollection with WP8

I'm using Windows Azure Mobile Services to store and retrieve data in my Windows Phone 8 app. This is a bit of a complicated issue so I will do my best to explain it.
Firstly I'm using raw push notifications to receive a message and when it receives the message it updates a listbox in my app. When I open my app, navigate to the page with the ListBox and receive a push notification the ListBox updates fine. If I press back, then navigate to the same page with the ListBox, the push notification is received, the code to update the ListBox executes with no errors yet the ListBox doesn't update. I have checked that the same code runs using the OnNavigatedTo handler in both scenarios, but it seems like the ListBox does not bind correctly in the second instance when I press back and then re-navigate to the same page. Here are some code snippets:
MobileServiceCollection declarations:
public class TodoItem
{
public int Id { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
}
private MobileServiceCollection<ToDoItem, ToDoItem> TodoItems;
private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();
Push Notification Received Handler:
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Dispatcher.BeginInvoke(() =>
{
var todoItem = new TodoItem
{
Text = message,
};
ToDoItems.Add(todoItem);
}
);
}
I have tried using:
ListItems.UpdateLayout();
and
ListItems.ItemsSource = null;
ListItems.ItemsSource = ToDoItems;
before and after the code in the above procedure that adds the ToDoItem but it didn't help.
The following procedure is called in my OnNavigatedTo event handler, and refreshes the Listbox and assigns ToDoItems as the items source:
private async void RefreshTodoItems()
{
try
{
ToDoItems = await todoTable
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
ListItems.ItemsSource = ToDoItems;
}
The above procedure is async but I have made sure it completes before receiving any notifications. Even so, as mentioned above when I open the app, navigate to the page that shows the ListBox it updates fine. When I press back, navigate to the same page again, it doesn't work. When I back out of the app, re-open it, navigate to the page with the ListBox, it works again, and then fails if I press back and re-open the page. So it seems the ListBox is not binding to ToDoItems correctly when I press back and navigate to the same page.
Any help appreciated. Thanks.
Can you modify your approach a bit to use Data Binding and the MVVM model to bind your model to your view.
It might look like a bit of effort initially but will save you a lot of debugging hours later on.
Just follow the below steps
Create a new class that implements INotifyPropertyChanged
Add the below method implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Add public ObservableCollection<TodoItem> TodoItems{ get; private set; } and initialize it in the constructor.
Every PhoneApplicationPage has a DataContext member. Assing it to a singleton instance of the above class that you create.
In the XAML, add the property ItemsSource="{Binding TodoItems}" to the list.
In the DataTemplate of the list use ItemsSource="{Binding Text}" for the control you wish to display this value on. ( e.g. TextBlock )
Now whenever you add elements to the collection, it will be reflected in the UI, and vice-versa.

How can I display a dialog on Currently visible activity on BroadcastReceiver?

I have a main Activity (OceanintelligenceActivity). In this activity I register the device for push notifications and also I registered a receiver that shows a Dialog and starts the proper Activity depending on the info sent from my server. This is the code I'm using to register the device and the receiver :
protected void gcmRegistration(){
PMApplication thisApp = PMApplication.getInstance();
AppDelegate delegate = thisApp.getAppDelegate();
final Context context = this;
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
// Let's declare our receiver
registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
Log.d("", "Lets register for Push");
GCMRegistrar.register(this, SENDER_ID);
}else {
if(GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
String apnsToken = delegate.sso.getAPNSToken();
if(!apnsToken.equals(regId)){
Log.d("", "The Device RegId has changed on GCM Servers");
// We should let our servers know about this
ServerUtilities.update(regId, context);
}
} else {
Log.d("","Is not register on PM Server");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
This is how I set the receiver:
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
Log.d("","BroadcastReceiver onReceive");
notificationIntent = GCMIntentService.getNotificationIntent(context);
new AlertDialog.Builder(context)
.setMessage(newMessage+". Would you like to see it right now?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Show update
startActivity(notificationIntent);
}
})
.setNegativeButton("No", null).show();
}
};
GCMIntentService.getNotificationIntent(context). This line returns the the Intent with the Activity I want to start.
Whenever there is a notification onReceive gets called but the Dialog only shows if I am on the main activity. So if the app is on a different activity, onReceive still gets called but the dialog doesn't show and therefore I can't start the proper activity.
How can I display a dialog on Currently visible activity on BroadcastReceiver?
Playing around with this one and searching on google I came across a solution. It is not the best one but it works. I still can't believe there is not an easy way to get the current context in Android. So this is what I did to manage to show the Dialog regardless of what the current activity is : I have a public static property of type Context on my singleton class(AppDelegate) and on each activity I override the onResume method and set the Context to the current activity like this AppDelegate.CURRENT_CONTEXT = this. Then on my dialog : AlertDialog.Builder(AppDelegate.CURRENT_CONTEXT).....

How to get live camera preview in Windows Phone 8

I want to create an application in Windows phone8. In this application i want to show live camera preview with different effect in multiple frame using C# in Windows phone 8. please give me a solution
To use the camera in Windows phone 8 you need to use the PhotoCamera object. Best to create this object on your OnNavigatedTo like so:
protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
{
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
{
cam = new PhotoCamera(CameraType.Primary);
cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
viewfinderBrush.SetSource(cam);
}
else
{
txtMessage.Text = "A Camera is not available on this device."; }
}
}
// dispose when we leave
protected override void OnNavigatingFrom (System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (cam != null)
{
cam.Dispose();
}
}
To actually capture the image from the camera you can then call the CaptureImage method on the cam object.

Resources