Beispiel #1
0
 public void ConnectToTool(Tool t)
 {
     Console.WriteLine("Connecting to tool: " + t.MPBID);
     Byte[] cmd = bglib.BLECommandGAPConnectDirect(t.BluetoothAddress, t.AddressType, 0x20, 0x30, 0x100, 0);
     bglib.SendCommand(serialAPI, cmd);
     t.BLEState = BluetoothState.STATE_CONNECTING;
 }
Beispiel #2
0
        public override bool Connect(string deviceName)
        {
            if (!port.IsOpen)
            {
                if (!ConnectToBluegiga())
                {
                    return(false);
                }
            }

            bool           commandStarted   = false;
            bool           connectionEst    = false;
            byte           connectionHandle = 0;
            AutoResetEvent resp             = new AutoResetEvent(false);

            ConnectDirectEventHandler connectResp = delegate(object sender, ConnectDirectEventArgs e)
            {
                if (e.result == 0)
                {
                    commandStarted   = true;
                    connectionHandle = e.connection_handle;
                    resp.Set();
                }
            };

            StatusEventHandler connectionStatus = delegate(object sender, StatusEventArgs e)
            {
                connectionEst = true;
                resp.Set();
            };

            bluetooth.BLEResponseGAPConnectDirect += connectResp;
            bluetooth.BLEEventConnectionStatus    += connectionStatus;

            foreach (BluetoothDevice device in discoveredDevices)
            {
                if (device.Name.Equals(deviceName))
                {
                    this.device = device;
                    bluetooth.SendCommand(this.port, bluetooth.BLECommandGAPConnectDirect(device.BluetoothAddress, 0, 20, 40, 100, 1));
                    resp.WaitOne(200);
                    if (commandStarted)
                    {
                        this.device.ConnectionHandle = connectionHandle;
                        resp.WaitOne(1000);
                    }
                    break;
                }
            }

            bluetooth.BLEResponseGAPConnectDirect -= connectResp;
            bluetooth.BLEEventConnectionStatus    -= connectionStatus;

            if (connectionEst)
            {
                isConnected = true;
            }

            return(connectionEst);
        }
        private void btnBLE_Conn_1_Click(object sender, EventArgs e)
        {
            //BLE_Base.Connect_to_BLE_Device(BLE_Base.SelectedAddr, bglib, serialAPI, ':');

            string[] AddrSplited = BLE_Base.SelectedAddr.Split(':');
            byte[]   addr        = new byte[6];
            int      add         = 0;
            int      value       = 0;
            string   hex         = null;

            for (int i = 0; i < AddrSplited.Length - 1; i++)
            {
                value = Convert.ToInt32(AddrSplited[i], 16);
                byte charValue = (byte)value;
                addr[add++] = charValue;
            }

            int conn_intv_min = Convert.ToInt32(txtConnIntvMin.Text);
            int conn_intv_max = Convert.ToInt32(txtConnIntvMax.Text);
            int conn_timeout  = Convert.ToInt32(txtConnTimeout.Text);
            int conn_legacy   = Convert.ToInt32(txtLegacy.Text);


            bglib.SendCommand(serialAPI, bglib.BLECommandGAPConnectDirect(addr, 0x00, (ushort)conn_intv_min, (ushort)conn_intv_max, (ushort)conn_timeout, (ushort)conn_legacy));
        }
Beispiel #4
0
        private void listScanDev_DoubleClick(object sender, EventArgs e)
        {
            if (comDev.IsOpen == false)
            {
                MessageBox.Show("请先打开串口", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (listScanDev.SelectedIndices != null && listScanDev.SelectedItems.Count > 0)
            {
                c_BleDev.Reset();
                c_BleDev.MacAddr = listScanDev.SelectedItems[0].SubItems[2].Text;
                if (listScanDev.SelectedItems[0].SubItems[3].Text == "Random")
                {
                    c_BleDev.AddrType = 1;
                }
                else
                {
                    c_BleDev.AddrType = 0;
                }
                c_BleDev.DevName = listScanDev.SelectedItems[0].SubItems[0].Text;

                stsLb_ConnSts.Text = listScanDev.SelectedItems[0].SubItems[0].Text;
                stsLb_ConnMac.Text = "MacAddr=" + listScanDev.SelectedItems[0].SubItems[2].Text;

                Byte[] cmd = bglib.BLECommandGAPConnectDirect(DatConvert.strToHexByte(c_BleDev.MacAddr), c_BleDev.AddrType, 0x20, 0x30, 0x100, 0);
                bglib.SendCommand(comDev, cmd);// 125ms interval, 125ms window, active scanning
                tvSrvTree.Nodes.Clear();
            }
        }
Beispiel #5
0
        public void Connect()
        {
            // Connection parameters
            float conn_interval_min = 40;   // in ms
            float conn_interval_max = 60;   // in ms
            float timeout           = 2560; // in ms
            byte  latency           = 0;

            // Form a direct connection
            byte[] cmd = bglib.BLECommandGAPConnectDirect(
                Address,
                AddressType,
                (ushort)(conn_interval_min / 1.25F),
                (ushort)(conn_interval_max / 1.25F),
                (ushort)(timeout / 10F),
                latency); // 125ms interval, 125ms window, active scanning
            MessageWriter.LogWrite("ble_cmd_gap_connect_direct: ", string.Format("address={0}, address_type={1}, conn_interval_min={2}; conn_interval_max={3}, timeout={4}, latency={5}",
                                                                                 BitConverter.ToString(Address),
                                                                                 AddressType,
                                                                                 conn_interval_min,
                                                                                 conn_interval_max,
                                                                                 timeout,
                                                                                 latency));
            MessageWriter.BLEWrite(cmd);

            // Initialize connecting timeout timer
            DispatcherTimer connectionTimer = new DispatcherTimer();

            connectionTimer.Tick    += new EventHandler(CheckConnection);
            connectionTimer.Interval = new TimeSpan(0, 0, 3);
            connectionTimer.Start();

            // Track uptime
            _uptimeDispatcher.IsEnabled = true;
            if (_uptime.IsRunning == false)
            {
                _uptime.Start();
            }

            // New save file
            SaveFile = null;

            ConnectionState = ConnState.Connecting;
        }
Beispiel #6
0
        public void Connect_to_BLE_Device(string Addr, Bluegiga.BGLib bglib, SerialPort serialAPI, char symbol)
        {
            string[] AddrSplited = Addr.Split(symbol);
            byte[]   addr        = new byte[6];
            int      add         = 0;
            int      value       = 0;
            string   hex         = null;

            for (int i = 0; i < AddrSplited.Length - 1; i++)
            {
                value = Convert.ToInt32(AddrSplited[i], 16);
                byte charValue = (byte)value;
                addr[add++] = charValue;
            }


            //BLECommandGAPConnectDirect
            bglib.SendCommand(serialAPI, bglib.BLECommandGAPConnectDirect(addr, 0x00, 10, 250, 300, 0));
        }
Beispiel #7
0
        public UInt16 att_handle_measurement_ccc = 0;             // heart rate measurement client characteristic configuration handle (to enable notifications)

        //-------------------------------------------------------------------------------------------------------------
        // NOTE: The ATTClientProcedureCompletedEvent is automatically triggered at the end of each event handler.
        //       The ATTClientProcedureCompletedEvent examines the "STATE" along with other data and decides
        //       what command to issue next.  In general each command triggers a corresponding event that
        //       performs some work and then triggers the ATTClientProcedureCompletedEvent.
        //-------------------------------------------------------------------------------------------------------------

        //-------------------------------------------------------------------------------------------------------------
        // For master/scanner devices, the "gap_scan_response" event is a common "entry-like" point
        // that filters ad packets to find devices which advertise the Heart Rate service.
        // Other services can be found as well. See https://www.bluetooth.com/specifications/gatt/services
        // for a list of Service Assigned Numbers (hexadecimal values are used).
        public void GAPScanResponseEvent(object sender, Bluegiga.BLE.Events.GAP.ScanResponseEventArgs e)
        {
            String log = String.Format("ble_evt_gap_scan_response: rssi={0}, packet_type={1}, sender=[ {2}], address_type={3}, bond={4}, data=[ {5}]" + Environment.NewLine,
                                       (SByte)e.rssi,
                                       e.packet_type,
                                       ByteArrayToHexString(e.sender),
                                       e.address_type,
                                       e.bond,
                                       ByteArrayToHexString(e.data)
                                       );

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

            // Pull all advertised service info from ad packet
            List <Byte[]> ad_services = findAllAdvertisedServices(e.data);

            // Check for 0x180D (the official Heart Rate service UUID),
            // using an "extension" method.
            if (ad_services.Any(a => a.SequenceEqual(new Byte[] { 0x18, 0x0D })))
            {
                // A device with the Heart Rate service has been found, so
                // connect to that device, triggering the ConnectionStatus event.

                // See Ref. p. 101, for info. about the Connect Direct command.
                // Parameters are:
                // Byte[] address, Byte addr_type, UInt16 conn_interval_min, UInt16 conn_interval_max, UInt16 timeout, UInt16 latency
                Byte[] cmd = bglib.BLECommandGAPConnectDirect(e.sender, e.address_type, 0x20, 0x30, 0x100, 0);

                // DEBUG: display bytes written
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });

                // Send the command, which then triggers the ConnectionStatus event.
                bglib.SendCommand(serialAPI, cmd);

                // Update the state to "connecting"
                app_state = STATE_CONNECTING;
            }

            // No callback function was specified. A callback function may be used.
            // Only the ConnectionStatus event handler is used in this application.
        }
Beispiel #8
0
        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;
                    }
                }
            }
        }
Beispiel #9
0
        public void GAPScanResponseEvent(object sender, Bluegiga.BLE.Events.GAP.ScanResponseEventArgs e)
        {
#if PRINT_DEBUG
            String log = String.Format("ble_evt_gap_scan_response: rssi={0}, packet_type={1}, sender=[ {2}], address_type={3}, bond={4}, data=[ {5}]" + Environment.NewLine,
                                       (SByte)e.rssi,
                                       e.packet_type,
                                       ByteArrayToHexString(e.sender),
                                       e.address_type,
                                       e.bond,
                                       ByteArrayToHexString(e.data)
                                       );
            Console.Write(log);
            ThreadSafeDelegate(delegate { txtLog.AppendText(log); });
#endif
            // pull all advertised service info from ad packet
            List <Byte[]> ad_services  = new List <Byte[]>();
            Byte[]        this_field   = { };
            int           bytes_left   = 0;
            int           field_offset = 0;
            for (int i = 0; i < e.data.Length; i++)
            {
                if (bytes_left == 0)
                {
                    bytes_left   = e.data[i];
                    this_field   = new Byte[e.data[i]];
                    field_offset = i + 1;
                }
                else
                {
                    this_field[i - field_offset] = e.data[i];
                    bytes_left--;
                    if (bytes_left == 0)
                    {
                        if (this_field[0] == 0x02 || this_field[0] == 0x03)
                        {
                            // partial or complete list of 16-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(2).Reverse().ToArray());
                        }
                        else if (this_field[0] == 0x04 || this_field[0] == 0x05)
                        {
                            // partial or complete list of 32-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(4).Reverse().ToArray());
                        }
                        else if (this_field[0] == 0x06 || this_field[0] == 0x07)
                        {
                            // partial or complete list of 128-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(16).Reverse().ToArray());
                        }
                    }
                }
            }

            if (ad_services.Any(a => a.SequenceEqual((new Byte[] { 0x19, 0xb1, 0x00, 0x10, 0xE8, 0xF2,
                                                                   0x53, 0x7E, 0x4F, 0x6C, 0xD1, 0x04, 0x76, 0x8A, 0x01, 0x16 }) /*.Reverse()*/)))
            {
                // connect to this device
                Byte[] cmd = bglib.BLECommandGAPConnectDirect(e.sender, e.address_type, 0x06, 0x0C, 0x100, 0); // ~120/60 Hz min/max interval
#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_CONNECTING;
            }
        }
Beispiel #10
0
        public UInt16 att_handle_measurement_ccc = 0;             // heart rate measurement client characteristic configuration handle (to enable notifications)

        // for master/scanner devices, the "gap_scan_response" event is a common entry-like point
        // this filters ad packets to find devices which advertise the Heart Rate service
        public void GAPScanResponseEvent(object sender, Bluegiga.BLE.Events.GAP.ScanResponseEventArgs e)
        {
            String log = String.Format("ble_evt_gap_scan_response: rssi={0}, packet_type={1}, sender=[ {2}], address_type={3}, bond={4}, data=[ {5}]" + Environment.NewLine,
                                       (SByte)e.rssi,
                                       e.packet_type,
                                       ByteArrayToHexString(e.sender),
                                       e.address_type,
                                       e.bond,
                                       ByteArrayToHexString(e.data)
                                       );

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

            // pull all advertised service info from ad packet
            List <Byte[]> ad_services = new List <Byte[]>();

            Byte[] this_field   = {};
            int    bytes_left   = 0;
            int    field_offset = 0;

            for (int i = 0; i < e.data.Length; i++)
            {
                if (bytes_left == 0)
                {
                    bytes_left   = e.data[i];
                    this_field   = new Byte[e.data[i]];
                    field_offset = i + 1;
                }
                else
                {
                    this_field[i - field_offset] = e.data[i];
                    bytes_left--;
                    if (bytes_left == 0)
                    {
                        if (this_field[0] == 0x02 || this_field[0] == 0x03)
                        {
                            // partial or complete list of 16-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(2).Reverse().ToArray());
                        }
                        else if (this_field[0] == 0x04 || this_field[0] == 0x05)
                        {
                            // partial or complete list of 32-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(4).Reverse().ToArray());
                        }
                        else if (this_field[0] == 0x06 || this_field[0] == 0x07)
                        {
                            // partial or complete list of 128-bit UUIDs
                            ad_services.Add(this_field.Skip(1).Take(16).Reverse().ToArray());
                        }
                    }
                }
            }

            // check for 0x180D (official heart rate service UUID)
            if (ad_services.Any(a => a.SequenceEqual(new Byte[] { 0x18, 0x0D })))
            {
                // connect to this device
                Byte[] cmd = bglib.BLECommandGAPConnectDirect(e.sender, e.address_type, 0x20, 0x30, 0x100, 0); // 125ms interval, 125ms window, active scanning
                // DEBUG: display bytes written
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("=> TX ({0}) [ {1}]", cmd.Length, ByteArrayToHexString(cmd)) + Environment.NewLine); });
                bglib.SendCommand(serialAPI, cmd);
                //while (bglib.IsBusy()) ;

                // update state
                app_state = STATE_CONNECTING;
            }
        }
Beispiel #11
0
 protected Byte[] GetConnectCmd(Byte[] address, Byte addr_type, UInt16 conn_interval_min, UInt16 conn_interval_max, UInt16 timeout, UInt16 latency)
 {
     return(bglib.BLECommandGAPConnectDirect(address, addr_type, conn_interval_min, conn_interval_max, timeout, latency));
 }