private void SetConnectState(bool isConnected)
 {
     this.Dispatcher.Invoke(() => {
         this.writeControl.Connected = isConnected;
         if (isConnected)
         {
             this.connectedOff.Collapse();
             this.connectedOn.Show();
             this.btnConnect.Collapse();
             this.btnDisconnect.Show();
             DI.Wrapper.BLE_ConnectionStatusChanged += this.connectionStatusChanged;
         }
         else
         {
             this.connectedOn.Collapse();
             this.connectedOff.Show();
             this.btnDisconnect.Collapse();
             this.btnConnect.Show();
             this.treeServices.ItemsSource = null;
             this.currentDevice            = null;
             this.currentCharacteristic    = null;
             this.writeControl.Reset();
             this.ucCmds.Reset();
             DI.Wrapper.BLE_ConnectionStatusChanged -= this.connectionStatusChanged;
             DI.Wrapper.BLE_Disconnect();
             // Reset title
             //this.lblCmdDataTypeContent.Content = BLE_DataType.Reserved.ToStr();
         }
         this.ResizeOnNormal();
     });
 }
Example #2
0
        private async Task <string> ReadValue(GattCharacteristic ch, BLE_CharacteristicDataModel dataModel)
        {
            try {
                // TODO - check if flag is in data model
                if (dataModel.PropertiesFlags.HasFlag(CharacteristicProperties.Read))
                {
                    GattReadResult readResult = await ch.ReadValueAsync();

                    if (readResult.Status == GattCommunicationStatus.Success)
                    {
                        byte[] data = readResult.Value.FromBufferToBytes();

                        // TODO The parser will know the data type so we could get that for the data model here.
                        //      also need to know it for the write only values

                        return(dataModel.Parser.Parse(data));
                    }
                    else
                    {
                        this.log.Error(9999, "ReadValue", () => string.Format("Failed read:{0}", readResult.Status));
                    }
                }
                else
                {
                    this.log.Info("ReadValue", "No READ property");
                }
            }
            catch (Exception e) {
                this.log.Exception(9999, "ReadValue", "", e);
            }
            return("");
        }
Example #3
0
 private void treeServices_Selected(object sender, RoutedEventArgs e)
 {
     if (sender is TreeView)
     {
         TreeView tv = sender as TreeView;
         if (tv.SelectedItem is BLE_CharacteristicDataModel)
         {
             BLE_CharacteristicDataModel ch = tv.SelectedItem as BLE_CharacteristicDataModel;
             if (this.borderInput.BorderThickness.Top > 0)
             {
                 // TODO - save the input selection
                 this.labelInputToDevice.Content = ch.CharName;
             }
             else
             {
                 // TODO - save the output selection
                 this.labelOutputFromDevice.Content = ch.CharName;
             }
         }
         else
         {
             if (e.OriginalSource is TreeViewItem)
             {
                 TreeViewItem tvi = e.OriginalSource as TreeViewItem;
                 tvi.IsSelected = false;
             }
             e.Handled = true;
         }
     }
 }
 private void TranslateIfBool(BLE_CharacteristicDataModel dm)
 {
     if (dm.Parser.DataType == BLE_DataType.Bool)
     {
         dm.CharValue = dm.Parser.BoolValue
             ? this.GetText(MsgCode.True)
             : this.GetText(MsgCode.False);
     }
 }
 public void Reset()
 {
     Unsubscribe();
     this.characteristic                = null;
     this.lbCmdList.ItemsSource         = null;
     this.lb_BLECmds.ItemsSource        = null;
     this.lblCmdDataTypeContent.Content = "";
     this.Subscribe();
 }
 public BLE_CharacteristicReadResult(
     BLE_CharacteristicDataModel dataModel,
     BLE_CharacteristicCommunicationStatus status,
     byte[] data,
     string dataAsString)
 {
     DataModel    = dataModel;
     Status       = status;
     Data         = data;
     DataAsString = dataAsString;
 }
Example #7
0
 /// <summary>Constructor</summary>
 /// <param name="osCharacteristic">The UWP Characteristic</param>
 /// <param name="dataModel">The cross platform data model</param>
 /// <param name="subscribed">if true then subscribe to the UWP characteristic value changes</param>
 public BLE_CharacteristicBinder(GattCharacteristic osCharacteristic, BLE_CharacteristicDataModel dataModel, bool subscribed)
 {
     this.subscribed       = subscribed;
     this.OSCharacteristic = osCharacteristic;
     this.DataModel        = dataModel;
     this.log.InfoEntry("BLE_CharacteristicBinder");
     if (this.subscribed)
     {
         this.OSCharacteristic.ValueChanged += this.OSCharacteristicReadValueChangedHandler;
     }
     this.DataModel.WriteRequestEvent += this.onDataModelWriteRequestHandler;
     this.DataModel.ReadRequestEvent  += this.onDataModelReadRequestHandler;
 }
 public void SetCharacteristic(BLE_CharacteristicDataModel dm)
 {
     try {
         if (this.selected != dm)
         {
             this.Reset();
             this.selected = dm;
             this.lblServiceContent.Content = this.selected.Service.DisplayName;
             DI.Wrapper.BLE_GetRangeDisplay(
                 this.selected, this.DelegateSelectSuccess, App.ShowMsg);
             this.SetEnabled(this.selected.IsReadable, this.selected.IsWritable);
         }
     }
     catch (Exception e) {
         this.log.Exception(9999, "SetCharacteristic", "", e);
     }
 }
        private async Task BuildDescriptors(GattCharacteristic ch, BLE_CharacteristicDataModel dataModel)
        {
            try {
                // TODO - change to an awaitable with result
                this.log.InfoEntry("BuildDescriptors");
                dataModel.Descriptors = new List <BLE_DescriptorDataModel>();
                GattDescriptorsResult descriptors = await ch.GetDescriptorsAsync();

                if (descriptors.Status == GattCommunicationStatus.Success)
                {
                    if (descriptors.Descriptors.Count > 0)
                    {
                        foreach (GattDescriptor desc in descriptors.Descriptors)
                        {
                            GattReadResult r = await desc.ReadValueAsync();

                            if (r.Status == GattCommunicationStatus.Success)
                            {
                                // New characteristic data model to add to service
                                IDescParser             parser        = this.descParserfactory.GetParser(desc.Uuid, desc.AttributeHandle);
                                BLE_DescriptorDataModel descDataModel = new BLE_DescriptorDataModel()
                                {
                                    Uuid            = desc.Uuid,
                                    AttributeHandle = desc.AttributeHandle,
                                    ProtectionLevel = (BLE_ProtectionLevel)desc.ProtectionLevel,
                                    DisplayName     = parser.Parse(r.Value.FromBufferToBytes()),
                                    Parser          = parser,
                                };

                                dataModel.Descriptors.Add(descDataModel);
                                this.log.Info("ConnectToDevice", () => string.Format("        Descriptor:{0}  Uid:{1} Value:{2}",
                                                                                     BLE_DisplayHelpers.GetDescriptorName(desc), desc.Uuid.ToString(), descDataModel.DisplayName));
                            }
                            ;
                        }
                    }
                }
                else
                {
                    this.log.Error(9999, "BuildDescriptors", () => string.Format("Get Descriptors result:{0}", descriptors.Status.ToString()));
                }
            }
            catch (Exception e) {
                this.log.Exception(9999, " BuildDescriptors", "", e);
            }
        }
 public void Reset()
 {
     try {
         if (this.selected != null)
         {
             this.selected.OnReadValueChanged -= Selected_OnReadValueChanged;
         }
         this.selected = null;
         this.lblServiceContent.Content     = "";
         this.lblCharacteristicName.Content = "";
         this.lblInfoContent.Content        = "";
         this.txtCommmand.Text = "";
         this.SetEnabled(false, false);
     }
     catch (Exception e) {
         this.log.Exception(9999, "Reset", "", e);
     }
 }
        public void Init(BLE_CharacteristicDataModel dm, bool force = false)
        {
            try {
                // The BLE tree updates continuously so need to check if same
                if (!force)
                {
                    if (this.characteristic != null && this.characteristic.Uuid == dm.Uuid)
                    {
                        return;
                    }
                }

                this.Unsubscribe();
                this.lbCmdList.ItemsSource         = null;
                this.lb_BLECmds.ItemsSource        = null;
                this.lblCmdDataTypeContent.Content = "";
                this.characteristic = dm;
                if (this.characteristic.IsWritable)
                {
                    this.lblCmdDataTypeContent.Content = dm.DataTypeDisplay;
                    DI.Wrapper.GetFilteredBLECmdList(
                        this.characteristic.Parser.DataType,
                        this.characteristic.CharName,
                        (general, specific) => {
                        // Only using general for now. Not filtering on specific characteristic name
                        this.general = general;
                        this.lbCmdList.ItemsSource = this.general;
                    }, App.ShowMsg);
                }
                this.Subscribe();
                if (this.lbCmdList.Items != null && this.lbCmdList.Count() > 0)
                {
                    this.lbCmdList.SelectedIndex = 0;
                    // Then select first of commands
                    if (this.lb_BLECmds.Items != null && this.lb_BLECmds.Count() > 0)
                    {
                        this.lb_BLECmds.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex) {
                this.log.Exception(9999, "Init", "", ex);
            }
        }
        private async Task BuildCharacteristicDataModel(GattCharacteristic ch, BLE_ServiceDataModel service)
        {
            try {
                BLE_CharacteristicDataModel characteristic = new BLE_CharacteristicDataModel();
                characteristic.Uuid                = ch.Uuid;
                characteristic.UserDescription     = ch.UserDescription;
                characteristic.AttributeHandle     = ch.AttributeHandle;
                characteristic.Service             = service;
                characteristic.CharName            = BLE_DisplayHelpers.GetCharacteristicName(ch);
                characteristic.PropertiesFlags     = ch.CharacteristicProperties.ToUInt().ToEnum <CharacteristicProperties>();
                characteristic.ProtectionLevel     = (BLE_ProtectionLevel)ch.ProtectionLevel;
                characteristic.PresentationFormats = this.BuildPresentationFormats(ch);
                await this.BuildDescriptors(ch, characteristic);

                service.Characteristics.Add(characteristic.Uuid.ToString(), characteristic);
            }
            catch (Exception e) {
                this.log.Exception(9999, "Failed during build of characteristic", e);
            }
        }
        private void treeServices_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            try {
                //if (e.NewValue is BLE_CharacteristicDataModel) {
                //    this.currentCharacteristic = e.NewValue as BLE_CharacteristicDataModel;
                //}
                ////// Cannot reset if not Characteristic since that happens on update
                //else if (e.NewValue is BLE_ServiceDataModel || e.NewValue is BLE_DescriptorDataModel) {
                //    this.log.Info("------------------------------------------------------", e.NewValue.GetType().Name);
                //    this.currentCharacteristic = null;
                //}

                // Will be null unless it is a characteristic. Handled in Update
                this.currentCharacteristic = e.NewValue as BLE_CharacteristicDataModel;
                this.Update(false);
            }
            catch (Exception ex) {
                this.log.Exception(9999, "", "treeServices_SelectedItemChanged", ex);
            }
        }
Example #14
0
 public void BLE_GetRangeDisplay(BLE_CharacteristicDataModel dataModel, Action <string, string> onSuccess, OnErr onError)
 {
     try {
         if (dataModel != null)
         {
             DataTypeDisplay display = this.validator.GetRange(dataModel.Parser.DataType);
             onSuccess(
                 dataModel.CharName,
                 string.Format("{0}: {1},  {2}: {3},  {4}: {5}",
                               this.GetText(MsgCode.DataType), display.DataType,
                               this.GetText(MsgCode.Min), display.Min,
                               this.GetText(MsgCode.Max), display.Max));
         }
     }
     catch (Exception e) {
         this.log.Exception(9999, "", e);
         WrapErr.SafeAction(() => {
             onError.Invoke(this.GetText(MsgCode.UnhandledError));
         });
     }
 }
Example #15
0
        private async Task BuildCharacteristicDataModel(GattCharacteristic ch, BLE_ServiceDataModel service)
        {
            try {
                this.log.InfoEntry("BuildCharacteristicDataModel");
                BLE_CharacteristicDataModel characteristic = new BLE_CharacteristicDataModel();
                // Build descriptors first to allow them to be used to build unknown Characteristic values
                await this.BuildDescriptors(ch, characteristic);

                characteristic.Uuid            = ch.Uuid;
                characteristic.GattType        = BLE_DisplayHelpers.GetCharacteristicEnum(ch);
                characteristic.UserDescription = ch.UserDescription;
                characteristic.AttributeHandle = ch.AttributeHandle;
                characteristic.Service         = service;
                characteristic.CharName        = BLE_DisplayHelpers.GetCharacteristicName(ch);
                // Must put this before the properties for indicate or Notify to work
                // TODO - notify value is no longer showing properly. But notification itself working
                bool subscribe = await this.EnableNotifyIndicate(ch);

                characteristic.PropertiesFlags     = ch.CharacteristicProperties.ToUInt().ToEnum <CharacteristicProperties>();
                characteristic.ProtectionLevel     = (BLE_ProtectionLevel)ch.ProtectionLevel;
                characteristic.PresentationFormats = this.BuildPresentationFormats(ch);

                // Do this after all else is defined
                characteristic.Parser = this.charParserFactory.GetParser(ch.Uuid, ch.AttributeHandle);
                this.RaiseIfError(characteristic.SetDescriptorParsers());
                characteristic.CharValue = await this.ReadValue(ch, characteristic);

                // Associate the UWP and data model characteristic for 2 way events to set and get
                this.binderSet.Add(new BLE_CharacteristicBinder(ch, characteristic, subscribe));

                service.Characteristics.Add(characteristic);

                // This also sends and receives dummy data to Arduino
                //await this.DumpCharacteristic(ch);
            }
            catch (Exception e) {
                this.log.Exception(9999, "Failed during build of characteristic", e);
            }
        }
Example #16
0
 public void BLE_Send(string value, BLE_CharacteristicDataModel dataModel, Action onSuccess, OnErr onError)
 {
     try {
         if (dataModel != null)
         {
             RangeValidationResult result = dataModel.Write(value);
             if (result.Status == BLE_DataValidationStatus.Success)
             {
                 onSuccess.Invoke();
             }
             else
             {
                 onError.Invoke(this.Translate(result));
             }
         }
     }
     catch (Exception e) {
         this.log.Exception(9999, "BLE_Send", "", e);
         WrapErr.SafeAction(() => {
             onError.Invoke(this.GetText(MsgCode.UnhandledError));
         });
     }
 }
Example #17
0
        private async Task BuildDescriptors(GattCharacteristic ch, BLE_CharacteristicDataModel dataModel)
        {
            dataModel.Descriptors = new Dictionary <string, BLE_DescriptorDataModel>();
            GattDescriptorsResult descriptors = await ch.GetDescriptorsAsync();

            if (descriptors.Status == GattCommunicationStatus.Success)
            {
                if (descriptors.Descriptors.Count > 0)
                {
                    foreach (GattDescriptor desc in descriptors.Descriptors)
                    {
                        GattReadResult r = await desc.ReadValueAsync();

                        if (r.Status == GattCommunicationStatus.Success)
                        {
                            // New characteristic data model to add to service
                            BLE_DescriptorDataModel descDataModel = new BLE_DescriptorDataModel()
                            {
                                Uuid            = desc.Uuid,
                                AttributeHandle = desc.AttributeHandle,
                                ProtectionLevel = (BLE_ProtectionLevel)desc.ProtectionLevel,
                                DisplayName     = BLE_ParseHelpers.GetDescriptorValueAsString(desc.Uuid, r.Value.FromBufferToBytes())
                            };

                            dataModel.Descriptors.Add(descDataModel.Uuid.ToString(), descDataModel);
                            this.log.Info("ConnectToDevice", () => string.Format("        Descriptor:{0}  Uid:{1} Value:{2}",
                                                                                 BLE_DisplayHelpers.GetDescriptorName(desc), desc.Uuid.ToString(), descDataModel.DisplayName));
                        }
                        ;
                    }
                }
            }
            else
            {
                this.log.Error(9999, "BuildDescriptors", () => string.Format("Get Descriptors result:{0}", descriptors.Status.ToString()));
            }
        }
        public void Translate(BLE_CharacteristicDataModel dataModel)
        {
            dataModel.DisplayHeader    = this.GetText(MsgCode.Characteristic);
            dataModel.DisplayReadWrite = string.Empty;
            if (dataModel.IsReadable || dataModel.IsWritable)
            {
                StringBuilder sb = new StringBuilder();
                if (dataModel.IsReadable)
                {
                    sb.Append(this.GetText(MsgCode.Read));
                }
                if (dataModel.IsWritable)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(this.GetText(MsgCode.Write));
                }
                if (sb.Length > 0)
                {
                    dataModel.DisplayReadWrite = string.Format("({0})", sb.ToString());
                }
            }

            if (dataModel.Parser is CharParser_Appearance)
            {
                dataModel.CharValue = this.Translate(dataModel.Parser as CharParser_Appearance);
            }
            this.TranslateIfBool(dataModel);

            foreach (BLE_DescriptorDataModel d in dataModel.Descriptors)
            {
                this.Translate(d);
            }
        }