public MasterPageViewModel(IBluetoothLowEnergyAdapter adapter, IUserDialogs dialogs) { var masterPageItems = new List <MasterPageItem>(); m_dialogs = dialogs; var gattServerPageModel = new GattServerPageModel(dialogs, adapter); var bleScanViewModel = new BleDeviceScannerViewModel( bleAdapter: adapter, dialogs: dialogs, onSelectDevice: async p => { try { await gattServerPageModel.Update(p); await m_rootPage.PushAsync(new GattServerPage(gattServerPageModel)); await gattServerPageModel.OpenConnection(); } catch (Exception e) { throw; } } ); var aa = new BleDeviceScannerPage(bleScanViewModel); m_rootPage = new NavigationPage(new BleDeviceScannerPage(bleScanViewModel)); masterPageItems.Add(new MasterPageItem { Title = "蓝牙模块", IconSource = "contacts.png", navigation = m_rootPage }); masterPageItems.Add(new MasterPageItem { Title = "其他", IconSource = "todo.png", navigation = new NavigationPage(new OtherPage()) }); listView = new ListView { ItemsSource = masterPageItems, ItemTemplate = new DataTemplate(() => { var grid = new Grid { Padding = new Thickness(5, 10) }; grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star }); var image = new Image(); image.SetBinding(Image.SourceProperty, "IconSource"); var label = new Label { VerticalOptions = LayoutOptions.FillAndExpand }; label.SetBinding(Label.TextProperty, "Title"); grid.Children.Add(image); grid.Children.Add(label, 1, 0); return(new ViewCell { View = grid }); }), SeparatorVisibility = SeparatorVisibility.None }; Title = "Personal Organiser"; Padding = new Thickness(0, 40, 0, 0); Content = new StackLayout { Children = { listView } }; }
public async void HandleUrl(Uri url, IBluetoothLowEnergyAdapter adapter) { Data.Set("IsFromScripting", true); Utils.Print("FormsApp: Scripting [ " + Data.Get.IsFromScripting + " ]"); if (this.abortMission) { return; } try { if (ble_interface != null && ble_interface.IsOpen()) { ble_interface.Close(); } #region WE HAVE TO DISABLE THE BLUETOOTH ANTENNA, IN ORDER TO DISCONNECT FROM PREVIOUS CONNECTION, IF WE WENT FROM INTERACTIVE TO SCRIPTING MODE await adapter.DisableAdapter(); await adapter.EnableAdapter(); //Android shows a window to allow bluetooth #endregion } catch (Exception e) { Utils.Print(e.StackTrace); } if (url != null) { //string path = Mobile.ConfigPath; //ConfigPaths(); string path = Mobile.ConfigPath; NameValueCollection query = HttpUtility.ParseQueryString(url.Query); var script_name = query.Get("script_name"); var script_data = query.Get("script_data"); var callback = query.Get("callback"); if (script_name != null) { path = Path.Combine(path, "___" + script_name.ToString()); } if (script_data != null) { File.WriteAllText(path, Base64Decode(script_data)); } if (callback != null) /* ... */ } { if (MainPage == null) // no interactive { tcs1 = new TaskCompletionSource <bool>(); bool result = await tcs1.Task; } await Task.Run(async() => { await Task.Delay(1000); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { //Settings.IsLoggedIn = false; //credentialsService.DeleteCredentials (); MainPage = new NavigationPage(new AclaraViewScripting(path, callback, script_name)); await MainPage.Navigation.PopToRootAsync(true); }); }); } }
public App(IBluetoothLowEnergyAdapter ble) { InitializeComponent(); MainPage = new MainPage(ble); }
public BleDeviceScannerPage(IBluetoothLowEnergyAdapter bleAdapter, IUserDialogs dialogs) { InitializeComponent(); bleAdapterSaved = bleAdapter; dialogsSaved = dialogs; disconnectDevice.Clicked += bleDisconnect; connection(); back_button.Tapped += hamburgerOpen; back_button_menu.Tapped += hamburgerClose; logout_button.Tapped += logout; back_button_detail.Tapped += hamburgerOpen; navigationDrawerList.IsEnabled = false; navigationDrawerList.Opacity = 0.65; ContentNav.IsVisible = false; background_scan_page.Opacity = 1; background_scan_page_detail.Opacity = 1; //MENU //Change username textview to Prefs. String if (Settings.SavedUserName != null) { userName.Text = Settings.SavedUserName; } menuList = new List <PageItem>(); // Creating our pages for menu navigation // Here you can define title for item, // icon on the left side, and page that you want to open after selection var page1 = new PageItem() { Title = "Read MTU", Icon = "readmtu_icon.png", TargetType = "ReadMTU" }; var page2 = new PageItem() { Title = "Turn Off MTU", Icon = "turnoff_icon.png", TargetType = "" }; var page3 = new PageItem() { Title = "Add MTU", Icon = "addMTU.png", TargetType = "AddMTU" }; var page4 = new PageItem() { Title = "Rep. MTU", Icon = "replaceMTU.png", TargetType = "" }; var page5 = new PageItem() { Title = "Rep. Meter", Icon = "replaceMeter.png", TargetType = "" }; var page6 = new PageItem() { Title = "Add MTU / Add meter", Icon = "addMTUaddmeter.png", TargetType = "" }; var page7 = new PageItem() { Title = "Add MTU / Rep. Meter", Icon = "addMTUrepmeter.png", TargetType = "" }; var page8 = new PageItem() { Title = "Rep.MTU / Rep. Meter", Icon = "repMTUrepmeter.png", TargetType = "" }; var page9 = new PageItem() { Title = "Install Confirmation", Icon = "installConfirm.png", TargetType = "" }; // Adding menu items to menuList menuList.Add(page1); menuList.Add(page2); menuList.Add(page3); menuList.Add(page4); menuList.Add(page5); menuList.Add(page6); menuList.Add(page7); menuList.Add(page8); menuList.Add(page9); // Setting our list to be ItemSource for ListView in MainPage.xaml navigationDrawerList.ItemsSource = menuList; }
private void CallToInitApp( IBluetoothLowEnergyAdapter adapter, IUserDialogs dialogs, string appVersion) { // Catch unhandled exceptions AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException; Utils.Print("FormsApp: Interactive [ " + Data.Get.IsFromScripting + " ]"); appVersion_str = appVersion; deviceId = CrossDeviceInfo.Current.Id; // Profiles manager credentialsService = new CredentialsService(); // Initializes Bluetooth ble_interface = new BleSerial(adapter); AppResources.Culture = CrossMultilingual.Current.DeviceCultureInfo; // Config path ConfigPaths(); string Mode = GenericUtilsClass.ChekInstallMode(); if (Data.Get.IsAndroid && Mode.Equals("None")) { var MamServ = DependencyService.Get <IMAMService>(); MamServ.UtilMAMService(); if (Mobile.configData.HasIntune) { GenericUtilsClass.SetInstallMode("Intune"); this.LoadConfigurationAndOpenScene(dialogs); return; } } // var MamServ = DependencyService.Get<IMAMService>(); // MamServ.UtilMAMService(); if (VersionTracking.IsFirstLaunchEver || Mode.Equals("None")) { SecureStorage.RemoveAll(); Device.BeginInvokeOnMainThread(() => { MainPage = new NavigationPage(new AclaraInstallPage()); }); } else { if (Mode.Equals("Intune")) { var MamServ = DependencyService.Get <IMAMService>(); MamServ.UtilMAMService(); } else if (Mode.Equals("FTP")) { // Check if FTP settings is in securestorage GenericUtilsClass.CheckFTPDownload(); } this.LoadConfigurationAndOpenScene(dialogs); } }
/// <summary> /// Attempt to find and connect to the given device by MAC address (6 bytes). Timeout after the default time; /// <see cref="DefaultConnectionTimeout" /> /// </summary> public static Task <IBleGattServer> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter, Guid id) { return(ConnectToDevice(adapter, id, DefaultConnectionTimeout)); }
/// <summary> /// Connect to a discovered <see cref="IBlePeripheral" />. Timeout if the connection is not obtained in /// the provided time /// </summary> public static Task <IBleGattServer> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter, IBlePeripheral device, TimeSpan timeout) { return(adapter.ConnectToDevice(device, new CancellationTokenSource(timeout).Token)); }
/// <summary> /// Scan for nearby BLE device advertisements. Stop scanning after /// <see cref="BluetoothLowEnergyUtils.DefaultScanTimeout" /> /// </summary> /// <param name="adapter">The adapter to use for scanning</param> /// <param name="advertisementDiscovered">Callback to notify for each discovered advertisement</param> public static Task ScanForBroadcasts(this IBluetoothLowEnergyAdapter adapter, Action <IBlePeripheral> advertisementDiscovered) { Contract.Requires <ArgumentNullException>(adapter != null); return(ScanForBroadcasts(adapter, advertisementDiscovered, BluetoothLowEnergyUtils.DefaultScanTimeout)); }
/// <summary> /// Attempt to find and connect to the given device by MAC address (6 bytes). Timeout if the connection is not obtained in /// the provided time /// </summary> public static Task <BleDeviceConnection> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter, Guid id, TimeSpan timeout, Action <ConnectionProgress> progress) { Contract.Requires <ArgumentNullException>(adapter != null); return(ConnectToDevice(adapter, id, timeout, new Progress <ConnectionProgress>(progress))); }
/// <summary> /// Attempt to find and connect to the given device by MAC address (6 bytes). Timeout after the default time; /// <see cref="BluetoothLowEnergyUtils.DefaultConnectionTimeout" /> /// </summary> public static Task <BleDeviceConnection> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter, Guid id, IProgress <ConnectionProgress> progress = null) { Contract.Requires <ArgumentNullException>(adapter != null); return(ConnectToDevice(adapter, id, BluetoothLowEnergyUtils.DefaultConnectionTimeout, progress)); }
/// <summary> /// Scan for nearby BLE device advertisements. Stop scanning after <paramref name="timeout" /> /// </summary> /// <param name="adapter">The adapter to use for scanning</param> /// <param name="advertisementDiscovered">Callback to notify for each discovered advertisement</param> /// <param name="timeout">cancel scan after this length of time</param> public static Task ScanForBroadcasts(this IBluetoothLowEnergyAdapter adapter, Action <IBlePeripheral> advertisementDiscovered, TimeSpan timeout) { Contract.Requires <ArgumentNullException>(adapter != null); return(ScanForBroadcasts(adapter, advertisementDiscovered, new CancellationTokenSource(timeout).Token)); }
public BlePage() { InitializeComponent(); ble = App.Adapter; }
public App(IBluetoothLowEnergyAdapter ble) { InitializeComponent(); BleService.bleAdapter = ble; MainPage = new MainPage(); }
public BluetoothManager() { ble = (Forms.Context as MainActivity).ble; EnableBle(); }
/// <summary> /// Initialize Bluetooth LE Serial port /// </summary> /// <param name="adapter">The Bluetooth Low Energy Adapter from the OS</param> public BleSerial(IBluetoothLowEnergyAdapter adapter) { ble_port_serial = new BlePort(adapter); }
// Public methods public async Task <bool> Initialize(Activity activity, Context context, BLECommandsParser.cmdTableDel_t action) { bool ret = false; try { g_activity = activity; g_context = context; // Initialize bluetooth adapter BluetoothLowEnergyAdapter.Init(activity); // Obtain bluetooth adapter handler g_BLEAdapterObj = BluetoothLowEnergyAdapter.ObtainDefaultAdapter(context); // Enable BLE adapter in case it is disabled. Close application if user denie if (g_BLEAdapterObj.AdapterCanBeEnabled && g_BLEAdapterObj.CurrentState.IsDisabledOrDisabling()) { await g_BLEAdapterObj.EnableAdapter(); if (true == g_BLEAdapterObj.CurrentState.IsDisabledOrDisabling()) { Library.CloseApplication(activity); } } // Suscribe to receive BLE adapter state changes g_BLEAdapterObj_stateChangeObserver = OnBLEAdapter_StateChange; g_BLEAdapterObj.CurrentState.Subscribe(Observer.Create <EnabledDisabledState>(g_BLEAdapterObj_stateChangeObserver, null, null)); // Suscribe to receive Location adapter state changes g_LocationAdapterStateChangeObserver = new OnLocationAdapterStateChange(); activity.RegisterReceiver(g_LocationAdapterStateChangeObserver, new IntentFilter(LocationManager.ProvidersChangedAction)); // Enable location service permissions. Needed to make BLE device scan Permission permissionCheck = ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation); if (permissionCheck != Permission.Granted) { if (true == Android.Support.V4.App.ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.AccessFineLocation)) { Toast.MakeText(activity, "The permission to get BLE location data is required", ToastLength.Short).Show(); } else { activity.RequestPermissions(new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessCoarseLocation }, 1); } } else { Toast.MakeText(activity, "Location permissions already granted", ToastLength.Short).Show(); } // Get Location Manager and check for GPS & Network location services. Ask user to enable them if needed LocationManager lm = (LocationManager)context.GetSystemService(Context.LocationService); if (!lm.IsProviderEnabled(LocationManager.GpsProvider) || !lm.IsProviderEnabled(LocationManager.NetworkProvider)) { EventHandler <DialogClickEventArgs> ButtonClickCb = OnLocationMsgButtonClick; // Build the alert dialog Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(activity); builder.SetTitle("Location Services Not Active"); builder.SetMessage("Please enable Location Services and GPS"); builder.SetPositiveButton("OK", ButtonClickCb); Dialog alertDialog = builder.Create(); alertDialog.SetCanceledOnTouchOutside(false); alertDialog.Show(); } // Initialize BLE Commands Parser g_BLECommandsParserObj = new BLECommandsParser(); Library.cmdTable += action; ret = true; } catch (Exception) { } return(ret); }
public RileyLink(IBluetoothLowEnergyAdapter ble) { this.Ble = ble; }
public App(IBluetoothLowEnergyAdapter adapter) { InitializeComponent(); MainPage = new Bluetooth(adapter); }
/// <summary> /// Connect to a discovered <see cref="IBlePeripheral" />. Timeout after the default time; /// <see cref="DefaultConnectionTimeout" /> /// </summary> public static Task <IBleGattServer> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter, IBlePeripheral device) { return(ConnectToDevice(adapter, device, DefaultConnectionTimeout)); }
/// <summary> /// Attempt to connect to the first device that passes <paramref name="filter" />, and continue the attempt until /// <paramref name="timeout" /> has elapsed. /// </summary> public static Task <BlePeripheralConnectionRequest> FindAndConnectToDevice( [NotNull] this IBluetoothLowEnergyAdapter adapter, ScanSettings settings, TimeSpan timeout, IProgress <ConnectionProgress> progress = null) { return(FindAndConnectToDevice(adapter, settings, new CancellationTokenSource(timeout).Token, progress)); }
/// <summary> /// Scan for nearby BLE device advertisements. Stop scanning after <paramref name="timeout" /> /// </summary> /// <param name="adapter">The adapter to use for scanning</param> /// <param name="advertisementDiscovered">Callback to notify for each discovered advertisement</param> /// <param name="timeout">cancel scan after this length of time</param> public static Task ScanForDevices(this IBluetoothLowEnergyAdapter adapter, IObserver <IBlePeripheral> advertisementDiscovered, TimeSpan timeout) { return(adapter.ScanForDevices(advertisementDiscovered, new CancellationTokenSource(timeout).Token)); }
public BluetoothLowEnergyServer(IBluetoothLowEnergyAdapter adapter) { _adapter = adapter; }