コード例 #1
0
        public void ATTClientProcedureCompletedEvent(object sender, Bluegiga.BLE.Events.ATTClient.ProcedureCompletedEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_procedure_completed: connection={0}, result={1}, chrhandle={2}" + Environment.NewLine,
                                       e.connection,
                                       e.result,
                                       e.chrhandle
                                       );

            Console.Write(log);
            ThreadSafeDelegate(delegate { txtLog.AppendText(log); });

            // check if we just finished searching for services
            if (app_state == STATE_FINDING_SERVICES)
            {
                if (att_handlesearch_end > 0)
                {
                    //print "Found 'Health Thermometer' service with UUID 0x1809"

                    // found the Health Thermometer service, so now search for the attributes inside
                    Byte[] cmd = bglib.BLECommandATTClientFindInformation(e.connection, att_handlesearch_start, att_handlesearch_end);
                    // DEBUG: display bytes written
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
                    bglib.SendCommand(cmd);
                    //while (bglib.IsBusy()) ;

                    // update state
                    app_state = STATE_FINDING_ATTRIBUTES;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find 'Health Thermometer' service with UUID 0x1809" + Environment.NewLine); });
                }
            }
            // check if we just finished searching for attributes within the thermometer service
            else if (app_state == STATE_FINDING_ATTRIBUTES)
            {
                if (att_handle_measurement_ccc > 0)
                {
                    //print "Found 'Health Thermometer' measurement attribute with UUID 0x2A1C"

                    // found the measurement + client characteristic configuration, so enable indications
                    // (this is done by writing 0x0002 to the client characteristic configuration attribute)
                    Byte[] cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, att_handle_measurement_ccc, new Byte[] { 0x02, 0x00 });
                    // DEBUG: display bytes written
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
                    bglib.SendCommand(cmd);
                    //while (bglib.IsBusy()) ;

                    // update state
                    app_state = STATE_LISTENING_MEASUREMENTS;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find 'Health Thermometer' measurement attribute with UUID 0x2A1C" + Environment.NewLine); });
                }
            }
        }
コード例 #2
0
        public override void Send(byte[] data)
        {
            try
            {
                if (device?.ConnectionHandle != null && isConnected)
                {
                    AutoResetEvent proceed = new AutoResetEvent(false);
                    ProcedureCompletedEventHandler complete = delegate(object sender, ProcedureCompletedEventArgs e)
                    {
                        Debug.WriteLine("Bluetooth: write complete");
                        proceed.Set();
                    };

                    bluetooth.BLEEventATTClientProcedureCompleted += complete;

                    if (data.Length > 20)
                    {
                        List <byte> payload = new List <byte>(data);
                        int         total   = data.Length;
                        bool        signal;

                        for (int i = 0; i < Math.Ceiling((double)data.Length / 20); i++)
                        {
                            bluetooth.SendCommand(this.port,
                                                  bluetooth.BLECommandATTClientAttributeWrite((byte)device.ConnectionHandle, (ushort)Handle.Write,
                                                                                              payload.GetRange(i * 20, (total < 20) ? total : 20).ToArray())
                                                  );
                            total -= 20;
                            signal = proceed.WaitOne(200);
                            if (!signal)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        bluetooth.SendCommand(this.port, bluetooth.BLECommandATTClientAttributeWrite((byte)device.ConnectionHandle, (ushort)Handle.Write, data));
                        proceed.WaitOne(200);
                    }

                    bluetooth.BLEEventATTClientProcedureCompleted -= complete;
                }
                else
                {
                    throw new HardwareException("There is no reader connected");
                }
            }
            catch (InvalidOperationException e)
            {
                throw new HardwareException("There is no TappyUSB connected");
            }
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: numpad0/lighthouse
        public void ATTClientProcedureCompletedEvent(object sender, Bluegiga.BLE.Events.ATTClient.ProcedureCompletedEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_procedure_completed: connection={0}, result={1}, chrhandle={2}" + Environment.NewLine,
                                       e.connection,
                                       e.result,
                                       e.chrhandle
                                       );

            Console.Write(log);
            ThreadSafeDelegate(delegate { txtLog.AppendText(log); });

            if (app_state == STATE_FINDING_SERVICES)
            {
                if (att_handlesearch_end > 0)
                {
                    Byte[] cmd = bglib.BLECommandATTClientFindInformation(e.connection, att_handlesearch_start, att_handlesearch_end);
#if PRINT_DEBUG
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
#endif
                    bglib.SendCommand(serialAPI, cmd);

                    // update state
                    app_state = STATE_FINDING_ATTRIBUTES;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find service" + Environment.NewLine); });
                }
            }
            else if (app_state == STATE_FINDING_ATTRIBUTES)
            {
                if (att_handle_measurement_ccc > 0)
                {
                    Byte[] cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, (UInt16)(att_handle_measurement + 0x01), new Byte[] { 0x01, 0x00 });
#if PRINT_DEBUG
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
#endif
                    bglib.SendCommand(serialAPI, cmd);
                    Byte[] cmd2 = bglib.BLECommandATTClientAttributeWrite(e.connection, (UInt16)(att_handle_measurement_ccc + 0x01), new Byte[] { 0x01, 0x00 });
#if PRINT_DEBUG
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
#endif
                    bglib.SendCommand(serialAPI, cmd2);
                    app_state = STATE_LISTENING_MEASUREMENTS;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find 'Heart Rate' measurement attribute with UUID 0x2A37" + Environment.NewLine); });
                }
            }
        }
コード例 #4
0
 private void SaveValue(object obj)
 {
     // Save value
     if (SelectedPeripheral.Characteristics.ContainsKey("RheostatSaveCommand"))
     {
         byte   connection = SelectedPeripheral.Connection;
         ushort handle     = SelectedPeripheral.Services["RheostatCalibrationService"].Characteristics["RheostatSaveCommand"].ValueAttribute.Handle;
         byte[] value      = new byte[] { 0x01 };
         byte[] cmd        = bglib.BLECommandATTClientAttributeWrite(connection, handle, value);
         MessageWriter.LogWrite("ble_cmd_att_client_attribute_write: ", string.Format("handle={0}, att_handle={1}, data={2}",
                                                                                      connection,
                                                                                      handle,
                                                                                      BitConverter.ToString(value)));
         MessageWriter.BLEWrite(cmd);
     }
 }
コード例 #5
0
        private void BLEPerformNextTask(BLEPeripheral peripheral)
        {
            // Find all attributes
            if (peripheral.Attributes.Count() == 0)
            {
                ushort start = 0x0001;
                ushort end   = 0xFFFF;
                cmd = bglib.BLECommandATTClientFindInformation(peripheral.Connection, start, end);
                MessageWriter.LogWrite("ble_cmd_att_client_find_information: ", string.Format("connection={0}, start={1}, end={2}",
                                                                                              peripheral.Connection,
                                                                                              start,
                                                                                              end));
                bglib.SendCommand(SelectedPort, cmd);
            }

            // Have attributes been found?
            else if (peripheral.Services.Count() == 0)
            {
                // Perform service discovery
                ushort start          = 0x0001;
                ushort end            = 0xFFFF;
                byte[] primaryService = new byte[] { 0x00, 0x28 };
                cmd = bglib.BLECommandATTClientReadByGroupType(peripheral.Connection, start, end, primaryService);
                MessageWriter.LogWrite("ble_cmd_att_client_read_by_group_type: ", string.Format("connection={0}, start={1}, end={2}, uuid={3}",
                                                                                                peripheral.Connection,
                                                                                                start,
                                                                                                end,
                                                                                                BitConverter.ToString(primaryService)));
                bglib.SendCommand(SelectedPort, cmd);
            }

            else if (!peripheral.Services.ContainsKey("CustomService"))
            {
                MessageWriter.LogWrite("Invalid device selected");
                peripheral.Disconnect();
            }

            else if (peripheral.attHandleCCC.Count > 0)
            {
                // Enable indications
                byte[] indications = new byte[] { 0x03, 0x00 };
                byte[] cmd         = bglib.BLECommandATTClientAttributeWrite(peripheral.Connection, peripheral.attHandleCCC.Peek(), indications);
                MessageWriter.LogWrite("ble_cmd_att_client_attribute_write: ", string.Format("connection={0}, att_handle={1}, data={2}",
                                                                                             peripheral.Connection, peripheral.attHandleCCC.Dequeue(), BitConverter.ToString(indications)));
                bglib.SendCommand(SelectedPort, cmd);
            }

            // Is the low power mode state known?
            else if (peripheral.Characteristics.ContainsKey("LPM"))
            {
                if (peripheral.Characteristics["LPM"].ValueAttribute.Handle > 0 && peripheral.LowPowerMode == BLEPeripheral.LPM.Unknown) //TODO Low-Power mode key not found
                {
                    // Check sleep mode
                    cmd = bglib.BLECommandATTClientReadByHandle(peripheral.Connection, peripheral.Characteristics["LPM"].ValueAttribute.Handle);
                    MessageWriter.LogWrite("ble_cmd_att_client_read_by_handle: ", string.Format("connection={0}, handle={1}",
                                                                                                peripheral.Connection, peripheral.Characteristics["LPM"].ValueAttribute.Handle));
                    bglib.SendCommand(SelectedPort, cmd);
                }
            }
        }
コード例 #6
0
        public void ConnectionStatusEvent(object sender, Bluegiga.BLE.Events.Connection.StatusEventArgs e)
        {
            String log = String.Format("ble_evt_connection_status: connection={0}, flags={1}, address=[ {2}], address_type={3}, conn_interval={4}, timeout={5}, latency={6}, bonding={7}" + Environment.NewLine,
                                       e.connection,
                                       e.flags,
                                       ByteArrayToHexString(e.address),
                                       e.address_type,
                                       e.conn_interval,
                                       e.timeout,
                                       e.latency,
                                       e.bonding
                                       );

            Console.Write(log);


            if ((e.flags & 0x05) == 0x05)
            {
                // connected, now perform service discovery
                Tool t;

                if (!localTools.TryGetValue(ByteArrayToHexString(e.address), out t))
                {
                    Console.WriteLine("Tool not found on connection!");
                    return;
                }

                // connected, now perform service discovery
                connection_handle = e.connection;

                byte[] payload = new byte[] {
                    0x01,       //Message type -- LOCAL_MEM_ACCESS (write)
                    0x01,       //Sequence ID
                    0x03,       //Data length
                    0xA0, 0x23, //Local data address
                    0x01,       //Data to write
                    0x00,       //Checksum MSB
                    0xc9        //Checksum LSB
                };
                Byte[] cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, 0x000F, payload);

                bglib.SendCommand(serialAPI, cmd);
                Console.WriteLine("Connected now discovering services");
            }
        }
コード例 #7
0
        private void LPMEnter()
        {
            // Wake up
            byte[] lpm_bit = new byte[] { 0x00 };
            byte[] cmd     = bglib.BLECommandATTClientAttributeWrite(Connection, Characteristics["LPM"].ValueAttribute.Handle, lpm_bit);
            MessageWriter.LogWrite("ble_cmd_att_client_attribute_write: ", string.Format("connection={0}, handle={1}, data={2}",
                                                                                         Connection, Characteristics["LPM"].ValueAttribute.Handle, BitConverter.ToString(lpm_bit)));
            MessageWriter.BLEWrite(cmd);

            /* Stop tracking uptime
             * _uptimeDispatcher.IsEnabled = false;
             * if (_uptime.IsRunning == true)
             * {
             *  _uptime.Reset();
             *  NotifyPropertyChanged("Uptime");
             * }
             *
             * // New save file
             * SaveFile = null;*/
        }
コード例 #8
0
 private void TryWriteValue(object obj)
 {
     try {
         byte[] data = { BitConverter.GetBytes(EditableValue)[0] };
         byte[] cmd  = bglib.BLECommandATTClientAttributeWrite(_parentPeripheral.Connection, _handle, data);
         MessageWriter.LogWrite("ble_cmd_att_client_attribute_write: ", string.Format("connection={0}, handle={1}, data={2}",
                                                                                      _parentPeripheral.Connection, Handle, BitConverter.ToString(data)));
         MessageWriter.BLEWrite(cmd);
     }
     catch (Exception ex)
     {
         MessageWriter.LogWrite("Error writing value!");
     }
 }
コード例 #9
0
ファイル: MainPage.xaml.cs プロジェクト: Lyque/diplomaterv
        private async void readBLEPeriodically()
        {
            bool rsp;

            while (true)
            {
                await Task.Delay(1000);

                if (this.bleSerial != null && this.SerialInitialized)
                {
                    try
                    {
                        do
                        {
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandSystemReset(0));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        } while (!rsp);

                        if (rsp)
                        {
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandSystemHello());

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        if (rsp)
                        {
                            byte[] bleAddress = new byte[] { SENSORTAG_ADDRESS_0, SENSORTAG_ADDRESS_1, SENSORTAG_ADDRESS_2, SENSORTAG_ADDRESS_3, SENSORTAG_ADDRESS_4, SENSORTAG_ADDRESS_5 };
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandGAPConnectDirect(bleAddress, 0, BLECONNINTERVALMIN, BLECINNINTERVANMAX, BLECONNTIMEOUT, BLECONNSLAVELATENCY));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        // Config temperature sensor period
                        if (rsp)
                        {
                            byte[] temperaturePeriod = new byte[] { 100 };
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientAttributeWrite(this.bleConnectionHndl, BLETEMPPERIODHNDL, temperaturePeriod));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        // Config light sensor period
                        if (rsp)
                        {
                            byte[] lightPeriod = new byte[] { 100 };
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientAttributeWrite(this.bleConnectionHndl, BLELIGHTPERIODHNDL, lightPeriod));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        // Start temperature measurement
                        if (rsp)
                        {
                            byte[] temperatureConfig = new byte[] { 0x01 };
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientAttributeWrite(this.bleConnectionHndl, BLETEMPCONFIGHNDL, temperatureConfig));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        // Start light measurement
                        if (rsp)
                        {
                            byte[] lightConfig = new byte[] { 0x01 };
                            await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientAttributeWrite(this.bleConnectionHndl, BLELIGHTCONFIGHNDL, lightConfig));

                            rsp = await this.bleSemaphore.WaitAsync(2000);
                        }
                        else
                        {
                            this.ErrorMessage.Text = "Semaphore timeout";
                        }

                        while (rsp)
                        {
                            await Task.Delay(1000);

                            // Read temperature data
                            if (rsp)
                            {
                                await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientReadByHandle(this.bleConnectionHndl, BLETEMPDATAHNDL));

                                rsp = await this.bleSemaphore.WaitAsync(2000);
                            }
                            else
                            {
                                this.ErrorMessage.Text = "Semaphore timeout";
                            }

                            // Read light data
                            if (rsp)
                            {
                                await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandATTClientReadByHandle(this.bleConnectionHndl, BLELIGHTDATAHNDL));

                                rsp = await this.bleSemaphore.WaitAsync(2000);
                            }
                            else
                            {
                                this.ErrorMessage.Text = "Semaphore timeout";
                            }
                        }

                        await bglib.SendCommandAsync(this.bleSerial, bglib.BLECommandConnectionDisconnect(this.bleConnectionHndl));
                    }
                    catch (Exception ex)
                    {
                        this.ErrorValue.Text   = "BGLib error!";
                        this.ErrorMessage.Text = ex.Message;
                    }
                }
            }
        }
コード例 #10
0
ファイル: Form1.cs プロジェクト: christian-schaub/BLE-csharp
        /// <summary>
        ///  The last started procedure has completed. E.g. we ended searching attr. or serv.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">ProcedureCompletedEventArgs</param>
        public void ATTClientProcedureCompletedEvent(object sender, Bluegiga.BLE.Events.ATTClient.ProcedureCompletedEventArgs e)
        {
            lock (o)
            {
                String log = String.Format("procedure_completed: connection={0}, result={1}, chrhandle={2}" + Environment.NewLine,
                                           e.connection,
                                           e.result,
                                           e.chrhandle
                                           );
                Console.Write(log);
                ThreadSafeDelegate(delegate { txtLog.AppendText(log); });
                Byte[] cmd;
                // check if we just finished searching for attr in services
                switch (app_state)
                {
                case  STATE_SEARCH_PLATTFORM_SERVICE:
                    // set to value when new service found
                    if (att_handlesearch_end > 0)
                    {
                        // found a service, so now search for the attributes inside
                        cmd = bglib.BLECommandATTClientFindInformation(e.connection, (UInt16)att_handlesearch_start, (UInt16)att_handlesearch_end);
                        //  Byte[] cmd = bglib.BLECommandATTClientReadByType(e.connection, (ushort)att_handlesearch_start, (ushort)att_handlesearch_end, new byte[] { 0x03, 0x28 });

                        ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Sending find information command \n =>   Length: ({0}) Data:   [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
                        bglib.SendCommand(serialAPI, cmd);
                        //while (bglib.IsBusy()) ;

                        // update state
                        app_state = STATE_SEARCH_ATTRIBUTES;
                        att_handlesearch_start = 0;
                        att_handlesearch_end   = 0;
                    }
                    else
                    {
                        ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find services" + Environment.NewLine); });
                    }
                    break;

                // characteristics search completed -- send notification command to first char
                case STATE_SEARCH_ATTRIBUTES:     // lasts ATTRccc val set in model - send notifications

                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Set STATE to SET_CCC \n ==> SET CCC Command Handle {0} ", tmpCharContainer1.Handle_ccc) + Environment.NewLine); });

                    app_state = STATE_SET_ATTRIBUTES_CCC;

                    cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, (UInt16)tmpCharContainer1.Handle_ccc, new Byte[] { 0x01 });

                    bglib.SendCommand(serialAPI, cmd);
                    break;

                case STATE_SET_ATTRIBUTES_CCC:

                    cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, (UInt16)tmpCharContainer2.Handle_ccc, new Byte[] { 0x01 });
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("STATE_SETATTR -- send last notify !!!!! to {0}", tmpCharContainer2.Handle_ccc) + Environment.NewLine); });

                    // we done notify for all characs
                    app_state = STATE_LISTEN_MEASUREMENTS;

                    readButton.Enabled = true;
                    bglib.SendCommand(serialAPI, cmd);

                    /*   // set the state to measure when all sensors connected
                     * if (att_Counter == SENSOR_COUNT)
                     * {
                     *     app_state = STATE_LISTENING_MEASUREMENTS;
                     * } */
                    break;

                case STATE_READ_ATTR_VAL:

                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Setting appstate back to READ Measure" + Environment.NewLine)); });

                    break;

                default: ThreadSafeDelegate(delegate { txtLog.AppendText("!!! STATE NOT FOUND" + Environment.NewLine); });
                    break;
                }
            }
        }
コード例 #11
0
ファイル: SippThing.cs プロジェクト: owan16/SippPC
 protected Byte[] NewWriteAttributeCmd(Byte connection, UInt16 attribute, Byte[] value)
 {
     return(bglib.BLECommandATTClientAttributeWrite(connection, attribute, value));
 }
コード例 #12
0
        //-------------------------------------------------------------------------------------------------------------
        // Event handler for the ATTClientProcedureCompleted event.
        // This function responds to the current asata and any input data.
        public void ATTClientProcedureCompletedEvent(object sender, Bluegiga.BLE.Events.ATTClient.ProcedureCompletedEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_procedure_completed: connection={0}, result={1}, chrhandle={2}" + Environment.NewLine,
                                       e.connection,
                                       e.result,
                                       e.chrhandle
                                       );

            Console.Write(log);
            ThreadSafeDelegate(delegate { txtLog.AppendText(log); });

            // Check if we just finished searching for services.
            if (app_state == STATE_FINDING_SERVICES)
            {
                // Did we find the service we were looking for?
                if (att_handlesearch_end > 0)
                {
                    //print "Found 'Heart Rate' service with UUID 0x180D"

                    // Yes, we found the Heart Rate service, so now search for the attributes of that service,
                    // triggering the ATTClientFindInformationFound event.

                    // Create the command.
                    Byte[] cmd = bglib.BLECommandATTClientFindInformation(e.connection, att_handlesearch_start, att_handlesearch_end);
                    // DEBUG: display bytes written
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });

                    // Send the command
                    bglib.SendCommand(serialAPI, cmd);

                    // Update the current state.
                    app_state = STATE_FINDING_ATTRIBUTES;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find 'Heart Rate' service with UUID 0x180D" + Environment.NewLine); });
                }
            }
            // check if we just finished searching for attributes within the Heart Rate service
            else if (app_state == STATE_FINDING_ATTRIBUTES)
            {
                if (att_handle_measurement_ccc > 0)
                {
                    //print "Found 'Heart Rate' measurement attribute with UUID 0x2A37"

                    // Yes, we found the measurement + client characteristic configuration values,
                    // so enable notifications. This is done by writing 0x0001 to the client characteristic configuration attribute.
                    // Notifications trigger the  ATTClientAttributeValueEvent.

                    // Create the command.
                    Byte[] cmd = bglib.BLECommandATTClientAttributeWrite(e.connection, att_handle_measurement_ccc, new Byte[] { 0x01, 0x00 });
                    // DEBUG: display bytes written
                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });

                    // Send the command.
                    bglib.SendCommand(serialAPI, cmd);

                    // Update the current application state.
                    app_state = STATE_LISTENING_MEASUREMENTS;
                }
                else
                {
                    ThreadSafeDelegate(delegate { txtLog.AppendText("Could not find 'Heart Rate' measurement attribute with UUID 0x2A37" + Environment.NewLine); });
                }
            }
        }
コード例 #13
0
        private void btAttrWrite_Click(object sender, EventArgs e)
        {
            if (comDev.IsOpen == false)
            {
                MessageBox.Show("请先打开串口", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (c_BleDev.ConnHandle == CAttribute.InvalidHandle)
            {
                return;
            }
            if (tvSrvTree.SelectedNode.Level != 1)
            {
                return;
            }

            string uuidstr = (string)tvSrvTree.SelectedNode.Tag;
            ushort attrID  = c_BleDev.AttrHandleByUUID(uuidstr);

            if (attrID == CAttribute.InvalidHandle)
            {
                return;
            }


            List <byte> byteList = new List <byte>();

            switch (cmbSetType.SelectedIndex)
            {
            case 0://hex
            {
                byte[] v = DatConvert.strToHexByte(tbAttrSet.Text);
                byteList.AddRange(v);
            }
            break;

            case 1://Number
                switch (cmbSetFormat.SelectedIndex)
                {
                case 0: //I8
                case 1: //U8
                    byteList.Add(byte.Parse(tbAttrSet.Text));
                    break;

                case 2://I16
                {
                    Int16  val = Int16.Parse(tbAttrSet.Text);
                    byte[] b   = BitConverter.GetBytes(val);
                    byteList.AddRange(b);
                }
                break;

                case 3://U16
                {
                    UInt16 val = UInt16.Parse(tbAttrSet.Text);
                    byte[] b   = BitConverter.GetBytes(val);
                    byteList.AddRange(b);
                }
                break;

                case 4://I32
                {
                    Int32  val = Int32.Parse(tbAttrSet.Text);
                    byte[] b   = BitConverter.GetBytes(val);
                    byteList.AddRange(b);
                }
                break;

                case 5://U32
                {
                    UInt32 val = UInt32.Parse(tbAttrSet.Text);
                    byte[] b   = BitConverter.GetBytes(val);
                    byteList.AddRange(b);
                }
                break;

                case 6://F32
                {
                    float  val = float.Parse(tbAttrSet.Text);
                    byte[] b   = BitConverter.GetBytes(val);
                    byteList.AddRange(b);
                }
                break;

                default:
                    break;
                }
                break;

            case 2://String
            {
                byte[] v = System.Text.Encoding.Default.GetBytes(tbAttrSet.Text);
                byteList.AddRange(v);
            }
            break;
            }
            Byte[] cmd = bglib.BLECommandATTClientAttributeWrite(c_BleDev.ConnHandle, attrID, byteList.ToArray());
            bglib.SendCommand(comDev, cmd);
        }