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);
                }
            }
        }
        private void WritePzVoltData(BLEPeripheral peripheral)
        {
            if (peripheral.Characteristics.ContainsKey("PiezoVoltage"))
            {
                long timestamp = peripheral.UptimeMilliseconds;
                long period    = 333;

                Models.Attribute attr = peripheral.Characteristics["PiezoVoltage"].ValueAttribute;
                for (int i = 0; i < attr.Value.Length / 2; i++)
                {
                    long   time  = timestamp - (period / (attr.Value.Length / 2) * (((attr.Value.Length / 2) - 1) - i));
                    ushort value = BitConverter.ToUInt16(attr.Value, 2 * i);

                    try
                    {
                        using (StreamWriter output = new StreamWriter(peripheral.SaveFile.Substring(0, peripheral.SaveFile.Length - 4) + "volt.csv", true))
                        {
                            output.WriteLine(time + "," + value);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        //MessageWriter.LogWrite("Error writing file. Check save location.");
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BLEGAPScanResponseEvent(object sender, Bluegiga.BLE.Events.GAP.ScanResponseEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                MessageWriter.LogWrite("ble_evt_gap_scan_response: ", string.Format("rssi={0}, packet_type={1}, sender={2}, address_type={3}, bond={4}, data={5}",
                                                                                    e.rssi,
                                                                                    e.packet_type,
                                                                                    BitConverter.ToString(e.sender),
                                                                                    e.address_type,
                                                                                    e.bond,
                                                                                    BitConverter.ToString(e.data)));

                BLEPeripheral peripheral = FindDiscoveredPeripheral(e.sender);

                // If the responder is undiscovereed, add it to the collection
                if (peripheral == null)
                {
                    peripheral = new BLEPeripheral(e.sender);
                    discoveredPeripherals.Add(peripheral);
                }

                // Update RSSI
                peripheral.RSSI = e.rssi;
                peripheral.Bond = e.bond;

                // Parse packet
                byte[] remainingData = e.data;
                while (remainingData.Length > 0)
                {
                    ushort elementLength = remainingData[0];
                    byte adType          = remainingData[1];
                    byte[] element       = remainingData.Skip(2).Take(elementLength - 1).ToArray();

                    if (!peripheral.AdData.ContainsKey(adType))
                    {
                        peripheral.AdData.Add(adType, BitConverter.ToString(element));
                    }

                    // Flags
                    if (adType == Bluetooth.GenericAccessProfile.AD_Type.Get("Flags"))
                    {
                        peripheral.Flags = element.FirstOrDefault();
                    }

                    // Complete local name
                    if (adType == Bluetooth.GenericAccessProfile.AD_Type.Get("Shortened Local Name"))
                    {
                        peripheral.ShortenedLocalName = Encoding.ASCII.GetString(element);
                    }

                    // Complete local name
                    if (adType == Bluetooth.GenericAccessProfile.AD_Type.Get("Complete Local Name"))
                    {
                        peripheral.Name = Encoding.ASCII.GetString(element);
                    }

                    remainingData = remainingData.Skip(elementLength + 1).ToArray();
                }
            });
        }
Пример #4
0
    void Start()
    {
        BLEPeri = GetComponent <BLEPeripheral>();

        rb = GetComponent <Rigidbody>();
        Renderer renderer = GetComponent <Renderer>();

        mat = renderer.material;
        tr  = GetComponent <TrailRenderer>();
    }
    static void characteristicUpdatedCallback(IntPtr nativep, string uuid, IntPtr valuep)
    {
        NeppiValue value =
            (NeppiValue)Marshal.PtrToStructure(valuep, typeof(NeppiValue));

        GCHandle            gch    = GCHandle.FromIntPtr(nativep);
        BLENativePeripheral native = (BLENativePeripheral)gch.Target;
        BLEPeripheral       peri   = native.client;

        if (peri != null && peri.CharacteristicUpdated != null)
        {
            peri.CharacteristicUpdated(uuid, value);
        }
    }
Пример #6
0
 public SimpleStringService()
 {
     _ = Task.Factory.StartNew(async() =>
     {
         var blePeripheral = new BLEPeripheral(serviceUuid);
         if (await blePeripheral.Initialize())
         {
             this.chara = await blePeripheral.GetCharacteristicAsync(charaUuid);
             Debug.WriteLine("device available");
             this.IsAvailable = true;
             this.OnAvailable.Invoke(this, EventArgs.Empty);
         }
     });
 }
        private void WriteData(BLEPeripheral peripheral, double[] newData)
        {
            long timestamp = peripheral.UptimeMilliseconds;

            for (int k = 0; k < newData.Length; k++)
            {
                long period = 333;

                // Name
                string outputLine = peripheral.Name;

                // Uptime
                double measurementTime = timestamp - ((period / newData.Length) * (newData.Length - k + 1));
                outputLine += string.Format(",{0}", measurementTime);

                // Main data
                outputLine += "," + newData[k];

                // Battery level
                if (peripheral.Characteristics.ContainsKey("Battery"))
                {
                    outputLine += string.Format(",{0}", peripheral.Characteristics["Battery"].Value);
                }

                // Temperature
                if (peripheral.Characteristics.ContainsKey("Temperature"))
                {
                    outputLine += string.Format(",{0:0.0}", peripheral.Characteristics["Temperature"].Value);
                }

                try
                {
                    using (StreamWriter output = new StreamWriter(peripheral.SaveFile, true))
                    {
                        output.WriteLine(outputLine);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    //MessageWriter.LogWrite("Error writing file. Check save location.");
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BLEConnectionStatusEvent(object sender, Bluegiga.BLE.Events.Connection.StatusEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                MessageWriter.LogWrite("ble_evt_connection_status: ", string.Format("connection={0}, flags={1}, address=[ {2}], address_type={3}, conn_interval={4}, timeout={5}, latency={6}, bonding={7}",
                                                                                    e.connection,
                                                                                    e.flags,
                                                                                    BitConverter.ToString(e.address),
                                                                                    e.address_type,
                                                                                    e.conn_interval,
                                                                                    e.timeout,
                                                                                    e.latency,
                                                                                    e.bonding));

                // Identify peripheral
                BLEPeripheral peripheral = FindDiscoveredPeripheral(e.address);

                if (peripheral == null)
                {
                    return;
                }

                // Has a new connection been established?
                if ((e.flags & 0x05) == 0x05)
                {
                    // Add to collection
                    if (!connectedDevices.Contains(peripheral))
                    {
                        connectedDevices.Add(peripheral);
                    }

                    // The connection is established
                    peripheral.ConnectionState = BLEPeripheral.ConnState.Connected;
                    MessageWriter.LogWrite("Connected to " + peripheral.Name);

                    BLEPerformNextTask(peripheral);
                }
            });
        }
        private void WriteRawData(BLEPeripheral peripheral)
        {
            // Add uptime to output line
            string outputLine = peripheral.UptimeMilliseconds.ToString();

            foreach (Models.Attribute attr in peripheral.Attributes.Values)
            {
                outputLine += string.Format(",{0}", BitConverter.ToString(attr.Value));
            }

            // Write finished line to file
            try
            {
                using (StreamWriter output = new StreamWriter(peripheral.SaveFile, true))
                {
                    output.WriteLine(outputLine);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //MessageWriter.LogWrite("Error writing file. Check save location.");
            }
        }