public static float GetValue(this ICharacteristic characteristic)
        {
            var value = characteristic.Value;

            if (value.Length == 0)
            {
                throw new Exception("Empty value");
            }
            if (value.Length == 1)
            {
                return((sbyte)value[0]);
            }
            if (value.Length == 2)
            {
                return(BitConverter.ToInt16(value, 0));
            }
            if (value.Length == 4)
            {
                return(BitConverter.ToSingle(characteristic.Value, 0));
            }
            //if (value.Length == 5)
            //{
            //    return BitConverter.ToInt16(characteristic.Value, 3);
            //}
            return(0);
        }
Пример #2
0
        async void Read()
        {
            var chars = await service.GetCharacteristicsAsync();

            charCfg              = chars.FirstOrDefault((x) => x.Id.Equals(GUID_CHAR_CFG));
            charIQ               = chars.FirstOrDefault((x) => x.Id.Equals(GUID_CHAR_IQ));
            charIQ.ValueUpdated += CharOutput_ValueUpdated;
            await charCfg.ReadAsync();

            if (charCfg.Value.Length > 0)
            {
                Estimator = AngleEstimatorFactory.CreateEstimator(charCfg.Value[0]);
                if (Estimator != null)
                {
                    AntCfg.Text = Estimator.Description;
                    await BleDevice.RequestMtuAsync(250);

                    await charIQ.StartUpdatesAsync();
                }
                else
                {
                    AntCfg.Text = string.Format("invalide cfg: {0}", charCfg.Value[0]);
                }
            }
            else
            {
                AntCfg.Text = "Unknown Error";
            }
        }
Пример #3
0
        /// Get Characteristics
        private async void BtnGetcharacters_Clicked(object sender, EventArgs e)
        {
            var builder = new StringBuilder();

            //Guid myServiceUuid = new Guid("166e3275-1b3a-465c-b0e1-3cbc24c5acbe"); // UUID of a known service (Dimming Service)
            try
            {
                Service = await device.GetServiceAsync(myServiceUuid);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Alert", ex.Message, "Ok");

                return;
            }
            //Guid myCharacteristicUuid = Guid.Parse("fe68847f-59ec-4429-9701-74423a4a7ad4"); // UUID of a known characteristic (Dimming Value)
            try
            {
                Characteristic = await Service.GetCharacteristicAsync(myCharacteristicUuid);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Alert", ex.Message, "Ok");

                return;
            }
            Characteristics = await Service.GetCharacteristicsAsync();              // Get all Characteristics of the Service

            foreach (var item in Characteristics)
            {
                builder.Append(item.Name.ToString() + ":\r\n " + item.Id.ToString() + "\r\n");
            }
            builder.Append("FIN CADENA\r\n");
            txtBle.Text = builder.ToString();
        }
Пример #4
0
        public ICharacteristic GetServicesCharacteristic(Constants.CharacteristicsUUID uuid)
        {
            ICharacteristic characterisitic = null;

            foreach (var service in this.Device.Services)
            {
                foreach (var chr in service.Characteristics)
                {
                    if (chr.Uuid.ToString().ToUpper().Contains(uuid.ToString().Replace("_", "")))
                    {
                        Debug.WriteLine("Characteristic Found: " + chr.ID);
                        characterisitic = chr;
                        if (characterisitic.CanUpdate)
                        {
                            if (NotifyStateUpdated == null)
                            {
                                Debug.WriteLine("Subscribing notifystateupdate!");
                                NotifyStateUpdated = new EventHandler <CharacteristicReadEventArgs>(NotifyStateUpdateDone);
                                characterisitic.NotificationStateValueUpdated += NotifyStateUpdateDone;
                            }
                        }
                        break;
                    }
                }
            }

            return(characterisitic);
        }
        public async void ConnectLostAsync()
        {
            _readerState = READERSTATE.READYFORDISCONNECT;

            _characteristicUpdate.ValueUpdated -= BLE_Recv;
            _adapter.DeviceConnectionLost      -= OnDeviceConnectionLost;

            _characteristicUpdate = null;
            _characteristicWrite  = null;
            _service = null;

            try
            {
                if (_device.State == DeviceState.Connected)
                {
                    await _adapter.DisconnectDeviceAsync(_device);
                }
            }
            catch (Exception ex)
            {
            }
            _device = null;

            _readerState = READERSTATE.DISCONNECT;

            FireReaderStateChangedEvent(new Events.OnReaderStateChangedEventArgs(null, Constants.ReaderCallbackType.CONNECTION_LOST));
        }
		void UpdateDisplay (ICharacteristic c) {
			Debug.WriteLine ("UpdateDisplay");
			Name.Text = c.Name;
			ID.Text = c.ID.PartialFromUuid ();

			var s = (from i in c.Value
				select i.ToString ("X").PadRight(2, '0')).ToArray ();
			RawValue.Text = string.Join (":", s);
			StringValue.Text = c.StringValue;


			if (c.ID == 0x2A37.UuidFromPartial ()) {
				// heart rate
				StringValue.Text = DecodeHeartRateCharacteristicValue (c.Value);
				StringValue.TextColor = Color.Red;
			} else if (c.ID == 0x2A38.UuidFromPartial ()) { 
				StringValue.Text = DecodeHeartMonitorPosition (c.Value);
				StringValue.TextColor = Color.Olive;
			} else {
				StringValue.Text = c.StringValue;
				StringValue.TextColor = Color.Default;
			}


		}
Пример #7
0
        async Task Connect()
        {
            using (UserDialogs.Instance.Loading("Connecting..."))
            {
                await retryForever.ExecuteAsync(async() =>
                {
                    device                   = await adapter.ConnectToKnownDeviceAsync(WagonId);
                    var services             = await device.GetServicesAsync();
                    var characs              = await services[3].GetCharacteristicsAsync();
                    tempCharacteristic       = characs[0];
                    programCharacteristic    = characs[1];
                    brightnessCharacteristic = characs[2];
                    paletteCharacteristic    = characs[3];
                    speedCharacteristic      = characs[4];
                    widthCharacteristic      = characs[5];
                    //resetCharacteristic = characs[6];
                    vjCharacteristic     = characs[6];
                    customCharacteristic = characs[7];

                    tempCharacteristic.ValueUpdated += (x, y) =>
                    {
                        Temperature = y.Characteristic.StringValue + "°C";
                    };
                    await tempCharacteristic.StartUpdatesAsync();
                });

                Connected = true;
            }
        }
Пример #8
0
        private async void BtnGetCharactersClicked(object sender, EventArgs e)
        {
            if (Service != null)
            {
                var  serviceUuid = "0000aaa1-0000-1000-8000-aabbccddeeff";
                Guid idGuid      = Guid.Parse(serviceUuid);
                Characteristic = await Service.GetCharacteristicAsync(idGuid);

                if (Characteristic != null)
                {
                    this.RunOnUiThread(() =>
                    {
                        Toast.MakeText(this, "Characteristic: " + Characteristic.Uuid.ToString(), ToastLength.Long).Show();
                    });
                }
                else
                {
                    this.RunOnUiThread(() =>
                    {
                        Toast.MakeText(this, "Characteristic is empty", ToastLength.Long).Show();
                    });
                }
            }
            else
            {
                Toast.MakeText(this, "Service is Empty", ToastLength.Long).Show();
            }
        }
Пример #9
0
 public Descriptor(CBDescriptor nativeDescriptor, CBPeripheral parentDevice, ICharacteristic characteristic, CBCentralManager centralManager)
     : base(characteristic)
 {
     _parentDevice     = parentDevice;
     _nativeDescriptor = nativeDescriptor;
     _centralManager   = centralManager;
 }
        void UpdateDisplay(ICharacteristic c)
        {
            Debug.WriteLine("UpdateDisplay");
            Name.Text = c.Name;
            ID.Text   = c.ID.AssignedNumberFromGuid();

            var s = (from i in c.Value
                     select i.ToString("X").PadRight(2, '0')).ToArray();

            RawValue.Text    = string.Join(":", s);
            StringValue.Text = c.StringValue;


            if (c.ID == 0x2A37.GuidFromAssignedNumber())
            {
                // heart rate
                StringValue.Text      = DecodeHeartRateCharacteristicValue(c.Value);
                StringValue.TextColor = Color.Red;
            }
            else if (c.ID == 0x2A38.GuidFromAssignedNumber())
            {
                StringValue.Text      = DecodeHeartMonitorPosition(c.Value);
                StringValue.TextColor = Color.Olive;
            }
            else
            {
                StringValue.Text      = c.StringValue;
                StringValue.TextColor = Color.Default;
            }
        }
Пример #11
0
 private DataType CharacteristicToDataTypeTranslator(ICharacteristic characteristic)
 {
     //2a18 = GlucoseMeasurement
     //2a37 = HeartRateMeasurement
     //2a1c = TemperatureMeasurement
     //2a49 = BloodPressureFeature
     if (characteristic.Uuid == "2a18")
     {
         return(DataType.ecg);
     }
     if (characteristic.Uuid == "2a37")
     {
         return(DataType.scg);
     }
     if (characteristic.Uuid == "2a1c")
     {
         return(DataType.temp);
     }
     if (characteristic.Uuid == "2a49")
     {
         return(DataType.ppg);
     }
     else
     {
         return(DataType.None);
     }
 }
Пример #12
0
        public CharacteristicDetail_TISensor(IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
        {
            InitializeComponent();
            this.characteristic = characteristic;

            Title = characteristic.Name;
        }
Пример #13
0
        /// <summary>
        ///     Resets the service events.
        /// </summary>
        private void ResetServiceEvents()
        {
            DisConnectFromWand();
            if (_batteryService != null)
            {
                _batteryService.CharacteristicsDiscovered -= ReadCharecteristics;
            }
            if (SelectedDevice != null)
            {
                SelectedDevice.ServicesDiscovered -= ServicesDiscovered;
            }

            Settings       = new BleSettings();
            SelectedDevice = null;
            if (_services != null)
            {
                _services.Clear();
            }

            _temperatureService = null;
            _deviceInfoService  = null;
            _batteryService     = null;

            _measurementTimeChar      = null;
            _measurementScaleChar     = null;
            _autooffIntervalChar      = null;
            _sleepTimeChar            = null;
            _resetAutoOffChar         = null;
            _disConnectPeripheralChar = null;

            _batteryServieOn     = false;
            _temperatureServieOn = false;
            _deviceServieOn      = false;
            Debug.WriteLine("ResetServiceEvents..");
        }
Пример #14
0
        private async void bleDeviceConnected(object sender, DeviceEventArgs e)
        {
            Services = (IList <IService>) await device.GetServicesAsync();

            //Thread.Sleep(500);

            Service = await device.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"));

            //Service = await device.GetServiceAsync(Services[2].Id);

            Characteristics = await Service.GetCharacteristicsAsync();

            //Thread.Sleep(50);
            Characteristic = await Service.GetCharacteristicAsync(Guid.Parse("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));

            //Thread.Sleep(50);
            if (!Characteristic.CanWrite)
            {
                await DisplayAlert("Notice", "Char NOT writable !", "OK");
            }


            isConnected = true;
            addBtnConnectText("Disconnect");
            setStatusText("Device Connected");
            setActIndicator(false);
        }
Пример #15
0
 public Descriptor(BluetoothGattDescriptor nativeDescriptor, BluetoothGatt gatt, IGattCallback gattCallback,
                   ICharacteristic characteristic) : base(characteristic)
 {
     this._gattCallback     = gattCallback;
     this._gatt             = gatt;
     this._nativeDescriptor = nativeDescriptor;
 }
Пример #16
0
        public EngineWarmupStage(IEngine engine) : base(engine)
        {
            warmupCount = engine.TargetJob.Run.WarmupCount;
            var maxSize = ShouldRunAuto(warmupCount) ? MaxIterationCount : warmupCount.SpecifiedValue;

            measurements = new List <Measurement>(maxSize);
        }
        private async Task _start()
        {
            await Task.Delay(1);

            _log("Start", "started");

            _device                     = null;
            _serviceHR                  = null;
            _serviceBattery             = null;
            _characteristicHR           = null;
            _characteristicBatteryLevel = null;

            _status = Status.STATUS_STARTED;

            while (true)
            {
                switch (_status)
                {
                case Status.STATUS_STARTED:
                    _scanningForDevice();
                    break;

                case Status.STATUS_SCANNING_FOR_DEVICE:
                    break;

                case Status.STATUS_CONNECTED:
                    break;

                case Status.STATUS_DEAD:
                    return;     //esce
                }
            }
        }
Пример #18
0
        View MakeView(ICharacteristic c)
        {
            var stack = new StackLayout();

            stack.Padding = 2;
            var label = new Label();

            label.Text  = c.Uuid;
            label.Style = Device.Styles.ListItemTextStyle;
            var prop = new Label();

            prop.Text = "Properties: Read " + BoolToIcon(c.CanRead)
                        + "    Update" + BoolToIcon(c.CanUpdate)
                        + "    Write" + BoolToIcon(c.CanWrite);
            prop.Style = Device.Styles.ListItemDetailTextStyle;
            stack.Children.Add(label);
            stack.Children.Add(prop);
            if (c.CanRead || c.CanUpdate)
            {
                stack.Children.Add(MakeReadView(c));
            }
            if (c.CanWrite)
            {
                stack.Children.Add(MakeWriteView(c));
            }
            stack.Children.Add(label);
            return(stack);
        }
        public CharacteristicManager(IAdapter adapter, IDevice device, IService service, Guid Scratch_Service_Used)
        {
            this.adapter         = adapter;
            this.device          = device;
            this.service         = service;
            this.characteristics = new ObservableCollection <ICharacteristic> ();



            // when characteristics are discovered
            service.CharacteristicsDiscovered += (object sender, EventArgs e) => {
                Debug.WriteLine("service.CharacteristicsDiscovered");
                if (characteristics.Count == 0)
                {
                    Device.BeginInvokeOnMainThread(() => {
                        foreach (var characteristic in service.Characteristics)
                        {
                            if (characteristic.ID == Scratch_Service_Used)
                            {
                                Debug.WriteLine("found characteristic");
                                Characteristic = characteristic;
                                Detail         = new CharacteristicDetails(adapter, device, service, characteristic);
                            }
                        }
                    });
                }
            };

            // start looking for characteristics
            service.DiscoverCharacteristics();
        }
Пример #20
0
 void Device_ServicesDiscovered(object sender, EventArgs e)
 {
     Debug.WriteLine("device.ServicesDiscovered");
     foreach (var service in device.Services)
     {
         Debug.WriteLine("Service: " + service.ID.ToString().ToUpper());
         if (service.ID.ToString().ToUpper().Contains("FF01"))
         {
             Debug.WriteLine("Customer Service identified");
             foreach (var chr in service.Characteristics)
             {
                 Debug.WriteLine("CHARACTERISTIC: " + chr.Uuid.ToString().ToUpper());
                 if (chr.Uuid.ToString().ToUpper().Contains("FF07") || chr.Uuid.ToString().ToUpper().Contains("FF08"))
                 {
                     Debug.WriteLine("FF07/FF08 identified");
                     if (chr.Uuid.ToString().ToUpper().Contains("FF07"))
                     {
                         this.ff07Char = chr;
                     }
                     if (chr.Uuid.ToString().ToUpper().Contains("FF08"))
                     {
                         this.ff08Char = chr;
                     }
                     chr.StartUpdates();
                 }
             }
         }
         else
         {
         }
     }
 }
Пример #21
0
        async void Read()
        {
            charInput = await service.GetCharacteristicAsync(GUID_CHAR_IN);

            charOutput = await service.GetCharacteristicAsync(GUID_CHAR_OUT);

            if (charOutput != null)
            {
                charOutput.ValueUpdated += CharOutput_ValueUpdated;
            }

            switch (Device.RuntimePlatform)
            {
            case Device.UWP:
                MtuSize = int.Parse(MtuInput.Text);
                break;

            default:
                MtuSize      = Math.Max(Utils.BLE_MIN_MTU_SIZE, await BleDevice.RequestMtuAsync(200) - 3);
                MtuInfo.Text = string.Format("MTU = {0} B {1}", MtuSize);
                break;
            }

            BleDevice.UpdateConnectionInterval(ConnectionInterval.High);
        }
Пример #22
0
            public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
            {
                UITableViewCell cell = tableView.DequeueReusableCell(cellID);

                if (cell == null)
                {
                    cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellID);
                }

                ICharacteristic characteristic = this._characteristics [indexPath.Row];

                cell.TextLabel.Text = characteristic.Name;
                StringBuilder descriptors = new StringBuilder();

                if (characteristic.Descriptors != null)
                {
                    foreach (var descriptor in characteristic.Descriptors)
                    {
                        descriptors.Append(descriptor.ID + " ");
                    }
                    cell.DetailTextLabel.Text = descriptors.ToString();
                }
                else
                {
                    cell.DetailTextLabel.Text = "Select to discover characteristic descriptors.";
                }

                return(cell);
            }
Пример #23
0
        Guid myCharacteristicUuid = Guid.Parse("fe68847f-59ec-4429-9701-74423a4a7ad4"); // UUID of a known characteristic (Dimming Value)

        private async void OnSliderChanged(object sender, ValueChangedEventArgs args)
        {
            if (Service == null)
            {
                try { Service = await device.GetServiceAsync(myServiceUuid); }
                catch { return; }
            }
            if (Characteristic == null)
            {
                try { Characteristic = await Service.GetCharacteristicAsync(myCharacteristicUuid); }
                catch { return; }
            }
            double value = args.NewValue;
            //string valor = String.Format("{0:F0}", value);
            int iValue = (int)Math.Round(value);

            //int iValue = Convert.ToByte(value);
            sLabel.Text = iValue.ToString();
            byte[] sliderValue = BitConverter.GetBytes(iValue);
            if (Characteristic.CanWrite)
            {
                try
                {
                    var res = await Characteristic.WriteAsync(sliderValue);
                }
                catch (Exception ex)
                {
                    //await DisplayAlert("Alert", ex.Message ,"Ok");
                }
            }
            //sLabel.Text = BitConverter.ToString(valorb);
            //var characteristic = await GetCharacteristicById(parameters, Guid.Parse("00002A87-0000-1000-8000-00805f9b34fb"));
            //byte[] array = Encoding.UTF8.GetBytes(UserDataMock.Email);
            //characteristic.WriteAsync(array);
        }
Пример #24
0
        async void Read()
        {
            if (service == null)
            {
                return;
            }

            var chars = await service.GetCharacteristicsAsync();

            charLevel = chars.FirstOrDefault((c) => c.Id == GUID_CHAR_BATTERY_LEVEL);
            if (charLevel == null)
            {
                return;
            }

            try
            {
                await charLevel.ReadAsync();

                showLevel();

                if ((charLevel.Properties & (CharacteristicPropertyType.Notify | CharacteristicPropertyType.Indicate)) > 0)
                {
                    useNotify = true;
                    charLevel.ValueUpdated += CharLevel_ValueUpdated;
                    await charLevel.StartUpdatesAsync();
                }

                BtnRefresh.IsVisible = !useNotify;
            }
            catch (Exception)
            { }
        }
        async Task ClearConnection()
        {
            _readerState = READERSTATE.READYFORDISCONNECT;
            // Stop Timer;
            await _characteristicUpdate.StopUpdatesAsync();

            _characteristicUpdate.ValueUpdated -= BLE_Recv;
            _adapter.DeviceConnectionLost      -= OnDeviceConnectionLost;

            _characteristicUpdate = null;
            _characteristicWrite  = null;
            _service = null;

            try
            {
                if (_device.State == DeviceState.Connected)
                {
                    await _adapter.DisconnectDeviceAsync(_device);
                }
            }
            catch (Exception ex)
            {
            }
            _device = null;

            _readerState = READERSTATE.DISCONNECT;
        }
Пример #26
0
        async void Read()
        {
            charCtrl = await service.GetCharacteristicAsync(GUID_CHAR_CTRL);

            charOutput = await service.GetCharacteristicAsync(GUID_CHAR_OUT);

            var charInfo = await service.GetCharacteristicAsync(GUID_CHAR_INFO);

            var info = await charInfo.ReadAsync();

            int size = info[0];

            labelInfo.Text = string.Format("BlockSize = {0} B", size);
            size           = Utils.Att2MTUSize(size);
            var this_size = await BleDevice.RequestMtuAsync(size);

            if (this_size < size)
            {
                if (this_size > 0)
                {
                    var msg = string.Format("Your BLE subsystem can't support required block size ({0} B).", this_size);
                    await DisplayAlert("Error", msg, "OK");

                    return;
                }
                else
                {
                    await DisplayAlert("Warning", "Failed to request MTU exchange\nVoice data might be corrupted.", "OK");
                }
            }
            BleDevice.UpdateConnectionInterval(ConnectionInterval.High);
            charOutput.ValueUpdated += CharOutput_ValueUpdated;
            await charOutput.StartUpdatesAsync();
        }
Пример #27
0
        private async void BtnWOn_Clicked(object sender, EventArgs e)
        {
            //Guid myServiceUuid = new Guid("166e3275-1b3a-465c-b0e1-3cbc24c5acbe"); // UUID of a known service (Dimming Service)
            try
            {
                Service = await device.GetServiceAsync(myServiceUuid);
            }
            catch (Exception ex)
            {
                return;
            }
            //Guid myCharacteristicUuid = Guid.Parse("fe68847f-59ec-4429-9701-74423a4a7ad4"); // UUID of a known characteristic (Dimming Value)
            try
            {
                Characteristic = await Service.GetCharacteristicAsync(myCharacteristicUuid);
            }
            catch
            {
                return;
            }
            if (Characteristic.CanWrite)
            {
                var result = await Characteristic.WriteAsync(new byte[] { 255 });

                if (!result)
                {
                    Debug.WriteLine("CAN'T WRITE TO CHARACTERISTIC");
                }
                else
                {
                    Debug.WriteLine("CHARACTERISTIC WRITTEN");
                }
            }
        }
Пример #28
0
        private async void LvwItems_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            try
            {
                if (lvwItems.SelectedItem != null)
                {
                    device           = lvwItems.SelectedItem as IDevice;
                    connected2Device = await btManager.Connect(device, adapter);

                    if (connected2Device)
                    {
                        CacheProvidor.Set <IDevice>("device", device, DateTime.Now.AddDays(1));
                        characteristic = await btManager.GetCharasteric(device);

                        CacheProvidor.Set <ICharacteristic>("characteristic", characteristic, DateTime.Now.AddDays(1));

                        await Navigation.PushModalAsync(new NavigationPage(new MasterPage()));
                    }
                    else
                    {
                        await DisplayAlert("Foutmelding", "Verbinding maken is mislukt. We scannen opnieuw voor u.", "Ok");

                        StartUp();
                    }
                }
                lvwItems.SelectedItem = null;
            }
            catch (Exception ex)
            {
                await StepOutManager.Writelog(ex);
                await DisplayAlert("Fout", "Er is iets misgelopen bij het connecteren met een bluetooth device, als dit blijft voorkomen gelieve contact op te nemen met de suport.", "Ok");
            }
        }
		public CharacteristicDetail_TISensor (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			Title = characteristic.Name;
		}
Пример #30
0
        private async Task GetMovementService()
        {
            try
            {
                IService service = await device.GetServiceAsync(Guid.Parse("f000aa80-0451-4000-b000-000000000000"));

                ICharacteristic dataCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("f000aa81-0451-4000-b000-000000000000"));

                ICharacteristic configCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("f000aa82-0451-4000-b000-000000000000"));

                await configCharacteristic.WriteAsync(new byte[] { 0x7F, 0x00 });

                _gyro    = new Gyroscope();
                _acc     = new Accelerometer();
                _mag     = new Magnetometer();
                Plates   = new List <Plate>();
                database = new StrongPlateDataService();
                dataCharacteristic.ValueUpdated += (o, args) =>
                {
                    byte[] bytes = args.Characteristic.Value;

                    SetGyro(bytes);
                    SetAcc(bytes);
                    SetMag(bytes);
                    addPlate();
                };
                await dataCharacteristic.StartUpdatesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error GetMovementService: " + ex);
            }
        }
Пример #31
0
        public ICharacteristic GetServicesCharacterisitic(Constants.CharacteristicsUUID uuid)
        {
            ICharacteristic characterisitic = null;

            foreach (var service in this.Device.Services)
            {
                Debug.WriteLine("Service: " + service.ID);
                foreach (var chr in service.Characteristics)
                {
                    Debug.WriteLine("Characteristic: " + chr.ID);
                    if (chr.Uuid.ToString().ToUpper().Contains(uuid.ToString().Replace("_", "")))
                    {
                        Debug.WriteLine("Characteristic Found!");
                        characterisitic = chr;
                        if (characterisitic.CanRead)
                        {
                            if (CharValueUpdated == null)
                            {
                                Debug.WriteLine("Subscribing valueupdated!");
                                CharValueUpdated              = new EventHandler <CharacteristicReadEventArgs>(GetValueFromChar);
                                characterisitic.ValueUpdated += CharValueUpdated;
                            }
                        }
                        break;
                    }
                }
            }

            return(characterisitic);
        }
Пример #32
0
        /// <summary>
        /// Handles the remote date time validation.
        /// </summary>
        /// <remarks>
        /// We validate the DA-12 station time and if it's before 2009 we know
        /// it's not valid, so we set a new time.
        /// We take a Unix timestamp as UTC and formats it into a station command to
        /// update the time.
        /// </remarks>
        /// <param name="txCharacteristic">Bluetooth service characteristic</param>
        /// <param name="remoteUnixDateTime">The remote Unix date time.</param>
        public async Task <bool> HandleRemoteDateTimeValidation(ICharacteristic txCharacteristic, int remoteUnixDateTime)
        {
            // Validate our station Unix time converted to windows time is less
            // than 2009.  If it is we know the station time needs to be set.
            if (remoteUnixDateTime.UnixTimeStampToDateTime().Year < CoreConstants.StationSettingLowestDateTimeYear)
            {
                // Get Unix timestamp "now" as UTC
                Int32 unixTimestampUtc = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                // Format DA-12 station Unix timestamp
                // T - is to set the station time,
                // 0 - is the data type
                // 00 - device index / unused
                // Next set of digits is Unix time UTC (converted to HEX)
                string remoteUnitTimestamp = "{T000" + unixTimestampUtc.ToString("X") + "}";

                // Send set Unix UTC time command to remote
                await txCharacteristic.WriteAsync(remoteUnitTimestamp.StrToByteArray()).ConfigureAwait(true);

                // Wait a couple seconds for remote to process
                await Task.Delay(3000).ConfigureAwait(true);

                // Let caller know we set station time
                return(true);
            }

            // We didn't set station time
            return(false);
        }
Пример #33
0
 async void _adapter_DeviceConnected(object sender, DeviceConnectionEventArgs e)
 {
     var service = await e.Device.GetServiceAsync(Guid.Parse("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"));
     _characteristic = await service.GetCharacteristicAsync(Guid.Parse("d8de624e-140f-4a22-8594-e2216b84a5f2"));
     _characteristic.StartUpdates();
     _characteristic.ValueUpdated += _characteristic_ValueUpdated;
     _device = e.Device;
 }
		void UpdateDisplay (ICharacteristic c) {
			Debug.WriteLine ("UpdateDisplay");
			Name.Text = c.Name;
			ID.Text = c.ID.PartialFromUuid ();

			var s = (from i in c.Value
				select i.ToString ("X").PadRight(2, '0')).ToArray ();
			RawValue.Text = string.Join (":", s);
			StringValue.Text = c.StringValue;
		}
		protected override async void OnAppearing ()
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			if (characteristic.CanRead) {
				var c = await characteristic.ReadAsync();
				UpdateDisplay(c);
			}
		}
		public CharacteristicDetail_TISensor (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			Title = characteristic.Name;

			if (Title.Contains ("Keys Data")) {
				InstructionsText.Text = "Press the two buttons on the TI Sensor to see the data generated below.";
			}
		}
		void UpdateDisplay (ICharacteristic c) {
			Name.Text = c.Name;
			//ID.Text = c.ID.ToString();
			ID.Text = c.ID.PartialFromUuid ();

			var s = (from i in c.Value
					select i.ToString ("X").PadRight(2, '0')).ToArray ();
			RawValue.Text = string.Join (":", s);

			StringValue.Text = c.StringValue;
			StringValue.TextColor = Color.Default;
		}
		public CharacteristicDetail (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			if (characteristic.CanUpdate) {
				characteristic.ValueUpdated += (s, e) => {
					Debug.WriteLine("characteristic.ValueUpdated");
					Device.BeginInvokeOnMainThread( () => {
						UpdateDisplay(characteristic);
					});
				};
				characteristic.StartUpdates();
			}
		}
Пример #39
0
		async Task InitializeAsync ()
		{
			Debug.WriteLine ("LEStream: Looking for service " + ServiceId + "...");
			service = await device.GetServiceAsync (ServiceId);
			Debug.WriteLine ("LEStream: Got service: " + service.ID);

			Debug.WriteLine ("LEStream: Getting characteristics...");
			receive = await service.GetCharacteristicAsync (ReceiveCharId);
			transmit = await service.GetCharacteristicAsync (TransmitCharId);
			reset = await service.GetCharacteristicAsync (ResetCharId);
			Debug.WriteLine ("LEStream: Got characteristics");

			receive.ValueUpdated += HandleReceiveValueUpdated;
			receive.StartUpdates ();
		}
		public CharacteristicDetail (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			if (characteristic.CanUpdate) {
				characteristic.ValueUpdated += (s, e) => {
					Debug.WriteLine("characteristic.ValueUpdated");
					Device.BeginInvokeOnMainThread( () => {
						IsBusy = false; // only spin until the first result is received
						UpdateDisplay(characteristic);
					});

				};
				IsBusy = true;
				characteristic.StartUpdates();
			}
		}
		void UpdateDisplay (ICharacteristic c) {
			Name.Text = c.Name;
			//ID.Text = c.ID.ToString();
			ID.Text = c.ID.PartialFromUuid ();

			var s = (from i in c.Value
					select i.ToString ("X").PadRight(2, '0')).ToArray ();
			RawValue.Text = string.Join (":", s);

			if (c.ID == 0x2A37.UuidFromPartial ()) {
				// heart rate
				StringValue.Text = DecodeHeartRateCharacteristicValue (c.Value);
				StringValue.TextColor = Color.Red;
			} else {
				StringValue.Text = c.StringValue;
				StringValue.TextColor = Color.Default;
			}

		}
Пример #42
0
        public void ProcessCommands()
        {
            Debug.WriteLine("SyncHandler: ProcessCommands");

            if (this.processQeueue.Count > 0)
            {
                command = this.processQeueue.Dequeue();
            }
            else {
                Debug.WriteLine("No more commands to be processed!");
                return;
            }

            switch (command)
            {
                case Constants.SyncHandlerSequence.EnableFF07:
                    Debug.WriteLine("SyncDeviceHandler961: Enabling FF07 characteristic");
                    ff07Char = GetServicesCharacterisitic(Constants.CharacteristicsUUID._FF07);
                    ff07Char.StartUpdates();
                    Task.Delay(500);
                    ProcessCommands();
                    break;
                case Constants.SyncHandlerSequence.EnableFF08:
                    Debug.WriteLine("SyncDeviceHandler961: Enabling FF08 characteristic");
                    ff08Char = GetServicesCharacterisitic(Constants.CharacteristicsUUID._FF08);
                    ff08Char.StartUpdates();
                    Task.Delay(500);
                    ProcessCommands();
                    break;
                case Constants.SyncHandlerSequence.ReadModel:
                    Debug.WriteLine("SyncDeviceHandler961: Reading model from characteristic.");
                    readChar = GetServicesCharacterisitic(Constants.CharacteristicsUUID._2A24);
                    readChar.ReadAsync();
                    break;
                case Constants.SyncHandlerSequence.ReadSerial:
                    Debug.WriteLine("SyncDeviceHandler961: Reading serial from characterisitic.");
                    readChar = GetServicesCharacterisitic(Constants.CharacteristicsUUID._2A25);
                    readChar.ReadAsync();
                    break;
                case Constants.SyncHandlerSequence.ReadFwVersion:
                    Debug.WriteLine("SyncDeviceHandler961: Reading fw version from characteristic.");
                    readChar = GetServicesCharacterisitic(Constants.CharacteristicsUUID._2A26);
                    readChar.ReadAsync();
                    break;
                case Constants.SyncHandlerSequence.ReadManufacturer:
                    Debug.WriteLine("SyncDeviceHandler961: Reading manufacturer from characteristic.");
                    readChar = GetServicesCharacterisitic(Constants.CharacteristicsUUID._2A29);
                    readChar.ReadAsync();
                    break;
                case Constants.SyncHandlerSequence.ReadBatteryLevel:
                    Debug.WriteLine("SyncDeviceHandler961: Reading battery level from characteristic.");
                    readChar = GetServicesCharacterisitic(Constants.CharacteristicsUUID._2A19);
                    readChar.ReadAsync();
                    break;
                default:
                    Debug.WriteLine("SyncDeviceHandler961: Unable to identify command.");
                    break;
            }
        }
Пример #43
0
		public void SendCommand (ICharacteristic handle, byte[] command)
		{
			//handle.ValueUpdated += Handle_ValueUpdated;

			if (handle.CanWrite)
			{
				Console.WriteLine("Adapter: Sending Command");
				handle.Write(command);
			}
			else {
				Console.WriteLine("Unable to write to handle");
			}
		}
 public void CheckMyCharacteristic(ICharacteristic characteristic)
 {
     characteristic.StartUpdates();
 }
		public string Decode (ICharacteristic _characteristic) {
			string output = "";
			double progress = -1; 
			double xb = 0, yb = 0, zb = 0;
			//
			// TI SensorTag hardcoded read/write
			//
			// http://processors.wiki.ti.com/index.php/SensorTag_User_Guide
			//
			Debug.WriteLine ("PopulateValueInfo switch for : " + _characteristic.ID.PartialFromUuid ());
			var sensorData = _characteristic.Value;
			if (_characteristic.ID.PartialFromUuid () == "0xaa01") {
				// Temperature sensorTMP006 - works
				var ambientTemperature = BitConverter.ToUInt16 (sensorData, 2) / 128.0;
				double Tdie = ambientTemperature + 273.15;


				// http://sensortag.codeplex.com/SourceControl/latest#SensorTagLibrary/SensorTagLibrary/Source/Sensors/IRTemperatureSensor.cs
				double Vobj2 = BitConverter.ToInt16 (sensorData, 0);
				Vobj2 *= 0.00000015625;

				double S0 = 5.593E-14;
				double a1 = 1.75E-3;
				double a2 = -1.678E-5;
				double b0 = -2.94E-5;
				double b1 = -5.7E-7;
				double b2 = 4.63E-9;
				double c2 = 13.4;
				double Tref = 298.15;
				double S = S0 * (1 + a1 * (Tdie - Tref) + a2 * Math.Pow ((Tdie - Tref), 2));
				double Vos = b0 + b1 * (Tdie - Tref) + b2 * Math.Pow ((Tdie - Tref), 2);
				double fObj = (Vobj2 - Vos) + c2 * Math.Pow ((Vobj2 - Vos), 2);
				double tObj = Math.Pow (Math.Pow (Tdie, 4) + (fObj / S), .25);

				tObj -= 273.15;

				output = "ambient: " + Math.Round(ambientTemperature,1) + "\nIR: " + Math.Round(tObj,1) + " C";

				// for "graphs"
				xb = tObj * 5;
				yb = ambientTemperature * 5;
			} else if (_characteristic.ID.PartialFromUuid () == "0xaa11") {
				// Accelerometer sensorKXTJ9
				int x = sensorData [0];
				int y = sensorData [1];
				int z = sensorData [2];

				//					x = (byte)((x * 0x0202020202 & 0x010884422010) % 1023); 
				//					y = (byte)((y * 0x0202020202 & 0x010884422010) % 1023); 
				//					z = (byte)((z * 0x0202020202 & 0x010884422010) % 1023); 

				const double KXTJ9_RANGE = 4.0;

				double scaledX = (x * 1.0) / (256.0 / KXTJ9_RANGE);
				double scaledY = (y * 1.0) / (256.0 / KXTJ9_RANGE) * -1; // Orientation of sensor on board means we need to swap Y (multiplying with -1)
				double scaledZ = (z * 1.0) / (256.0 / KXTJ9_RANGE);

				output = String.Format ("scaled: {0}, {1}, {2} xyz", Math.Round(scaledX,2), Math.Round(scaledY,2), Math.Round(scaledZ,2));

			} else if (_characteristic.ID.PartialFromUuid () == "0xaa21") {
				// Humidity sensorSHT21 - works
				int a = BitConverter.ToUInt16 (sensorData, 2);
				a = a - (a % 4);
				double humidity = (-6f) + 125f * (a / 65535f);

				//					int t = BitConverter.ToInt16 (sensorData, 0);
				var t = (sensorData[0] & 0xff) | ((sensorData[1] << 8) & 0xff00); // iono what this sensor is returning :-(

				output = "humidity: " + Math.Round(humidity,1) + "%rH\ntemp: " + Math.Round(t / 1000.0, 1) + "C"; // HACK /1000

			} else if (_characteristic.ID.PartialFromUuid () == "0xaa31") {
				// Magnometer sensorMAG3110

				int x1 = BitConverter.ToInt16 (sensorData, 0);
				int y1 = BitConverter.ToInt16 (sensorData, 2);
				int z1 = BitConverter.ToInt16 (sensorData, 4);

				const double MAG3110_RANGE = 2000.0;
				// calculate acceleration, unit G, range -2, +2
				double x = x1 * (MAG3110_RANGE / 65536f) * -1; //Orientation of sensor on board means we need to swap X (multiplying with -1)
				double y = y1 * (MAG3110_RANGE / 65536f) * -1; //Orientation of sensor on board means we need to swap Y (multiplying with -1)
				double z = z1 * (MAG3110_RANGE / 65536f);

				if (!magno_calibrated) {
					magno_calX = x;
					magno_calY = y;
					magno_calZ = z;
					magno_calibrated = true;
				}

				output = String.Format ("heading: {0}, {1}, {2} /nmag uT", 
					Math.Round(x - magno_calX,1),
					Math.Round(y - magno_calY,1),
					Math.Round(z - magno_calZ,1));
				// TODO: http://cache.freescale.com/files/sensors/doc/app_note/AN4248.pdf?fpsp=1

				// for "graphs"
				xb = 300 + 10 * (x - magno_calX);
				yb = 300 + 10 * (y - magno_calY);
				zb = 300 + 10 * (z - magno_calZ);

			} else if (_characteristic.ID.PartialFromUuid () == "0xaa41") {
				// Barometer
				// TODO: !!!!!!!!!









			} else if (_characteristic.ID.PartialFromUuid () == "0xaa51") {
				// Gyroscope
				int x1 = BitConverter.ToInt16 (sensorData, 0);
				int y1 = BitConverter.ToInt16 (sensorData, 2);
				int z1 = BitConverter.ToInt16 (sensorData, 4);

				const double IMU3000_RANGE = 500.0;

				double x = (x1 * 1.0) / (65536 / IMU3000_RANGE);
				double y = (y1 * 1.0) / (65536 / IMU3000_RANGE);
				double z = (z1 * 1.0) / (65536 / IMU3000_RANGE); 

				if (!gyro_calibrated) {
					gyro_calX = x;
					gyro_calY = y;
					gyro_calZ = z;
					gyro_calibrated = true;
				}

				output = String.Format ("rotation: {0}, {1}, {2} /nxyz degrees/sec", 
					Math.Round(x - gyro_calX,1),
					Math.Round(y - gyro_calY,1),
					Math.Round(z - gyro_calZ,1));

				// for "graphs" 
				xb = 300 + (x - gyro_calX);
				yb = 300 + (y - gyro_calY);
				zb = 300 + (y - gyro_calZ);
			} else if (_characteristic.ID.PartialFromUuid () == "0xffe1") {
				// Smart Keys: Bit 2 - side key, Bit 1 - right key, Bit 0 – left key - works
				var b = ((int)_characteristic.Value[0]) % 4;
				switch (b) {
				case 1:
					output = "Right button";
					break;
				case 2:
					output = "Left button";
					break;
				case 3:
					output = "Both buttons";
					break;
				default:
					output = "Neither button";
					break;
				}
				output += " " + b;
			}

			if (xb > 0) {
				AbsoluteLayout.SetLayoutBounds(Box1, new Rectangle(10, 10, xb, 10));
				AbsoluteLayout.SetLayoutBounds(Box2, new Rectangle(10, 30, yb, 10));
				AbsoluteLayout.SetLayoutBounds(Box3, new Rectangle(10, 50, zb, 10));
			}
			return output;
		}
Пример #46
0
		public void SendCommand (ICharacteristic handle, byte[] command)
		{
			Debug.WriteLine("Subscribers: " + handle.ValueUpdatedSubscribers);
			if (handle.ValueUpdatedSubscribers <= 1)
			{
				handle.ValueUpdated += Handle_ValueUpdated;
			}

			if (handle.CanWrite)
			{
				Console.WriteLine("Adapter: Sending Command");
				handle.Write(command);
			}
			else {
				Console.WriteLine("Unable to write handle");
			}
		}
Пример #47
0
		public async void ProcessCommands()
		{
			Debug.WriteLine("SyncHandler: ProcessCommands");

			if (this.ProcessQeueue.Count > 0)
			{
				Command = this.ProcessQeueue.Dequeue();

			}
			else {
				Debug.WriteLine("No more commands to be processed! Disconnecting device.");
				this.Adapter.DisconnectDevice(this.Device);
				return;
			}

			ICharacteristic chr = null;

			switch (Command)
			{
				case Constants.SyncHandlerSequence.EnableFF07:
					Debug.WriteLine("SyncDeviceHandler961: Enabling FF07 characteristic");
					Ff07Char = GetServicesCharacteristic(Constants.CharacteristicsUUID._FF07);
					if (Ff07Char == null)
					{
						Debug.WriteLine("FF07 is NULL. Disconnecting device.");
						this.Adapter.DisconnectDevice(Device);
					}
					else {
						Ff07Char.StartUpdates();
					}
					break;
				case Constants.SyncHandlerSequence.EnableFF08:
					Debug.WriteLine("SyncDeviceHandler961: Enabling FF08 characteristic");
					Ff08Char = GetServicesCharacteristic(Constants.CharacteristicsUUID._FF08);
					if (Ff08Char == null)
					{
						Debug.WriteLine("FF08 is NULL. Disconnecting device.");
						this.Adapter.DisconnectDevice(Device);
					}
					else {
						Ff08Char.StartUpdates();
					}
					break;
				case Constants.SyncHandlerSequence.ReadModel:
					Debug.WriteLine("SyncDeviceHandler961: Reading model from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A24);
					chr = await ReadChar.ReadAsync();
					int num = 0;
					int.TryParse(System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length).Replace("PE", "").Replace("FT", ""), out num);
					Debug.WriteLine("Model: " + num);
					this.TrioDeviceInformationInstance.ModelNumber = num;
					string[] deviceNameComponents = this.Device.Name.Split(new Char[] {'-'});
					if ( deviceNameComponents.Count() == 3)
						this.TrioDeviceInformationInstance.BroadcastType = deviceNameComponents[1];
					else
						this.TrioDeviceInformationInstance.BroadcastType = "";

					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadSerial:
					Debug.WriteLine("SyncDeviceHandler961: Reading serial from characterisitic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A25);
					chr = await ReadChar.ReadAsync();
					long serial = 0;
					long.TryParse(System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length), out serial);
					Debug.WriteLine("Serial: " + serial);
					this.TrioDeviceInformationInstance.SerialNumber = serial;
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadFwVersion:
					Debug.WriteLine("SyncDeviceHandler961: Reading fw version from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A26);
					chr = await ReadChar.ReadAsync();
					float fwVer = 0;
					float.TryParse(System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length), out fwVer);
					Debug.WriteLine("Firmware Version: " + fwVer);
					this.TrioDeviceInformationInstance.FirmwareVersion = fwVer;
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadManufacturer:
					Debug.WriteLine("SyncDeviceHandler961: Reading manufacturer from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A29);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Manufacturer: " + System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length));
					this.Adapter.CommandResponse += ReceiveResponse;
					//this.isGettingDeviceInformation = false;
					//if (this.ScanType == Constants.ScanType.SYNCING)
					//	this.isGettingDeviceInformation = true;
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadBatteryLevel:
					Debug.WriteLine("SyncDeviceHandler961: Reading battery level from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A19);
					chr = await ReadChar.ReadAsync();
					int battery = (int) chr.Value[0];
					Debug.WriteLine("Battery Level: " + battery);
					this.TrioDeviceInformationInstance.BatteryLevel = battery;
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadTallies:
					Debug.WriteLine("SyncDeviceHandler961: Read Device Tallies");
					CommandRequest = new byte[] { 0x1B, 0x5D };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadDeviceInformation:
					Debug.WriteLine("SyncDeviceHandler961: Read Device Information");
					CommandRequest = new byte[] { 0x1B, 0x40 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadDeviceStatus:
					Debug.WriteLine("SyncDeviceHandler961: Read Device Status");
					CommandRequest = await DeviceStatusInstance.GetReadCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadDeviceSettings:
					Debug.WriteLine("SyncDeviceHandler961: Read Device Settings");
					CommandRequest = await DeviceSettingsInstance.GetReadCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSeizureSettings:
					Debug.WriteLine("SyncDeviceHandler961: Read Seizure Settings");
					CommandRequest = await SeizureSettingsInstance.GetReadCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;	
				case Constants.SyncHandlerSequence.ReadUserSettings:
					Debug.WriteLine("SyncDeviceHandler961: Read User Settings");
					CommandRequest = await UserSettingsInstance.GetReadCommand();
					Debug.WriteLine("Read User Settings: " + Motion.Mobile.Utilities.Utils.ByteArrayToHexString(CommandRequest));
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadStepsHeader:
					Debug.WriteLine("SyncDeviceHandler961: Read Steps Header");
					CommandRequest = await StepsTableDataInstance.GetReadStepTableDataCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSeizureBlocks:
					Debug.WriteLine("SyncDeviceHandler961: Read Seizure Table");
					CommandRequest = await SeizureBlocksDataInstance.GetReadSeizureBlocksDataCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadHourlySteps:
					Debug.WriteLine("SyncDeviceHandler961: Read Hourly Steps");
					DateTime dt = this.currentDateForStepTable;
					CommandRequest = await StepsDataInstance.getReadHourRangeCommand(dt, this.currentStartTimeForStepTable, currentEndTimeForStepTable);
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					Debug.WriteLine("Read Hour Range Settings: " + Motion.Mobile.Utilities.Utils.ByteArrayToHexString(CommandRequest));
					break;
				case Constants.SyncHandlerSequence.ReadCurrentHour:
					Debug.WriteLine("SyncDeviceHandler961: Read Current Hour");
					CommandRequest = await StepsDataInstance.getReadCurrentHourCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSignature:
					Debug.WriteLine("SyncDeviceHandler961: Read Signature Data");
					StepsTableParameters sigData = this.SignatureToBeUploadedTableList.ElementAt(0);
					SignatureDataInstance.SDYear = sigData.dbYear;
					SignatureDataInstance.SDMonth = sigData.dbMonth;
					SignatureDataInstance.SDDay = sigData.dbDay;
					CommandRequest = await SignatureDataInstance.GetReadSignDataCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);

					// insert timer here
					break;
				case Constants.SyncHandlerSequence.ReadSeizure:
					Debug.WriteLine("SyncDeviceHandler961: Read seizure Data");
					SeizureBlockInfo seizureBlock = this.SeizureToBeUploadedList.ElementAt(0);
					SeizureDataInstance.SeizureRecToRead = seizureBlock.sbseizureRecordNo;
					SeizureDataInstance.BlockNumber = seizureBlock.sbSeizureBlock;
					CommandRequest = await SeizureDataInstance.GetReadCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);

					// insert timer here
					break;
				case Constants.SyncHandlerSequence.WriteStepsHeader:
					Debug.WriteLine("SyncDeviceHandler961: Writing steps header");
					CommandRequest = await StepsTableDataInstance.GetWriteStepTableDataCommand(StepTableParamInstance);
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteDeviceSettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing device settings");
					CommandRequest = await DeviceSettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteUserSettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing user settings");
					CommandRequest = await UserSettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteExerciseSettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing exercise settings");
					CommandRequest = await ExerciseSettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteCompanySettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing company settings");
					CommandRequest = await CompanySettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteSignatureSettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing signature settings");
					CommandRequest = await SignatureSettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteSeizureSettings:
					Debug.WriteLine("SyncDeviceHandler961: Writing seizure settings");
					CommandRequest = await SeizureSettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
		          	break;
				case Constants.SyncHandlerSequence.WriteScreenFlow:
					Debug.WriteLine("SyncDeviceHandler961: Writing screenflow settings");
					CommandRequest = await FirmwareDisplaySequenceInstance.GetWriteCommand(this.ScreenFlowList);
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteDeviceSensitivity:
					Debug.WriteLine("SyncDeviceHandler961: Writing device sensitivity settings");
					SensitivitySettingsInstance.SensitivityOld = DeviceDataInstance.TrackerSensitivity;
					CommandRequest = await SensitivitySettingsInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteDeviceStatus:
					Debug.WriteLine("SyncDeviceHandler961: Writing device status settings");
					CommandRequest = await DeviceStatusInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WriteDeviceMode:
					Debug.WriteLine("SyncDeviceHandler961: Writing device mode settings");
					DeviceModeInstance.EnableBroadcastAlways = DeviceDataInstance.AdvertiseMode;
					CommandRequest = await DeviceModeInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;	
				case Constants.SyncHandlerSequence.WriteScreenDisplay:
					Debug.WriteLine("SyncDeviceHandler961: Writing screen display");
					this.ActivationCode = Utils.GetRandomDigits(4); //4 random digits to be generated
					// For testing purposes only
					this.ActivationCode[0] = 0x31;
					this.ActivationCode[1] = 0x32;
					this.ActivationCode[2] = 0x33;
					this.ActivationCode[3] = 0x34;
					// For testing purposes only
					Debug.WriteLine("Random digits: " + Motion.Mobile.Utilities.Utils.ByteArrayToHexString(this.ActivationCode));
					CommandRequest = await DisplayOnScreenInstance.GetWriteCommand(this.ActivationCode);
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ClearEEProm:
					Debug.WriteLine("SyncDeviceHandler961: Clear eeprom");
					ClearEEPROMInstance.ExerciseData = this.clearMessagesOnly?false:true;
					ClearEEPROMInstance.SettingsData = false;
					ClearEEPROMInstance.SurveyQuestions = true;
					ClearEEPROMInstance.Tallies = true;
					ClearEEPROMInstance.MedicineAlarm = true;
					ClearEEPROMInstance.MotivationalQuotes = true;
					CommandRequest = await ClearEEPROMInstance.GetWriteCommand();
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;

				case Constants.SyncHandlerSequence.WsActivateDeviceWithMember:
					Debug.WriteLine("SyncDeviceHandler961: WS Activate Device With Member");
					WSActivateDeviceWithMemberInstance.request.TrackerModel = TrioDeviceInformationInstance.ModelNumber;
					WSActivateDeviceWithMemberInstance.request.TrackerSerialNumber = TrioDeviceInformationInstance.SerialNumber;
					WSActivateDeviceWithMemberInstance.request.TrackerBtAdd = "";
					WSActivateDeviceWithMemberInstance.request.ApplicationID = UserInformationInstance.ApplicationID;
					WSActivateDeviceWithMemberInstance.request.MemberDermID = UserInformationInstance.MemberID;
					WSActivateDeviceWithMemberInstance.request.TrackerFirmwareVersion = TrioDeviceInformationInstance.FirmwareVersion;
					this.status = await WSActivateDeviceWithMemberInstance.PostRequest();

					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");
						if (WSActivateDeviceWithMemberInstance.response != null)
						{
							this.SetSettingsFromActivateDeviceWithMemberResponseWS(WSActivateDeviceWithMemberInstance.response);
							ProcessCommands();
						}


					}
					else
					{
						Debug.WriteLine("ActivateDeviceWithMemeber Response is " + WSActivateDeviceWithMemberInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					//this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.WsGetDeviceInfo:
					Debug.WriteLine("SyncDeviceHandler961: WS Request GetDeviceInfo");
					WSGetDeviceInformationInstance.request.TrackerModel = TrioDeviceInformationInstance.ModelNumber;
					WSGetDeviceInformationInstance.request.TrackerSerialNumber = TrioDeviceInformationInstance.SerialNumber;
					WSGetDeviceInformationInstance.request.DeviceDateTime = Motion.Mobile.Utilities.Utils.GetDeviceDateTimeWithFormat(DateTime.Now);
					WSGetDeviceInformationInstance.request.ApplicationID = UserInformationInstance.ApplicationID;
					WSGetDeviceInformationInstance.request.DevicePairingStatus = 1;
					WSGetDeviceInformationInstance.request.TrackerFirmwareVersion = TrioDeviceInformationInstance.FirmwareVersion;
					this.status = await WSGetDeviceInformationInstance.PostRequest();

					this.ServerReadTimeDuration = 0;
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");
						if (WSGetDeviceInformationInstance.response != null)
						{
							this.isResettingTrio = false;
							timerForServer = new Timer(timerCallBack, new object(), 0, 1000);
							timerForServer.Increment += TimerForServer_Increment;
							this.SetSettingsFromGetDeviceInfoResponseWS(WSGetDeviceInformationInstance.response);
							ProcessCommands();
						}
						else
						{
							Debug.WriteLine("WS Request GetDeviceInfo Response is " + WSGetDeviceInformationInstance.response.ResponseMessage);
							this.Adapter.DisconnectDevice(this.Device);
						}

					}
					//else if  Tobe Added?
					else if (string.Equals(WSGetDeviceInformationInstance.response.ResponseStatus, "reset"))
					{
						this.isResettingTrio = true;
						DeviceStatusInstance.PairingStatus = 1;
						this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.WriteDeviceStatus);
						this.ProcessCommands();
						Debug.WriteLine("Device Not Paired...");
					}
					else
					{ 
						Debug.WriteLine("Get Device Info Failed :(");
					}
						


					break;

				case Constants.SyncHandlerSequence.WsUploadTallies:
					Debug.WriteLine("SyncDeviceHandler961: WS Upload Tallies");

					WSUploadTalliesDataInstance.request.DeviceModel = TrioDeviceInformationInstance.ModelNumber;
					WSUploadTalliesDataInstance.request.DeviceSerial = TrioDeviceInformationInstance.SerialNumber;
					WSUploadTalliesDataInstance.request.MemberDeviceID = UserInformationInstance.MemberDeviceId;
					WSUploadTalliesDataInstance.request.ApplicationID = UserInformationInstance.ApplicationID;
					WSUploadTalliesDataInstance.request.PlatformID = UserInformationInstance.PlatformID;
					WSUploadTalliesDataInstance.request.DeviceDateTime = Motion.Mobile.Utilities.Utils.GetServerDateTimeFromString(MemberServerProfileInstance.ServerDateTime);
					WSUploadTalliesDataInstance.request.talliesData = TalliesDataInstance;

					this.status = await WSUploadTalliesDataInstance.PostRequest();

					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");

						if (ApplicationInfoInstance.ApplicationID > 0 && ApplicationInfoInstance.PlatformID > 0)
						{
							if ((AppUpdateSettingsInstance.UpdateFlag && AppUpdateSettingsInstance.UpdateType != 2) || !AppUpdateSettingsInstance.UpdateFlag)
							{
								if (!this.clearTracker)
								{
									this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.ReadSeizureSettings);
									this.ProcessCommands();
								}

							}

						}

						else
						{
							this.isValidateAppInfo = true;
							this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.WsSendAppInfo);
							this.ProcessCommands();
						}


					}
					else
					{
						Debug.WriteLine("Upload Tallies Response is " + WSUploadTalliesDataInstance.response.ResponseStatus);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;
				case Constants.SyncHandlerSequence.WsUploadSteps:
					Debug.WriteLine("SyncDeviceHandler961: WS Upload Steps");
					this.CreateUploadStepsDataRequest(WSUploadStepsDataInstance.request);
					this.status = await WSUploadStepsDataInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");
						if (this.isReadingCurrentHour)
						{
							//READ_DEVICE_SETTING
							this.checkTimeDifferenceAndUpdateDeviceTime();
						}
						else
						{
							//UpdateStepDataTable
							StepTableParamInstance = this.UpdateStepDataTable();
							this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.WriteStepsHeader);
							this.ProcessCommands();

						}

					}
					else
					{
						Debug.WriteLine("Upload Steps Response is " + WSUploadStepsDataInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;
				case Constants.SyncHandlerSequence.WsUploadSignature:
					Debug.WriteLine("SyncDeviceHandler961: WS Upload Signature");
					this.CreateUploadSignatureRequestData(WSUploadSignatureDataInstance.request);
					this.status = await WSUploadSignatureDataInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");
						if (this.SignatureToBeUploadedTableList.Count() > 0)
						{
							this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.ReadSignature);
							this.ProcessCommands();
						}
						else
						{
							if (this.MemberServerProfileInstance.UpdateFlag > 0)
							{
								this.UpdateSettingsFlag(Utils.USER_SETTINGS_BIT_LOC);
							}
							else
							{
								//if(READ SURVEY)
								//else
								// update settings 
								//CLEAR_MESSAGES_SETTINGS_BIT_LOC
								this.UpdateSettingsFlag(Utils.CLEAR_MESSAGES_SETTINGS_BIT_LOC);
							}
						}
							

					}
					else
					{
						Debug.WriteLine("Upload Signature Response is " + WSUploadSignatureDataInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;
				case Constants.SyncHandlerSequence.WsUploadProfile:
					break;
				case Constants.SyncHandlerSequence.WsUnpairDevice:
					Debug.WriteLine("SyncDeviceHandler961: WS Unpair Device");
					WSUnpairMemberDeviceInstance.request.DeviceID = WSActivateDeviceWithMemberInstance.response.DeviceID;
					WSUnpairMemberDeviceInstance.request.MemberID = UserInformationInstance.MemberID;
					WSUnpairMemberDeviceInstance.request.MemberDeviceID = UserInformationInstance.MemberDeviceId;
					this.status = await WSUploadSeiureDataInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Deactivating Device Successful");
					}
					break;
				case Constants.SyncHandlerSequence.WsUploadSeizure:
					Debug.WriteLine("SyncDeviceHandler961: WS Upload Seizure");
					this.CreateUploadSeizureRequestData(WSUploadSeiureDataInstance.request);
					this.status = await WSUploadSeiureDataInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("Success");
						if (this.SeizureToBeUploadedList.Count() > 0)
						{
							this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.ReadSeizure);
							this.ProcessCommands();
						}
						else
						{
							if (this.SignatureToBeUploadedTableList.Count() > 0)
							{
								this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.ReadSignature);
								this.ProcessCommands();
							}
							else
							{
								if (this.MemberServerProfileInstance.UpdateFlag > 0)
								{
									this.UpdateSettingsFlag(Utils.USER_SETTINGS_BIT_LOC);
								}
								else
								{
									//if(READ SURVEY)
									//else
									// update settings 
									//CLEAR_MESSAGES_SETTINGS_BIT_LOC
									this.UpdateSettingsFlag(Utils.CLEAR_MESSAGES_SETTINGS_BIT_LOC);
								}
							}
						}


					}
					else
					{
						Debug.WriteLine("Upload Seizure Response is " + WSUploadSeiureDataInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;
				case Constants.SyncHandlerSequence.WsSendNotifySettingsUpdate:
					Debug.WriteLine("SyncDeviceHandler961: WS Notify Settings Update");

					DateTime currentDateTime = DateTime.Now;

					long dateTimeInUnix = (long)Motion.Mobile.Utilities.Utils.DateTimeToUnixTimestamp(currentDateTime);

					DateTime dateTime = new DateTime(DeviceSettingsInstance.Year + 2000, DeviceSettingsInstance.Month, DeviceSettingsInstance.Day, DeviceSettingsInstance.Hour, DeviceSettingsInstance.Minute, DeviceSettingsInstance.Second);
					dateTime.AddSeconds(this.DeviceReadTimeDuration);

					WSNotifySettingsUpdateInstance.request.MemberID = UserInformationInstance.MemberID;
					WSNotifySettingsUpdateInstance.request.MemberDeviceID = UserInformationInstance.MemberDeviceId;
					WSNotifySettingsUpdateInstance.request.LastSyncSettingDateTime = dateTimeInUnix;
					WSNotifySettingsUpdateInstance.request.TrackerModel = TrioDeviceInformationInstance.ModelNumber;
					WSNotifySettingsUpdateInstance.request.UpdateFlag = MemberServerProfileInstance.UpdateFlag;
					WSNotifySettingsUpdateInstance.request.SettingType = MemberServerProfileInstance.UpdateFlagChanges;
					WSNotifySettingsUpdateInstance.request.DevicePairingStatus = DeviceStatusInstance.PairingStatus;
					WSNotifySettingsUpdateInstance.request.DeviceDateTime = Motion.Mobile.Utilities.Utils.GetDeviceDateTimeWithFormat(dateTime);
					WSNotifySettingsUpdateInstance.request.BatteryLevel = TrioDeviceInformationInstance.BatteryLevel;


					this.status = await WSNotifySettingsUpdateInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("WS Notify Settings Update Successful");
					}
					else
					{
						Debug.WriteLine("WS Notify Settings Update Response is " + WSNotifySettingsUpdateInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;
				case Constants.SyncHandlerSequence.WsUploadCommandResponse:
					Debug.WriteLine("SyncDeviceHandler961: WS Upload Command Response");
					WSUploadCommandResponseInstance.request.commandRespData.UploadCommand = 0x58;
					WSUploadCommandResponseInstance.request.DeviceModel = TrioDeviceInformationInstance.ModelNumber;
					WSUploadCommandResponseInstance.request.DeviceSerial = TrioDeviceInformationInstance.SerialNumber;
					WSUploadCommandResponseInstance.request.MemberDeviceID = UserInformationInstance.MemberDeviceId;
					WSUploadCommandResponseInstance.request.ApplicationID = UserInformationInstance.ApplicationID;
					WSUploadCommandResponseInstance.request.PlatformID = UserInformationInstance.PlatformID;
					WSUploadCommandResponseInstance.request.SynchronizationID = this.MemberServerProfileInstance.SynchronizationID;
					this.status = await WSUploadCommandResponseInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("WS Upload Command Successful!");
					}
					else
					{
						Debug.WriteLine("WS Upload Command Response is " + WSUploadCommandResponseInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;	
				case Constants.SyncHandlerSequence.WsSendAppInfo:
					Debug.WriteLine("SyncDeviceHandler961: WS Validate App Info");
					WSSendAppInfoInstance.request.ApplicationName = ApplicationInfoInstance.ApplicationName;
					WSSendAppInfoInstance.request.ApplicationVersion = ApplicationInfoInstance.ApplicationVersion;
					WSSendAppInfoInstance.request.OperatingSystem = ApplicationInfoInstance.OperatingSystem;
					WSSendAppInfoInstance.request.OperatingSystemVersion = ApplicationInfoInstance.OperatingSystemVersion;
					WSSendAppInfoInstance.request.PlatformType = ApplicationInfoInstance.PlatformType;
					WSSendAppInfoInstance.request.Brand = ApplicationInfoInstance.Brand;
					WSSendAppInfoInstance.request.Model = ApplicationInfoInstance.Model;
					WSSendAppInfoInstance.request.Manufacturer = ApplicationInfoInstance.Manufacturer;
					WSSendAppInfoInstance.request.CommunicationType = ApplicationInfoInstance.CommunicationType;
					this.status = await WSSendAppInfoInstance.PostRequest();
					if (this.status == WebServiceRequestStatus.SUCCESS)
					{
						Debug.WriteLine("WS Validate App Info Successful");

						this.UserInformationInstance.ApplicationID = WSSendAppInfoInstance.response.ApplicationID;
						this.UserInformationInstance.PlatformID = WSSendAppInfoInstance.response.PlatformID;
						if (this.isValidateAppInfo)
						{
							this.ApplicationInfoInstance.ApplicationID = WSSendAppInfoInstance.response.ApplicationID;
							this.ApplicationInfoInstance.PlatformID = WSSendAppInfoInstance.response.PlatformID;
							if ((AppUpdateSettingsInstance.UpdateFlag && AppUpdateSettingsInstance.UpdateType != 2) || !AppUpdateSettingsInstance.UpdateFlag)
							{
								if (!this.clearTracker)
									this.ProcessCommands();
								else
								{
									this.ProcessQeueue.Enqueue(Constants.SyncHandlerSequence.WriteDeviceSettings);
									this.ProcessCommands();
								}
							}

						}
						else
						{ 
							this.AppUpdateSettingsInstance.UpdateType = WSSendAppInfoInstance.response.appUpdateInfo.UpdateType;
						}

					}
					else
					{
						Debug.WriteLine("WS Validate App Info Response is " + WSUploadCommandResponseInstance.response.ResponseMessage);
						this.Adapter.DisconnectDevice(this.Device);
					}
					break;	
				default:
					Debug.WriteLine("SyncDeviceHandler961: Unable to identify command.");
					break;
			}

		}
				public CharacteristicSelectedEventArgs (ICharacteristic characteristic)
				{
					this._characteristic = characteristic;
				}
		public void ProcessCommands()
		{
			Debug.WriteLine("SyncDeviceHandlerStriiv: ProcessCommands");

			if (this.ProcessQeueue.Count > 0)
			{
				Command = this.ProcessQeueue.Dequeue();

			}
			else {
				Debug.WriteLine("No more commands to be processed!");
				return;
			}

			ICharacteristic chr = null;

			switch (Command)
			{
				case Constants.StriivSyncHandlerSequence.EnableFE23:
					Debug.WriteLine("SyncDeviceHandlerSTRIIV: Enabling FE23 characteristic");
					CharFE23 = GetServicesCharacteristic(Constants.CharacteristicsUUID._FE23);
					if (CharFE23 == null)
					{
						Debug.WriteLine("FE23 is NULL. Disconnecting device.");
						this.Adapter.DisconnectDevice(Device);
					}
					else {
						CharFE23.StartUpdates();
					}
					break;
				case Constants.StriivSyncHandlerSequence.Ack:
					Debug.WriteLine("Ack response");
					CommandRequest = new byte[] { 0x08 };
					this.Adapter.SendCommand(Char9A0A, CommandRequest);
					break;
				case Constants.StriivSyncHandlerSequence.DeviceInfo:
					Debug.WriteLine("Read Device Info");
					CommandRequest = new byte[] { 0x06 };
					this.Adapter.SendCommand(Char9A0A, CommandRequest);
					break;
				case Constants.StriivSyncHandlerSequence.RegisterRead:
					Debug.WriteLine("Register Read Command");
					CommandRequest = new byte[] { 0x00 };
					this.Adapter.SendCommand(Char9A0A, CommandRequest);
					break;
				case Constants.StriivSyncHandlerSequence.RegisterWrite:
					Debug.WriteLine("Register Write Time");
					//CommandRequest = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x30, 0x1E, 0x02, 0x16, 0x07, 0x07, 0xE0 };
					CommandRequest = new byte[19];
					CommandRequest[0] = 0x01;
					CommandRequest[1] = 0x00;
					CommandRequest[2] = 0x00;
					CommandRequest[3] = 0x01;//00
					CommandRequest[4] = 0x1E;//01
					CommandRequest[5] = 0x0F;//02
					CommandRequest[6] = 0x0B;//03
					CommandRequest[7] = 0x18;//04
					CommandRequest[8] = 0x08;//05
					CommandRequest[9] = 0x7E;//06
					CommandRequest[10] = 0x00;//07
					CommandRequest[11] = 0x00;//08
					CommandRequest[12] = 0x00;//09
					CommandRequest[13] = 0x00;//10
					CommandRequest[14] = 0x00;//11
					CommandRequest[15] = 0x00;//12
					CommandRequest[16] = 0x00;//13
					CommandRequest[17] = 0x00;//14
					CommandRequest[18] = 0x00;//15

					this.Adapter.SendCommand(Char9A0A, CommandRequest);
					break;
				case Constants.StriivSyncHandlerSequence.FileLoadList:
					Debug.WriteLine("Reading File Load List");
					CommandRequest = new byte[] { 0x02, 0x01 };
					this.Adapter.SendCommand(Char9A0A, CommandRequest);
					break;
				default:
					Debug.WriteLine("Invalid command request...");
					break;
			}
		}
		public void StartSync(Constants.ScanType scanType)
		{
			Debug.WriteLine("SyncDeviceHandlerStriiv: Start syncing....");

			Char9A0A = GetServicesCharacteristic(Constants.CharacteristicsUUID._9A0A);
			this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.EnableFE23);
			//this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.DeviceInfo);
			//this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.RegisterWrite);
			//this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.RegisterRead);
			this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.FileLoadList);
			//this.ProcessQeueue.Enqueue(Constants.StriivSyncHandlerSequence.DeviceInfo);

			this.ProcessCommands();
		}
 public CharacteristicReadEventArgs(ICharacteristic characteristic)
 {
     Characteristic = characteristic;
 }
 public CharacteristicWriteEventArgs(ICharacteristic characteristic, bool isSuccessful)
 {
     Characteristic = characteristic;
     IsSuccessful = isSuccessful;
 }
		public void SetDeviceServiceAndCharacteristic (IDevice device, IService service, ICharacteristic characteristic)
		{
			this._connectedDevice = device;
			this._currentService = service;
			this._characteristic = characteristic;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothLE.Core.Events.CharacteristicDiscoveredEventArgs"/> class.
		/// </summary>
		/// <param name="characteristic">The characteristic that was discovered.</param>
		public CharacteristicDiscoveredEventArgs(ICharacteristic characteristic)
		{
			Characteristic = characteristic;
		}
Пример #55
0
		public async void ProcessCommands()
		{
			Debug.WriteLine("SyncHandler: ProcessCommands");

			if (this.ProcessQeueue.Count > 0)
			{
				Command = this.ProcessQeueue.Dequeue();

			}
			else {
				Debug.WriteLine("No more commands to be processed!");
				return;
			}

			ICharacteristic chr = null;

			switch (Command)
			{
				case Constants.SyncHandlerSequence.EnableFF07:
					Debug.WriteLine("SyncDeviceHandler936: Enabling FF07 characteristic");
					Ff07Char = GetServicesCharacteristic(Constants.CharacteristicsUUID._FF07);
					if (Ff07Char == null)
					{
						Debug.WriteLine("FF07 is NULL. Disconnecting device.");
						this.Adapter.DisconnectDevice(Device);
					}
					else {
						Ff07Char.StartUpdates();
					}
					break;
				case Constants.SyncHandlerSequence.EnableFF08:
					Debug.WriteLine("SyncDeviceHandler936: Enabling FF08 characteristic");
					Ff08Char = GetServicesCharacteristic(Constants.CharacteristicsUUID._FF08);
					if (Ff08Char == null)
					{
						Debug.WriteLine("FF08 is NULL. Disconnecting device.");
						this.Adapter.DisconnectDevice(Device);
					}
					else {
						Ff08Char.StartUpdates();
					}
					break;
				case Constants.SyncHandlerSequence.ReadModel:
					Debug.WriteLine("SyncDeviceHandler936: Reading model from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A24);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Model: " + System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length));
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadSerial:
					Debug.WriteLine("SyncDeviceHandler936: Reading serial from characterisitic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A25);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Serial: " + System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length));
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadFwVersion:
					Debug.WriteLine("SyncDeviceHandler936: Reading fw version from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A26);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Firmware Version: " + System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length));
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadManufacturer:
					Debug.WriteLine("SyncDeviceHandler936: Reading manufacturer from characteristic.");
					this.StartIncrementProgress = true;
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A29);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Manufacturer: " + System.Text.Encoding.UTF8.GetString(chr.Value, 0, chr.Value.Length));
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadBatteryLevel:
					Debug.WriteLine("SyncDeviceHandler936: Reading battery level from characteristic.");
					ReadChar = GetServicesCharacteristic(Constants.CharacteristicsUUID._2A19);
					chr = await ReadChar.ReadAsync();
					Debug.WriteLine("Battery Level: " + (int)chr.Value[0]);
					ProcessCommands();
					break;
				case Constants.SyncHandlerSequence.ReadDeviceStatus:
					Debug.WriteLine(": Read Device Status");
					CommandRequest = new byte[] { 0x1B, 0x13 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadDeviceSettings:
					Debug.WriteLine("SyncDeviceHandler936: Read Device Settings");
					CommandRequest = new byte[] { 0x1B, 0x17 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadUserSettings:
					Debug.WriteLine("SyncDeviceHandler936: Read User Settings");
					CommandRequest = new byte[] { 0x1B, 0x19 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadStepsHeader:
					Debug.WriteLine("SyncDeviceHandler936: Read Steps Header");
					CommandRequest = new byte[] { 0x1B, 0x22 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSeizureTable:
					Debug.WriteLine("SyncDeviceHandler936: Read Seizure Table");
					break;
				case Constants.SyncHandlerSequence.ReadHourlySteps:
					Debug.WriteLine("SyncDeviceHandler936: Read Steps Header");
					//CommandRequest = new byte[] { 0x1B, 0x24, 0x };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadCurrentHour:
					Debug.WriteLine("SyncDeviceHandler936: Read Current Hour");
					CommandRequest = new byte[] { 0x1B, 0x27 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSignature:
					Debug.WriteLine("SyncDeviceHandler936: Read Signature Data");
					//CommandRequest = new byte[] { 0x1B, 0x27 };
					this.Adapter.SendCommand(Ff07Char, CommandRequest);
					break;
				case Constants.SyncHandlerSequence.ReadSeizure:
					Debug.WriteLine("SyncDeviceHandler936: Read seizure Data");
					break;
				case Constants.SyncHandlerSequence.WriteStepsHeader:
					Debug.WriteLine("SyncDeviceHandler936: Writing steps header");
					break;
				case Constants.SyncHandlerSequence.WriteDeviceSettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing device settings");
					break;
				case Constants.SyncHandlerSequence.WriteUserSettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing user settings");
					break;
				case Constants.SyncHandlerSequence.WriteExerciseSettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing exercise settings");
					break;
				case Constants.SyncHandlerSequence.WriteCompanySettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing company settings");
					break;
				case Constants.SyncHandlerSequence.WriteSignatureSettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing signature settings");
					break;
				case Constants.SyncHandlerSequence.WriteSeizureSettings:
					Debug.WriteLine("SyncDeviceHandler936: Writing seizure settings");
					break;
				case Constants.SyncHandlerSequence.WriteScreenFlow:
					Debug.WriteLine("SyncDeviceHandler936: Writing screenflow settings");
					break;
				case Constants.SyncHandlerSequence.WriteDeviceSensitivity:
					Debug.WriteLine("SyncDeviceHandler936: Writing device sensitivity settings");
					break;
				case Constants.SyncHandlerSequence.WriteDeviceStatus:
					Debug.WriteLine("SyncDeviceHandler936: Writing device status settings");
					break;
				case Constants.SyncHandlerSequence.WriteScreenDisplay:
					Debug.WriteLine("SyncDeviceHandler936: Writing screen display");
					break;
				case Constants.SyncHandlerSequence.ClearEEProm:
					Debug.WriteLine("SyncDeviceHandler936: Clear eeprom");
					break;
				case Constants.SyncHandlerSequence.WsGetDeviceInfo:
					Debug.WriteLine("SyncDeviceHandler936: WS Request GetDeviceInfo");
					/*Dictionary<String, object> parameter = new Dictionary<String, object>();
					parameter.Add("serno", "9999999894");
					parameter.Add("fwver", "4.3");
					parameter.Add("mdl", "961");
					parameter.Add("aid", 16781);
					parameter.Add("ddtm", "16-08-12 14:15");
					await WebService.PostData("https://test.savvysherpa.com/DeviceServices/api/Pedometer/GetDeviceInfo", parameter);
					*/
					break;
				default:
					Debug.WriteLine("SyncDeviceHandler936: Unable to identify command.");
					break;
			}

			if (this.ProcessQeueue.Count == 0)
			{
				Debug.WriteLine("Queue is already empty. Device will be disconnected.");
				this.Adapter.DisconnectDevice(this.Device);
				this.SyncDone(this, new SyncDoneEventArgs { Status = true });
			}
		}
Пример #56
0
		public void SendCommand (ICharacteristic handle, byte[] command)
		{
			handle.ValueUpdated += Handle_ValueUpdated;

			if (handle.CanWrite)
				handle.Write (command);
		}
Пример #57
0
		private IService GetService(ICharacteristic chr)
		{
			IService svc = null;
			foreach (var service in this.Device.Services)
			{
				bool found = false;
				foreach (var chars in service.Characteristics)
				{
					if (chars.ID == chr.ID)
					{
						found = true;
						break;
					}
				}
				if (found)
				{
					svc = service;
					break;
				}
			}

			return svc;
		}
Пример #58
0
		void Device_ServicesDiscovered (object sender, EventArgs e)
		{
			Debug.WriteLine("device.ServicesDiscovered");
			//this.services = (List<IService>)device.Services;

			if (this.services.Count == 0) 
			{
				Debug.WriteLine ("Service Count: " + device.Services.Count);
				foreach (var service in device.Services) 
				{
					service.CharacteristicsDiscovered += (object s, EventArgs ce) => {

						Debug.WriteLine("service.CharacteristicsDiscovered");
						if (this.characteristics.Count == 0)
						{
							Debug.WriteLine("Characteristics count: "+service.Characteristics.Count);
							foreach (var characteristic in service.Characteristics) 
							{
								if(characteristic !=null)
								{
									if(characteristic.Uuid.ToUpper().Contains("2A24") || 
										characteristic.Uuid.ToUpper().Contains("2A25") ||
										characteristic.Uuid.ToUpper().Contains("2A26") ||
										characteristic.Uuid.ToUpper().Contains("2A19") )
									{
										if(characteristic.CanRead)
										{
											characteristic.ValueUpdated += (cs, chre) => {
												Debug.WriteLine("characteristic.ValueUpdated");
											};
											characteristic.ReadAsync();
										}
									}
									else if(characteristic.Uuid.ToUpper().Contains("FF07"))
									{
										Debug.WriteLine("FF07");
										if(characteristic.CanUpdate)
										{
											this.ff07Char = characteristic;

											characteristic.StartUpdates();
										}
									}
									else if(characteristic.Uuid.ToUpper().Contains("FF08"))
									{
										Debug.WriteLine("FF08");
										if(characteristic.CanUpdate)
										{
											this.ff08Char = characteristic;

											characteristic.StartUpdates();
										}
									}
								}
							}
						}
					};

					service.DiscoverCharacteristics ();
				}
			}
		}
 public CharacteristicUpdatedEventArgs(ICharacteristic characteristic)
 {
     Characteristic = characteristic;
 }
		public CharacteristicDetail_TISwitch (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;
		}