Example #1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ConnectButton.IsEnabled = true;

            if (e.NavigationMode != NavigationMode.Back)
            {
                // Reset page
                ConnectButton.Content        = "Connect";
                Device.Visibility            = Windows.UI.Xaml.Visibility.Collapsed;
                DeviceNoWifi.Visibility      = Windows.UI.Xaml.Visibility.Collapsed;
                DeviceWifiDetails.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                if (e.Parameter is BleDevice && e.Parameter != null)
                {
                    BleDevice device = e.Parameter as BleDevice;

                    DeviceName.Text = device.Name;
                    deviceId        = device.Id;
                }
            }
            else
            {
                // If we're returning from connecting to a network,
                // set up a timer that refreshes the page every 5 seconds.
                timer = new Timer(Timer_Callback, null, 0, 5000);
            }

            base.OnNavigatedTo(e);
        }
Example #2
0
 private void OnDeviceDisconnected(int reason, BleDevice d)
 {
     BluetoothLEPlugin.BleReadyForSyncEvent -= OnReadyForSync;
     //s_LabelText = "";
     m_shouldtick    = false;
     m_currentDevice = null;
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: got OnDeviceDisconnected with reason: " + (disconnectReason)reason + "(" + reason + ")\nBleReadyForSyncEvent unsubscribed");
     }
     if (reason == 8)         //manual Disconnect
     {
         m_status = "Disconnected\nFor new Measurement\npress Update";
         BluetoothLEPlugin.BleDeviceFoundEvent -= OnDeviceFound;
         BluetoothLEPlugin.BleDeviceFoundEvent += OnDeviceFound;
         if (b_Loggin)
         {
             Debug.Log("HeartRateScene: BleDeviceFoundEvent un-/resubscribed");
         }
         m_state = MenuState.START;
         //m_state = MenuState.SCANNING;
         //BluetoothLEPlugin.Scan(90);
     }
     else
     {
         m_status = "Got Disconnected-Event for:\n" + d.Adress + "\nreason: " + (disconnectReason)reason + "\nplease check and hit update";
         clearMAC();
         m_state = MenuState.START;
     }
 }
Example #3
0
        public async Task BleServiceTests_GetGattServicesByDeviceId_Returns_BleGattServices()
        {
            var deviceId    = "deviceId";
            var bMgrDevices = new BleDevice {
                Id = deviceId, Name = "name_1"
            };
            var bMgerDeviceGattServices = new[]
            {
                new BleGattService {
                    DeviceId = "gatt-service-1"
                },
                new BleGattService {
                    DeviceId = "gatt-service-2"
                },
                new BleGattService {
                    DeviceId = "gatt-service-3"
                },
            };

            var bMgr = new Mock <IBleManager>();

            bMgr.Setup(b => b.GetDiscoveredDevices()).Returns(new[] { bMgrDevices });
            bMgr.Setup(b => b.GetDeviceGattServices(It.IsAny <string>()))
            .Returns(Task.FromResult((IEnumerable <BleGattService>)bMgerDeviceGattServices));
            var srv = new BleService(bMgr.Object);

            var res = await srv.GetGattServicesByDeviceId(deviceId);

            res.Result.ShouldBe(ServiceResponseResult.Success);
            res.Data.Count().ShouldBe(bMgerDeviceGattServices.Length);
            foreach (var gt in res.Data)
            {
                bMgerDeviceGattServices.Any(t => t.Uuid == gt.Uuid).ShouldBeTrue();
            }
        }
        /// <summary>
        /// Fired when disconnect-button is clicked
        /// Cleares found ble devices and server, stops websocket server and changes UI
        /// </summary>
        /// <param name="sender">Clicked button</param>
        /// <param name="e">Args</param>
        private void disconnect_Click(object sender, RoutedEventArgs e)
        {
            // Disconnect and clear all found ble devices including server
            watcher.ClearDevices();

            // reset esp server
            espServer = null;

            // Change UI
            blestatus.Foreground = Brushes.Red;
            blestatus.Text       = "Nicht verbunden";

            // Stop websocket server
            wsServer.Stop();

            // If wsServer was successfully stopped
            if (!wsServer.IsListening)
            {
                // Change UI
                wssstatus.Foreground = Brushes.Red;
                wssstatus.Text       = "Nicht verbunden";

                EnableConnect();
                DisableTest();
            }
        }
Example #5
0
        public void BleManager_GetDeviceCharacteristics_NotFound()
        {
            var deviceId = "device-Id";
            var gsUuid   = Guid.Parse("4C088D33-76C6-4094-8C4A-65A80430678A");
            var gs       = new BleGattService {
                DeviceId = deviceId, Uuid = gsUuid
            };

            gs.Characteristics = new BleGattCharacteristic[] { };

            var bleAdapter = new DummyBleAdapter();
            var device     = new BleDevice
            {
                Id   = deviceId,
                Name = "some-device-name"
            };

            var bm = new BleManager(new[] { bleAdapter }, null, null);

            bleAdapter.SetGetGattServices(device, new[] { gs });

            var task = bm.GetDeviceCharacteristics(deviceId, "not-exists-gatt-service-id");

            task.Exception.InnerExceptions.First().ShouldBeOfType <NullReferenceException>();
        }
Example #6
0
        public async Task BleManager_GetDeviceCharacteristics_Found()
        {
            var deviceId = "device-Id";
            var gsUuid   = Guid.Parse("4C088D33-76C6-4094-8C4A-65A80430678A");
            var gs       = new BleGattService {
                DeviceId = deviceId, Uuid = gsUuid
            };

            gs.Characteristics = new BleGattCharacteristic[] { };

            var bleAdapter = new DummyBleAdapter();

            var device = new BleDevice
            {
                Id   = deviceId,
                Name = "some-device-name"
            };

            var bm = new BleManager(new[] { bleAdapter }, null, null);

            bleAdapter.SetGetGattServices(device, new[] { gs });

            var res = await bm.GetDeviceCharacteristics(deviceId, gsUuid.ToString());

            res.ShouldBe(gs.Characteristics);
        }
Example #7
0
        public void BleManager_RegisterToCharacteristicNotificationsasses()
        {
            const string deviceUuid         = "device-Id";
            const string serviceUuid        = "4C088D33-76C6-4094-8C4A-65A80430678A";
            const string characteristicUuid = "some-characteristic-id";
            const string message            = "this is notifucation content";
            var          gs = new BleGattService {
                DeviceId = deviceUuid, Uuid = Guid.Parse(serviceUuid)
            };

            gs.Characteristics = new BleGattCharacteristic[] { };

            var bleAdapter = new DummyBleAdapter();
            var device     = new BleDevice
            {
                Id   = deviceUuid,
                Name = "some-device-name"
            };

            var notifier = new Mock <INotifier>();
            var bm       = new BleManager(new[] { bleAdapter }, notifier.Object, null);

            bleAdapter.SetGetGattServices(device, new[] { gs });

            bleAdapter.RaiseDeviceValueChangedEvent(deviceUuid, serviceUuid, characteristicUuid, message);
            notifier.Verify(n => n.Push(It.Is <string>(s => s == deviceUuid), It.Is <BleDeviceValueChangedEventArgs>(
                                            b =>
                                            b.DeviceUuid == deviceUuid &&
                                            b.ServiceUuid == serviceUuid &&
                                            b.CharacteristicUuid == characteristicUuid &&
                                            b.Message == message)), Times.Once);
        }
Example #8
0
        public void BleManager_ConnectAndDisconnectDevice()
        {
            var dummyAdapter = new DummyBleAdapter();

            var bm     = new BleManager(new[] { dummyAdapter }, null, null);
            var device = new BleDevice
            {
                Id   = "some-device-id",
                Name = "Some-device-Uuid"
            };

            dummyAdapter.RaiseDeviceDiscoveredEvent(device);
            var devices = bm.GetDiscoveredDevices();

            devices.Count().ShouldBe(1);
            var d = devices.First();

            d.Name = device.Name;
            d.Id   = device.Id;

            dummyAdapter.RaiseDeviceConnectedEvent(device);
            devices = bm.GetDiscoveredDevices();
            devices.Count().ShouldBe(1);
            d      = devices.First();
            d.Name = device.Name;
            d.Id   = device.Id;

            dummyAdapter.RaiseDeviceDisconnectedEvent(device);
            devices = bm.GetDiscoveredDevices();
            devices.Count().ShouldBe(1);
        }
Example #9
0
        public async Task BleManager_WriteToCharacteristic(bool writeResult)
        {
            var deviceId         = "device-Id";
            var gattServiceId    = "4C088D33-76C6-4094-8C4A-65A80430678A";
            var characteristicId = "some-characteristic-id";
            var gs = new BleGattService {
                DeviceId = deviceId, Uuid = Guid.Parse(gattServiceId)
            };

            gs.Characteristics = new BleGattCharacteristic[] { };

            var bleAdapter = new DummyBleAdapter();
            var device     = new BleDevice
            {
                Id   = deviceId,
                Name = "some-device-name"
            };

            var bm = new BleManager(new[] { bleAdapter }, null, null);

            bleAdapter.SetGetGattServices(device, new[] { gs });
            bleAdapter.WriteToCharacteristicResult = writeResult;
            var res = await bm.WriteToCharacteristric(deviceId, gattServiceId, characteristicId, new List <byte>());

            res.ShouldBe(writeResult);
        }
Example #10
0
        public async Task BleManager_RegisterToCharacteristicNotifications_Fails(bool readResult)
        {
            var deviceId         = "device-Id";
            var gattServiceId    = "4C088D33-76C6-4094-8C4A-65A80430678A";
            var characteristicId = "some-characteristic-id";
            var gs = new BleGattService {
                DeviceId = deviceId, Uuid = Guid.Parse(gattServiceId)
            };

            gs.Characteristics = new BleGattCharacteristic[] { };

            var bleAdapter = new DummyBleAdapter();
            var device     = new BleDevice
            {
                Id   = deviceId,
                Name = "some-device-name"
            };

            var bm = new BleManager(new[] { bleAdapter }, null, null);

            bleAdapter.SetGetGattServices(device, new[] { gs });
            bleAdapter.BleNotificationResult = readResult;
            var res = await bm.RegisterToCharacteristicNotifications(deviceId, gattServiceId, characteristicId);

            res.ShouldBe(readResult);
        }
Example #11
0
 public void StartScan(BleDevice device)
 {
     _CentralManager = new CBCentralManager(this, null);
     if (device == null)
     {
         throw new Exception("Could not start client without a service type to scan for.");
     }
     _CentralManager.DiscoveredPeripheral += (o, e) =>
     {
         DeviceFound?.Invoke(this, new DeviceEventArgs {
             Device = new BleDevice {
                 Guid = e.Peripheral.UUID.Uuid
             }
         });
     };
     _CentralManager.ConnectedPeripheral += (o, e) =>
     {
         DeviceConnected?.Invoke(this, new DeviceEventArgs {
             Device = new BleDevice {
                 Guid = e.Peripheral.UUID.Uuid
             }
         });
     };
     //_CentralManager.ScanForPeripherals(CBUUID.FromPartial(device.GuidValue));
     _CentralManager.ScanForPeripherals(CBUUID.FromString(device.Guid));
 }
		public FindBleViewModel (INavigation navigation, bool selMeuSkey)
		{
			fim = false;
			this.selMeuSkey = selMeuSkey;
			App.gateSkey = null;  //sKey selecionada se for scan para gateDevice
			keySelecionada = null; //resultado da acao de click em item da lista de sKeys encontrados
			if (selMeuSkey || App.gateSkeys == null)
				devices = new ObservableCollection<BleDevice> ();
			else
				devices = new ObservableCollection<BleDevice> (App.gateSkeys);  //Skeys do ultimo scan

			if (selMeuSkey && MySafetyDll.MySafety.isScanning)
				((App)Application.Current).mysafetyDll.cancelScan ();

			((App)Application.Current).mysafetyDll.Scan += mysafetyDll_Scan;
			_navigation = navigation;

			FindCommand = new Command ((key) => {
				findBleButton = (Button)key;
				scanSkeys ();
			});

			//
			if (devices.Count () == 0)
				scanSkeys ();
		}
Example #13
0
        /// <summary>
        /// Initializes (acquires) the GATT services.
        /// </summary>
        /// <param name="device">The headset device whose services to initialize.</param>
        /// <returns>True, if successful. False otherwise.</returns>
        public async Task <bool> SelectDeviceAsync(BleDevice device)
        {
            IsInitialized = false;

            if (_deviceInformationService != null)
            {
                _deviceInformationService.Device.ConnectionStatusChanged -= OnConnectionStatusChanged;
            }

            SelectedDevice            = device;
            _deviceInformationService = await GattDeviceService.FromIdAsync(device.DeviceInformation.Id);


            if (_deviceInformationService != null)
            {
                foreach (var item in _deviceInformationService.Device.GattServices)
                {
                    _services.Add(item.Uuid, item);
                }

                _deviceInformationService.Device.ConnectionStatusChanged += OnConnectionStatusChanged;

                IsInitialized = await PopulateModelAsync();
            }

            return(IsInitialized);
        }
Example #14
0
 private void OnReadyForSync(BleDevice device)
 {
     m_state = MenuState.CONNECTED;
     BluetoothLEPlugin.BleDeviceConnectEvent -= OnDeviceConnected;
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: BleDeviceConnectEvent unsubscribed");
     }
     HeartRate.OnHRMDataReceived -= On_DataReceived;
     HeartRate.OnHRMDataReceived += On_DataReceived;
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: OnHRMDataReceived un-/resubscribed");
     }
     if (device.GetType().Equals(typeof(HeartRate)))
     {
         m_heartrate = (HeartRate)device;
         m_heartrate.Sync(b_Loggin);
     }
     m_status = "syncing...";
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: Device successfully connected, syncing");
     }
 }
Example #15
0
    private void addToggleDevice(BleDevice device)
    {
        //calculated height of scroll container
        count++;
        scrollHeight = (height + 1.5f) * count;

        containerTransform.offsetMin = new Vector2(4.0f, -scrollHeight);
        containerTransform.offsetMax = new Vector2(-5.0f, 0);

        //create new entry
        GameObject newToggle = Instantiate(Resources.Load("Prefabs/Toggle_Device")) as GameObject;

        newToggle.name = device.mac;
        newToggle.transform.SetParent(deviceScroll.transform, false);

        displayedDevices.Add(device.mac, newToggle);

        RectTransform newRect = newToggle.GetComponent <RectTransform>();

        x = containerTransform.anchorMax.x;
        y = scrollHeight - 1.5f;

        newRect.offsetMax = new Vector2(x, y);

        x = containerTransform.anchorMin.x;
        y = scrollHeight - height;

        newRect.offsetMin = new Vector2(x, y);

        newToggle.GetComponentInChildren <Text>().text = device.ToString();
    }
Example #16
0
 private void OnDeviceConnected(BleDevice device)
 {
     BluetoothLEPlugin.BleReadyForSyncEvent += OnReadyForSync;
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: Device successfully connected and ReadyForSyncEvent subscribed");
     }
 }
Example #17
0
        private void DeviceFound(string name, string address)
        {
            var device = new BleDevice {
                Name = name, Address = address
            };

            _DeviceSource.Add(device);
            Console.WriteLine("new device=" + name + ", mac=" + address);
        }
Example #18
0
        private async void StartScan(Double seconds)
        {
            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);

            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));

            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });

            await m_bleAdapter.ScanForBroadcasts(


                new ScanFilter().AddAdvertisedService("0000fe9a-0000-1000-8000-00805f9b34fb"),

                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var temp     = new BleDevice(peripheral);
                    var existing = FoundDevices.FirstOrDefault(d => d.Address == peripheral.Address.Select(b => b.EncodeToBase16String()).Join(":"));
                    if (existing != null)
                    {
                        existing.Update(temp.abs);
                    }
                    else
                    {
                        FoundDevices.Add(new BlePeripheralViewModel(temp));
                    }
                });
            },
                m_scanCancel.Token);

            IsScanning = false;
        }
Example #19
0
 private void OnDeviceFound(BleDevice device)
 {
     if (b_Loggin)
     {
         Debug.Log("HeartRateScene: DevicefoundEvent received, adding Adress");
     }
     m_status = "Found Device(s)\nplease hit connect";
     m_adresses.Add(device);
 }
Example #20
0
        public void DisconnectDevice(BleDevice device)
        {
            var peripheral = _Connected.FirstOrDefault(p => p.UUID.Uuid.Equals(device.Guid));

            if (peripheral == null)
            {
                return;
            }
            //  TODO: disconnect
        }
Example #21
0
        public void Start(BleDevice device, BleCharacteristic[] characteristics)
        {
            string dataServiceUUIDsKey               = "71DA3FD1-7E10-41C1-B16F-4430B5060000";
            string customBeaconServiceUUIDsKey       = "71DA3FD1-7E10-41C1-B16F-4430B5060001";
            string customBeaconCharacteristicUUIDKey = "71DA3FD1-7E10-41C1-B16F-4430B5060002";
            string identifier = "71DA3FD1-7E10-41C1-B16F-4430B5060003";

            peripheralManager = new CBPeripheralManager(this, DispatchQueue.DefaultGlobalQueue);
            peripheralManager.AdvertisingStarted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("*** BleServer -> Advertising error: {0}", e.Error.Description));
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("*** BleServer -> We are advertising.");
                }
            };


            var customBeaconServiceUUID        = CBUUID.FromString(customBeaconServiceUUIDsKey);
            var customBeaconCharacteristicUUID = CBUUID.FromString(customBeaconCharacteristicUUIDKey);

            var service  = new CBMutableService(customBeaconServiceUUID, true);
            var dataUUID = NSData.FromString(identifier, NSStringEncoding.UTF8);

            var characteristic = new CBMutableCharacteristic(
                customBeaconCharacteristicUUID,
                CBCharacteristicProperties.Read,
                dataUUID,
                CBAttributePermissions.Readable);

            service.Characteristics = new CBCharacteristic[] { characteristic };
            peripheralManager.AddService(service);

            var localName = new NSString("CustomBeacon");

            //var advertisingData = new NSDictionary( CBAdvertisement.DataLocalNameKey, localName,
            //    CBAdvertisement.IsConnectable, false,
            //    CBAdvertisement.DataManufacturerDataKey, CBUUID.FromString(dataServiceUUIDsKey),
            //    CBAdvertisement.DataServiceUUIDsKey, CBUUID.FromString(dataServiceUUIDsKey));

            //peripheralManager.StartAdvertising(advertisingData);



            var UUI = new CBUUID[] { CBUUID.FromString("71DA3FD1-7E10-41C1-B16F-4430B5060000") };

            NSArray arry = NSArray.FromObjects(UUI);
            var     test = NSObject.FromObject(arry);
            var     ad   = new NSDictionary(CBAdvertisement.DataServiceUUIDsKey, test);

            peripheralManager.StartAdvertising(ad);
        }
Example #22
0
 public void ResetAll()
 {
     BleDevice.CancelConnection();
     BleDevice = null;
     CharacteristicAddERC20      = null;
     CharacteristicTransaction   = null;
     CharacteristicTXN           = null;
     CharacteristicUpdateBalance = null;
     CharacteristicGeneralCmd    = null;
     CharacteristicGeneralData   = null;
 }
Example #23
0
 public void postUpdate(BleDevice device)
 {
     if (!displayedDevices.ContainsKey(device.mac))
     {
         addToggleDevice(device);
     }
     else
     {
         updateToggleDevice(device);
     }
 }
Example #24
0
 public BleCyclingSensor(BleDevice dev)
     : base(dev)
 {
     this.ConnectionStateChanged += BleCyclingSensor_ConnectionStateChanged;
     this.ServicesDiscovered     += BleCyclingSensor_ServicesDiscovered;
     this.CharacteristicChanged  += BleCyclingSensor_CharacteristicChanged;
     WheelRev  = 0;
     WheelTime = 0;
     CrankRev  = 0;
     CrankTime = 0;
 }
        private void DeviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Only trigger this if an item is being selected.
            if (e.AddedItems.Count > 0)
            {
                StopScan();

                BleDevice selectedDevice = (BleDevice)e.AddedItems[0];

                this.Frame.Navigate(typeof(DevicePage), selectedDevice);
            }
        }
Example #26
0
        /// <summary>
        /// Read a specified navigation value
        /// </summary>
        /// <param name="value">Navigation value to read</param>
        /// <returns>true if the operation succeeded, false otherwise</returns>
        public async Task <ReadNavigationValueResult> ReadNavigationValue(NavigationValue value)
        {
            ReadNavigationValueResult ret = new ReadNavigationValueResult();

            // List characteristics
            ret.Success = await InitCharacteristics();

            if (ret.Success)
            {
                // Look for the selected characteristic
                BleValue val = new BleValue();
                BleGattCharacteristic nav_characteristic = _navigation_characteristics[value];
                ret.Success = await BleDevice.ReadValueAsync(nav_characteristic, val);

                if (ret.Success)
                {
                    switch (value)
                    {
                    case NavigationValue.Speed:
                    {
                        ret.SpeedValue = val.ToUInt16();
                        break;
                    }

                    case NavigationValue.Latitude:
                    {
                        ret.LatitudeValue = val.ToFloat64();
                        break;
                    }

                    case NavigationValue.Longitude:
                    {
                        ret.LongitudeValue = val.ToFloat64();
                        break;
                    }

                    case NavigationValue.TrackAngle:
                    {
                        ret.TrackAngleValue = val.ToUInt16();
                        break;
                    }

                    default:
                    {
                        ret.Success = false;
                        break;
                    }
                    }
                }
            }

            return(ret);
        }
Example #27
0
        public void DisconnectDevice(BleDevice device)
        {
            var exists = _Connected.FirstOrDefault(d => d.DeviceId.Equals(device.Guid));

            if (exists == null)
            {
                return;
            }
            exists.Dispose();
            _Connected.Remove(exists);
            exists = null;
        }
Example #28
0
    private IEnumerator SendDelayedReportDisconnect(int reason, BleDevice device)      //needed for Bloodpressure and WeightScale
    {
        if (b_Loggin)
        {
            Debug.Log("BluetoothLEPlugin.cs; delayed disconnect");
        }
        yield return(new WaitForSeconds(1.5f));

        if (BleDeviceDisconnectEvent != null)
        {
            BleDeviceDisconnectEvent(reason, device);
        }
    }
Example #29
0
    protected virtual void OnDeviceConnected(BleDevice device)
    {
        Connected = true;
        if (IsDebug)
        {
            Debug.Log("BleDevice: Connected " + GetType().ToString() + " " + Name + ", Adress: " + Adress);
        }

        /*BluetoothLEPlugin.BleDeviceDisconnectEvent -= OnDeviceDisconnected;
         * BluetoothLEPlugin.BleDeviceDisconnectEvent += OnDeviceDisconnected;
         * if (IsDebug)
         *      Debug.Log("BleDevice: BleDeviceDisconnectEvent un-/resubscribed");*/
    }
Example #30
0
 protected virtual void OnDeviceDisconnected(int reason, BleDevice device)
 {
     Connected = false;
     if (IsDebug)
     {
         Debug.Log("BleDevice: Disconnected " + GetType().ToString() + " " + Name + ", Adress: " + Adress + ", Reason: " + ((disconnectReason)reason).ToString());
     }
     BluetoothLEPlugin.BleDeviceDisconnectEvent -= OnDeviceDisconnected;
     BluetoothLEPlugin.BleValueChangeEvent      -= OnDataReceived;
     if (IsDebug)
     {
         Debug.Log("BleDevice: BleDeviceDisconnectEvent and BleValueChangeEvent unsubscribed");
     }
 }
Example #31
0
        public bool ConnectDevice(BleDevice device)
        {
            //  find the device in the list
            var discovered = _Discovered.FirstOrDefault(d => d.Peripheral.UUID.Uuid.Equals(device.Guid));

            if (discovered == null)
            {
                return(false);
            }
            //  connect the device
            _CentralManager.ConnectPeripheral(discovered.Peripheral);
            _Connected.Add(discovered.Peripheral);
            return(true);
        }
		private async void newGateUserCell(string email)
		{
			var gateUser = new GateDevices(email, true);
			if (gateUsers.Contains(gateUser))
			{
				IsBusy = false;
				await notificator.Notify(ToastNotificationType.Error, "MySafety", "Usuario já tem acesso a esse portao", TimeSpan.FromSeconds(3));
				return;
			}

			IsBusy = true;
			var novoUser = new Repository<MysafetyUser>().GetAllAsync().Result.Single(us => us.Email == email);
			if (novoUser == null)
			{
				await notificator.Notify(ToastNotificationType.Error, "MySafety", "Usuario não cadastrado no sistema", TimeSpan.FromSeconds(3));

				//TODO perguntar se deseja enviar convite com link para instalacao do app


				IsBusy = false;
				return;
			}
			IsBusy = false;

			gateUser.Id = novoUser.Id + "_" + SelectedGate.Id;  
			gateUser.Name = novoUser.Nome;
			gateUser.SkeyBleId = novoUser.mySKeyId;
			gateUser.PhoneBleId = novoUser.BleIdCel;
			gateUser.SKeyName = novoUser.mySKeyName;
			gateUser.GateLicId = SelectedGate.Id;
			gateUser.GateBleId = SelectedGate.BleId;
			gateUser.Perfil = "Liberado Geral";
			gateUser.GateDescr = "Portao de " + Settings.nome;
			gateUser.Code = MySafetyDll.MySafety.calculateAccessCode(SelectedGate.BleId, novoUser.BleIdCel,((App)Application.Current).mysafetyDll.localBleAddress);
			gateUsers.Add(gateUser);
			if (!string.IsNullOrEmpty(gateUser.SkeyBleId) && !gateUser.SkeyBleId.Equals("00:00:00:00:00:00"))
			{
				BleDevice naLista = new BleDevice(gateUser.SkeyBleId, gateUser.SKeyName);
				naLista.selecionado = true;   //impede ser mostrado poder ser selecionado em Find
				App.gateSkeys.Add(naLista);
			}
			await(tableDevices.CreateAsync(gateUser));
			Console.WriteLine("Novo gate device  fone:" + gateUser.Name);
		}
		public GerenciarPortoesViewModel (INavigation navigation)
		{
			Navigation = navigation;
			Gates = App.Gates;
			gateUsers = null;

			#pragma warning disable CS4014 
			((App)Application.Current).renovaMeusPortoes ().Wait ();
			if (SelectedGate != null) {
				//Sempre precisa tentar recompor tabela local, pois dados dos usuarios podem ter sido alterados
				//                try
				//                {
//				tableDevices.SyncAsync ("GD" + SelectedGate.Id, tableDevices.table.Where (gs => gs.GateLicId == SelectedGate.Id), true);
				//                }
				//                catch (Exception ex)
				//               {
				//                 Console.WriteLine("Exception  tableDevices.SyncAsync:" + ex.Message);
				//              }

				// Monta lista de todos os usuarios do portao selecionado.
				gateUsers = new ObservableCollection<GateDevices> (tableDevices.GetAllAsync ().
					Result.Where (gs => gs.GateLicId == SelectedGate.Id).OrderBy (ho => ho.labelName));
			}

			#pragma warning restore CS4014 
			Gates = App.Gates; 
			if (gateUsers != null && gateUsers.Count () > 0) {
				App.gateSkeys = new ObservableCollection<BleDevice> ();

				foreach (var user in gateUsers) {
					//Skeys ja inseridos nao devem ser selecionados no Find
					if (!string.IsNullOrEmpty (user.SkeyBleId) && !user.SkeyBleId.Equals ("00:00:00:00:00:00")) {
						BleDevice naLista = new BleDevice (user.SkeyBleId, user.SKeyName);
						naLista.selecionado = true;   //impede poder ser selecionado
						App.gateSkeys.Add (naLista);
					}

					if (!string.IsNullOrEmpty (user.Email)) {
						string Activationcode = MySafetyDll.MySafety.calculateAccessCode (SelectedGate.BleId, user.PhoneBleId, ((App)Application.Current).mysafetyDll.localBleAddress);
						if (!Activationcode.Equals (user.Code)) {
							user.Code = Activationcode;
							#pragma warning disable CS4014 
							tableDevices.UpdateAsync (user).Wait ();
							#pragma warning restore C
						
						}
					}
				}
			} 
			GateOptionsCommand = new Command(async (key) =>
				{
					await transferGateLicense();
				});

			//_hubProxy.On<string>("refreshGateRequests", async msg =>
			//{

			//    string tst = msg;
			//    msg += "";

			//});
		}
Example #34
0
		async private Task PreparandoDll (bool Imediato = false)
		{
			if (!Imediato) {
				timeOut = 20;
				while (timeOut-- > 0)
					await Task.Delay (1000);
			}
			Console.WriteLine ("em PreparandoDll..");
			timeOut = 0;
			int p = 0;
			try {
				p = 1;

				if (meuSkey != null) {
					if (string.IsNullOrEmpty (meuSkey.deviceAddress))
						meuSkey.deviceAddress = "00:00:00:00:00:00";
					else if (!meuSkey.deviceAddress.Equals ("00:00:00:00:00:00") && !(mysafetyDll.meusBLEs.ContainsKey (meuSkey.deviceAddress))) {
						mysafetyDll.meusBLEs.Add (meuSkey.deviceAddress, meuSkey);
						mysafetyDll.setaMeuSkey (meuSkey, false);
						Console.WriteLine ("em PreparaDll*** " + meuSkey);

					} else
						Console.WriteLine ("em PreparaDll.." + meuSkey);
				} else
					Console.WriteLine ("em PreparaDll.. skey null?");

				DadosAlterados = false;
				string userId = Settings.user_Id;

				if (Gates.Count () == 0) {
					inicializando = false;
					return;
				}

				p = 2;
				if (!string.IsNullOrEmpty (userId)) {
					string horariosVerao = String.Format ("{0:ddMM}{1:ddMM}", user.IVerao, user.FVerao);
					if (horariosVerao.Length == 8)
						mysafetyDll.horariosVerao = horariosVerao;

					p = 3;
					//    0 - Montar uma collection com todos os objetos horário.
					Dictionary<String, FaixaHorario> horarios = new Dictionary<String, FaixaHorario> ();

					foreach (var accessTime in HorariosDisponiveis) {
						string diasSemana = String.Empty;
						diasSemana += accessTime.Hol ? "F" : "0";
						diasSemana += accessTime.Mon ? "S" : "0";
						diasSemana += accessTime.Tue ? "T" : "0";
						diasSemana += accessTime.Wed ? "Q" : "0";
						diasSemana += accessTime.Thu ? "Q" : "0";
						diasSemana += accessTime.Fri ? "S" : "0";
						diasSemana += accessTime.Sat ? "S" : "0";
						diasSemana += accessTime.Sun ? "D" : "0";
						FaixaHorario horario = new FaixaHorario (accessTime.Name, accessTime.Start, accessTime.End, diasSemana);
						horario.descricao = accessTime.Name;
						horarios.Add (accessTime.Name, horario);

					}
					p = 4;
					// 1 - montar em uma collection todos os objetos perfil disponíveis.

					Dictionary<String, Perfil> perfis = new Dictionary<String, Perfil> ();


					AccessTimes ac;
					int pos;
					foreach (var accessProfile in Perfis) {
						int tipoPermissao = 0;
						if (accessProfile.IsP)
							tipoPermissao = Perfil.PEDESTRE;
						if (accessProfile.IsA)
							tipoPermissao = Perfil.GARAGEM;
						if (accessProfile.IsA && accessProfile.IsP)
							tipoPermissao = Perfil.BOTH;
						Perfil perfil = new Perfil (accessProfile.Name, accessProfile.Expire, tipoPermissao);
						perfis.Add (accessProfile.Name, perfil);

						//Coloca o nome dos horarios selecionados dentro do objeto perfil
						for (int i = 0; i < 8; i++)
							if (!string.IsNullOrEmpty (accessProfile.AcessTimeId (i))) {
								ac = new AccessTimes (accessProfile.AcessTimeId (i));
								if ((pos = HorariosDisponiveis.IndexOf (ac)) >= 0) {
									ac = HorariosDisponiveis [pos];
									perfil.faixas.Add (horarios [ac.Name]);
								}
							}

					}

					p = 6;
					//Feriados comuns a todos os portoes
					string holidaysStr = String.Empty;

					foreach (var holiday in Holidays)
						if (string.IsNullOrEmpty (holiday.GateLicId))
							holidaysStr += string.Format ("{0:ddMM}", holiday.Date);


					p = 7;

					BleDevice portao = null;
					// loop de portoes
					Console.WriteLine ($"loop com {Gates.Count} portoes");
					foreach (var gate in Gates) {
						portao = new BleDevice (gate.BleId, gate.Name);
						portao.codigoAutorizacao = gate.Code;
						Console.WriteLine ("Activation code: " + gate.Code);
						portao.feriados = holidaysStr;

						//Feriados especificos de um portao
						foreach (var holiday in Holidays)
							if (holiday.GateLicId.Equals (gate.Id))
								portao.feriados += string.Format ("{0:YYYY-dd-MM}", holiday.Date);

						List<MySafetyDll.BleDevice> devices = new List<BleDevice> ();
						var skeysPortao =
							new Repository<GateDevices> ().GetAllAsync ().Result.Where (gd => gd.GateBleId == gate.Id);

						p = 8;

						foreach (var gateDevice in skeysPortao) {
							var bleDevice = new BleDevice (gateDevice.SkeyBleId, gateDevice.SkeyBleId);
							devices.Add (bleDevice);
							if (gateDevice.Perfil != null) {
								if (gateDevice.Perfil.Equals ("Liberado"))
									bleDevice.perfil = MySafetyDll.MySafety.PERFIL_LIBERADO_GERAL;
								else {
									bleDevice.perfil = MySafetyDll.MySafety.PERFIL_BLOQUEADO;
									if (!gateDevice.Perfil.Equals ("Bloqueado")) {
										if (perfis.ContainsKey (gateDevice.Perfil))
											bleDevice.perfil = perfis [gateDevice.Perfil];
									}
								}
							}

							p = 9;
							mysafetyDll.setaPortao (portao);
							mysafetyDll.preparaListaBranca (portao, devices);
						}

						mysafetyDll.setaPortao (portao);
						string result = mysafetyDll.preparaListaBranca (portao, devices);
						if (!string.IsNullOrEmpty (result))
							Console.WriteLine (p + "Erro no prepara dll: " + result + portao + " --- " + mysafetyDll.horariosVerao.Length + mysafetyDll.horariosVerao);
						else {
							Console.WriteLine ("Tudo certo!" + p);
							inicializando = false;
							return;
						}

					}

				}
				Console.WriteLine ("Faltou algo!" + p);
			} catch (Exception ex) {
				Console.WriteLine (p + "   Exception - " + ex.Message);
			}
		}