Пример #1
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

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

            // check for a new value from the connected peripheral's temperature measurement attribute
            if (e.connection == connection_handle && e.atthandle == att_handle_measurement)
            {
                Byte htm_flags    = e.value[0];
                int  htm_exponent = e.value[4];
                int  htm_mantissa = (e.value[3] << 16) | (e.value[2] << 8) | e.value[1];
                if (htm_exponent > 127)
                {
                    // # convert to signed 8-bit int
                    htm_exponent = htm_exponent - 256;
                }
                float htm_measurement = htm_mantissa * (float)Math.Pow(10, htm_exponent);
                char  temp_type       = 'C';
                if ((htm_flags & 0x01) == 0x01)
                {
                    // value sent is Fahrenheit, not Celsius
                    temp_type = 'F';
                }

                // display actual measurement
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Temperature: {0}\u00B0 {1}", htm_measurement, temp_type) + Environment.NewLine); });
            }
        }
Пример #2
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            // check for a new value from the connected peripheral's heart rate measurement attribute
            if (e.connection == GetConnectionHandle() && e.atthandle == att_handle_measurement)
            {
                aX = (e.value[1] * 256 + e.value[2]) * accelerometerFSR / Math.Pow(2, 16);
                aY = (e.value[3] * 256 + e.value[4]) * accelerometerFSR / Math.Pow(2, 16);
                aZ = (e.value[5] * 256 + e.value[6]) * accelerometerFSR / Math.Pow(2, 16);
                gX = (e.value[7] * 256 + e.value[8]) * gyroFSR / Math.Pow(2, 16);
                gY = (e.value[9] * 256 + e.value[10]) * gyroFSR / Math.Pow(2, 16);
                gZ = (e.value[11] * 256 + e.value[12]) * gyroFSR / Math.Pow(2, 16);
                AccelerationValue    = new Acceleration(aX, aY, aZ);
                AngularvelocityValue = new AngularVelocity(gX, gY, gZ);
                double x0 = aX * aX + aY * aY + aZ * aZ;

                if (x0 - x1 > 290)
                {
                    if (originalStep < 0)
                    {
                        originalStep = step;
                    }
                    currentStep = step - originalStep;

                    PedometerValue = new PedometerData(step, calorie, distance, duration, currentStep);
                    step           = step + 1;
                }
                x1 = x0;
            }
        }
Пример #3
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

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

            // check for a new value from the connected peripheral's
            if (e.connection == adrTIUser)
            {
                switch ((TI_Sensor_Data)e.atthandle)
                {
                case TI_Sensor_Data.Temperature:
                    double tempA  = st.getTempAmbient(e.value);
                    double tempIR = st.extractTargetTemperature(e.value, tempA);
                    ThreadSafeDelegate(delegate { labTempAmbient.Text = tempA.ToString("f2") + " °C"; });
                    ThreadSafeDelegate(delegate { labTempIR.Text = tempIR.ToString("f2") + " °C"; });
                    break;

                case TI_Sensor_Data.Humidity:
                    ThreadSafeDelegate(delegate { labHumidity.Text = st.convertHumidity(e.value).ToString("f2") + " rel. %"; });
                    break;

                case TI_Sensor_Data.Barometer:
                    ThreadSafeDelegate(delegate { labBarometer.Text = st.convertBarometer(e.value).ToString("f2") + " mbar"; });
                    break;

                case TI_Sensor_Data.Movement:
                    p3d_a = st.convertAccelerometer(e.value);
                    p3d_g = st.convertGyroscope(e.value);
                    p3d_m = st.convertMagnetometer(e.value);

                    ThreadSafeDelegate(delegate
                    {
                        dataGridView1.Rows[0].Cells[1].Value = p3d_a.x.ToString("f3");
                        dataGridView1.Rows[0].Cells[2].Value = p3d_a.y.ToString("f3");
                        dataGridView1.Rows[0].Cells[3].Value = p3d_a.z.ToString("f3");
                        dataGridView1.Rows[1].Cells[1].Value = p3d_g.x.ToString("f3");
                        dataGridView1.Rows[1].Cells[2].Value = p3d_g.y.ToString("f3");
                        dataGridView1.Rows[1].Cells[3].Value = p3d_g.z.ToString("f3");
                        dataGridView1.Rows[2].Cells[1].Value = p3d_m.x.ToString("f3");
                        dataGridView1.Rows[2].Cells[2].Value = p3d_m.y.ToString("f3");
                        dataGridView1.Rows[2].Cells[3].Value = p3d_m.z.ToString("f3");
                    });
                    break;

                case TI_Sensor_Data.Luxometer:
                    ThreadSafeDelegate(delegate { labLuxometer.Text = st.convertLuxometer(e.value).ToString("f2") + " lux"; });
                    break;

                default:
                    break;
                }
            }
        }
Пример #4
0
 public void EventReadAttributeValue(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
 {
     // check for a new value from the connected peripheral's heart rate measurement attribute
     if (e.connection == c_BleDev.ConnHandle)// && e.atthandle == gChrHandle)
     {
         c_BleDev.AttReadDone  = true;
         c_BleDev.AttReadValue = e.value;
         c_BleDev.AttReadType  = e.type;
     }
 }
Пример #5
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

            Console.Write(log);

            // check for a new value from the connected peripheral's heart rate measurement attribute
            if (e.connection == GetConnectionHandle() && e.atthandle == att_handle_rx)
            {
                if (e.value[0] == SIPP_02_CMD_11_REALTIME)
                {
                    step     = e.value[1] << 16 & 0xff0000 | e.value[2] << 8 & 0xff00 | e.value[3] & 0xff;
                    calorie  = e.value[7] << 16 & 0xff0000 | e.value[8] << 8 & 0xff00 | e.value[9] & 0xff;
                    distance = e.value[10] << 16 & 0xff0000 | e.value[11] << 8 & 0xff00 | e.value[12] & 0xff;
                    duration = e.value[13] << 8 & 0xff00 | e.value[14] & 0xff;
                    if (originalStep < 0)
                    {
                        originalStep = step;
                    }
                    currentStep    = step - originalStep;
                    PedometerValue = new PedometerData(step, calorie, distance, duration, currentStep);

                    // display actual measurement
                    Console.WriteLine(String.Format("Step: {0},  Calore: {1} K, Distance: {2} meter, Duration: {3} minute", step, calorie, distance, duration) + Environment.NewLine);
                }
                else if (e.value[0] == SIPP_02_CMD_09_READ_DATA)
                {
                    if (e.value[1] == 0x00)
                    {
                        step    = e.value[6] << 16 & 0xff0000 | e.value[7] << 8 & 0xff00 | e.value[8] & 0xff;
                        calorie = e.value[12] << 16 & 0xff0000 | e.value[13] << 8 & 0xff00 | e.value[14] & 0xff;

                        if (originalStep < 0)
                        {
                            originalStep = step;
                        }
                        currentStep = step - originalStep;
                    }
                    else if (e.value[1] == 0x01)
                    {
                        distance = e.value[6] << 16 & 0xff0000 | e.value[7] << 8 & 0xff00 | e.value[8] & 0xff;
                        duration = e.value[9] << 8 & 0xff00 | e.value[10] & 0xff;

                        PedometerValue = new PedometerData(step, calorie, distance, duration, currentStep);
                        // display actual measurement
                        Console.WriteLine(String.Format("Step: {0},  Calore: {1} K, Distance: {2} meter, Duration: {3} minute", step, calorie, distance, duration) + Environment.NewLine);
                    }
                }
            }
        }
Пример #6
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            // Adatolvasás sikeresen megtörtént
            if (e.connection == this.bleConnectionHndl)
            {
                if (e.atthandle == BLETEMPDATAHNDL)
                {
                    if (e.value.Length == 4)
                    {
                        short ambTemp = (short)(e.value[1] << 8 | e.value[0]);
                        short remTemp = (short)(e.value[3] << 8 | e.value[2]);

                        float ambTemp_f = (float)(ambTemp >> 2);
                        float remTemp_f = (float)(remTemp >> 2);

                        float ambTempVal = ambTemp_f / 32;
                        float remTempVal = remTemp_f / 32;

                        this.AmbientTempValue.Text = ((int)(ambTempVal)).ToString() + "°C";
                        this.RemoteTempValue.Text  = ((int)(remTempVal)).ToString() + "°C";

                        this.stringQueue.Add("Ambient temp: " + ((int)(ambTempVal)).ToString() + "°C" + Environment.NewLine);
                        this.stringQueue.Add("Remote temp: " + ((int)(remTempVal)).ToString() + "°C" + Environment.NewLine);
                    }
                }
                else if (e.atthandle == BLELIGHTDATAHNDL)
                {
                    if (e.value.Length == 2)
                    {
                        int val           = checked ((int)(e.value[1] << 8 | e.value[0]));
                        int exp           = (val & 0xF000) >> 12;
                        int low_limit_res = (val & 0x0FFF);

                        float lightVal = (float)(0.01 * (1 << (exp)) * low_limit_res);

                        this.LightValue.Text = lightVal.ToString() + " lux";

                        this.stringQueue.Add("Light: " + lightVal.ToString() + " lux" + Environment.NewLine);
                    }
                }
            }
            this.bleSemaphore.Release();
        }
Пример #7
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

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

            // check for a new value from the connected peripheral's heart rate measurement attribute
            if (e.connection == connection_handle && e.atthandle == att_handle_measurement)
            {
                Byte hr_flags       = e.value[0];
                int  hr_measurement = e.value[1];

                // display actual measurement
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Heart rate: {0} bpm", hr_measurement) + Environment.NewLine); });
            }
        }
Пример #8
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            // check for a new value from the connected peripheral's heart rate measurement attribute
            if (e.connection == GetConnectionHandle() && e.atthandle == att_handle_measurement)
            {
                aX = BitConverter.ToInt16(e.value, 0) * accelerometerFSR / Math.Pow(2, 16);
                aY = BitConverter.ToInt16(e.value, 2) * accelerometerFSR / Math.Pow(2, 16);
                aZ = BitConverter.ToInt16(e.value, 4) * accelerometerFSR / Math.Pow(2, 16);
                gX = BitConverter.ToInt16(e.value, 6) * gyroFSR / Math.Pow(2, 16);
                gY = BitConverter.ToInt16(e.value, 8) * gyroFSR / Math.Pow(2, 16);
                gZ = BitConverter.ToInt16(e.value, 10) * gyroFSR / Math.Pow(2, 16);
                AccelerationValue    = new Acceleration(aX, aY, aZ);
                AngularvelocityValue = new AngularVelocity(gX, gY, gZ);
                double x0 = aX * aX + aY * aY + aZ * aZ;
                if (x0 < (this.threshold * this.threshold))
                {
                    if (x1 > 0)
                    {
                        x1 = 0;
                    }

                    return;
                }

                if (x0 - x1 > (this.threshold * this.threshold))
                {
                    if (originalStep < 0)
                    {
                        originalStep = step;
                    }
                    currentStep = step - originalStep;

                    PedometerValue = new PedometerData(step, calorie, distance, duration, currentStep);
                    step           = step + 1;
                }
                x1 = x0;
            }
        }
Пример #9
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

            //Console.Write(log);
            //ThreadSafeDelegate(delegate { txtLog.AppendText(log); });
            if (debug)
            {
                SetLogText(log);
            }

            /*
             * // check for a new value from the connected peripheral's heart rate measurement attribute
             * if (e.connection == connection_handle && e.atthandle == att_handle_measurement)
             * {
             *  Byte hr_flags = e.value[0];
             *  int hr_measurement = e.value[1];
             *  // #################################################################################################
             *  // display actual measurement
             *  //ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Heart rate: {0} bpm", hr_measurement) + Environment.NewLine); });
             *  // #################################################################################################
             *  String logText = String.Format("Heart rate: {0} bpm", hr_measurement) + Environment.NewLine;
             *  SetLogText(logText);
             *
             *  heartRate = hr_measurement;
             *
             *  // Set the LiveCharts Gauge control value;
             *  SetGaugeValue(heartRate);
             *
             *  // Add the value to the LiveCharts lineSeries0 Values
             *  if(myLineSeries0.Values.Count < N)
             *  {
             *      myLineSeries0.Values.Add(heartRate);
             *  }
             *  else
             *  {
             *      myLineSeries0.Values.RemoveAt(0);
             *      myLineSeries0.Values.Add(heartRate);
             *  }
             *
             *  //Value = heartRate;
             * }
             */

            // Which handle was this?
            foreach (var ahandle in connection_handle)
            {
                if (e.connection == ahandle && e.atthandle == att_handle_measurement)
                {
                    Byte hr_flags       = e.value[0];
                    int  hr_measurement = e.value[1];


                    // #################################################################################################
                    // display actual measurement
                    //ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Heart rate: {0} bpm", hr_measurement) + Environment.NewLine); });
                    // #################################################################################################

                    //String logText = String.Format("{0} Handle: {1} Rate: {2} bpm", stopwatch.Elapsed.ToString(), ahandle, hr_measurement) + Environment.NewLine;
                    // For Unix timestamp: https://stackoverflow.com/questions/17632584/how-to-get-the-unix-timestamp-in-c-sharp
                    Int32 timeStamp = new TimeStamp().UnixTimeStampUTC();

                    // For Milliseconds timestamp: https://stackoverflow.com/questions/16032451/get-datetime-now-with-milliseconds-precision
                    //string timeStamp = DateTime.UtcNow.ToString("MM-dd-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

                    String logText = String.Format("{0} Handle: {1} Rate: {2} bpm", timeStamp, ahandle, hr_measurement) + Environment.NewLine;
                    SetLogText(logText);

                    // heartRate is defined near Main()
                    heartRate = hr_measurement;

                    // Set the LiveCharts Gauge control value;
                    SetGaugeValue(heartRate);

                    // Add the value to the LiveCharts lineSeries0 Values

                    /*
                     * if (myLineSeries0.Values.Count < N)
                     * {
                     *  myLineSeries0.Values.Add(heartRate);
                     * }
                     * else
                     * {
                     *  myLineSeries0.Values.RemoveAt(0);
                     *  myLineSeries0.Values.Add(heartRate);
                     * }
                     */

                    /*
                     * if (myValues0.Count < N)
                     * {
                     *  myValues0.Add(heartRate);
                     * }
                     * else
                     * {
                     *  myValues0.RemoveAt(0);
                     *  myValues0.Add(heartRate);
                     * }
                     */

                    //Value = heartRate;
                }
            }
        }
Пример #10
0
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            if (e.connection == connection_handle && e.atthandle == att_handle_measurement)
            {
                UInt32[] times = new UInt32[6];
                UInt16   status;
                byte[]   vals = e.value.Reverse().ToArray();
                for (int i = 0; i < 6; ++i)
                {
                    times[i] = (BitConverter.ToUInt32(vals, ((5 - i) * 3) + 1)) >> 8;
                }
                status = BitConverter.ToUInt16(vals, 0);
                int is_b = (status & 0xf000) >> 15;
                for (int i = 0; i < 3; ++i)
                {
                    if ((status & (1 << i)) == 0)
                    {
                        ++fails[(1 - is_b) * 3 + i];
                    }
                    else
                    {
                        fails[(1 - is_b) * 3 + i] = 0;
                    }
                }
                if (is_b != 0)
                {
                    this.Invoke(new Action(delegate() {
                        this.textBox1.Text      = String.Format("{0:#}", ((float)times[0]) / factor);
                        this.textBox1.BackColor = fails[0] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox2.Text      = String.Format("{0:#}", ((float)times[1]) / factor);
                        this.textBox2.BackColor = fails[0] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox4.Text      = String.Format("{0:#}", ((float)times[2]) / factor);
                        this.textBox4.BackColor = fails[1] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox3.Text      = String.Format("{0:#}", ((float)times[3]) / factor);
                        this.textBox3.BackColor = fails[1] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox6.Text      = String.Format("{0:#}", ((float)times[4]) / factor);
                        this.textBox6.BackColor = fails[2] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox5.Text      = String.Format("{0:#}", ((float)times[5]) / factor);
                        this.textBox5.BackColor = fails[2] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                }
                else
                {
                    this.Invoke(new Action(delegate() {
                        this.textBox12.Text      = String.Format("{0:#}", ((float)times[0]) / factor);
                        this.textBox12.BackColor = fails[3] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox11.Text      = String.Format("{0:#}", ((float)times[1]) / factor);
                        this.textBox11.BackColor = fails[3] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox10.Text      = String.Format("{0:#}", ((float)times[2]) / factor);
                        this.textBox10.BackColor = fails[4] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox9.Text      = String.Format("{0:#}", ((float)times[3]) / factor);
                        this.textBox9.BackColor = fails[4] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox8.Text      = String.Format("{0:#}", ((float)times[4]) / factor);
                        this.textBox8.BackColor = fails[5] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                    this.Invoke(new Action(delegate() {
                        this.textBox7.Text      = String.Format("{0:#}", ((float)times[5]) / factor);
                        this.textBox7.BackColor = fails[5] < MAXFAILS ? Color.FromArgb(0x33, 0xff, 0x99) : Color.FromArgb(0xFF, 0x99, 0x99);
                    }));
                }
#if PRINT_DEBUG
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 0, times[0], ((float)times[0]) / 48.0, ((float)times[0]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 1, times[1], ((float)times[1]) / 48.0, ((float)times[1]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 2, times[2], ((float)times[2]) / 48.0, ((float)times[2]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 3, times[3], ((float)times[3]) / 48.0, ((float)times[3]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 4, times[4], ((float)times[4]) / 48.0, ((float)times[4]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Time {0}: {1:X} = {2:#.##} uS, {3:#.##} deg", 5, times[5], ((float)times[5]) / 48.0, ((float)times[5]) / factor) + Environment.NewLine); });
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Status: {0:X}", status) + Environment.NewLine); });
#endif

                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                String text = "";
                bool   doit = false;
                double angleH = 0f, angleV = 0f;
                if (is_b == 0 && do_b)
                {
                    if (fails[4] == 0)
                    {
                        angleH = times[2];
                        angleV = times[3];
                        text   = String.Format("{0:0.###} {1:0.###}", ((float)times[2]) / factor, ((float)times[3]) / factor);
                        doit   = true;
                    }
                    else if (fails[5] == 0)
                    {
                        angleH = times[4];
                        angleV = times[5];
                        text   = String.Format("{0:0.###} {1:0.###}", ((float)times[4]) / factor, ((float)times[5]) / factor);
                        doit   = true;
                    }
                    else if (fails[3] == 0)
                    {
                        angleH = times[0];
                        angleV = times[1];
                        text   = String.Format("{0:0.###} {1:0.###}", ((float)times[0]) / factor, ((float)times[1]) / factor);
                        doit   = true;
                    }
                }
                else
                {
                    if (fails[1] == 0)
                    {
                        angleH = times[2];
                        angleV = times[3];
                        b_text = String.Format(" {0:0.###} {1:0.###}", ((float)times[2]) / factor, ((float)times[3]) / factor);
                        do_b   = true;
                    }
                    else if (fails[2] == 0)
                    {
                        angleH = times[4];
                        angleV = times[5];
                        b_text = String.Format(" {0:0.###} {1:0.###}", ((float)times[4]) / factor, ((float)times[5]) / factor);
                        do_b   = true;
                    }
                    else if (fails[0] == 0)
                    {
                        angleH = times[0];
                        angleV = times[1];
                        b_text = String.Format(" {0:0.###} {1:0.###}", ((float)times[0]) / factor, ((float)times[1]) / factor);
                        do_b   = true;
                    }
                    else
                    {
                        do_b = false;
                    }
                }
                if (doit)
                {
                    IPAddress addr = IPAddress.Parse("127.0.0.1");
                    text += b_text;
                    IPEndPoint ep          = new IPEndPoint(addr, 8051);
                    byte[]     send_buffer = Encoding.ASCII.GetBytes(text);
                    sock.SendTo(send_buffer, ep);
                }
            }
            else if (e.connection == connection_handle && e.atthandle == att_handle_measurement_ccc)
            {
                ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Got IMU reading") + Environment.NewLine); });
            }
        }
Пример #11
0
        /// <summary>
        /// A new value arrived via notification or read request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">AttributeValueEventArgs</param>
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            lock (o)
            {
                String log = String.Format("attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                           e.connection,
                                           e.atthandle,
                                           e.type,
                                           ByteArrayToHexString(e.value)
                                           );
                Console.Write(log);
                //ThreadSafeDelegate(delegate { txtLog.AppendText(log); });
                int measurement = 0;

                // each connection has its own list of serv. and char.
                switch (e.connection)
                {
                case 0:
                    // con - get serv. , get char list ... alle !!
                    // Only display char. we know so check the List
                    //  for (int i = 0; i < att_List.Length; i++)
                    // {
                    if (e.atthandle == tmpCharContainer1.Handle)
                    {
                        measurement             = ByteArrayToInt(e.value);
                        tmpCharContainer1.Value = measurement;
                        // display actual measurement

                        Console.WriteLine(String.Format("Conn.: {0}   Sensor Data: {1} ListNr.: {2} ", 0, measurement, 0) + Environment.NewLine);

                        ThreadSafeDelegate(delegate { sensor_distance_value_label.Text = "" + measurement + " cm"; });
                    }
                    if (e.atthandle == tmpCharContainer2.Handle)
                    {
                        measurement             = ByteArrayToInt(e.value);
                        tmpCharContainer1.Value = measurement;
                        // display actual measurement

                        Console.WriteLine(String.Format("Conn.: {0}   Sensor Data: {1} ListNr.: {2} ", 0, measurement, 1) + Environment.NewLine);

                        ThreadSafeDelegate(delegate { sensor_distance_raw_label.Text = "" + measurement; });
                    }
                    if (app_state == STATE_READ_ATTR_VAL)
                    {
                        ThreadSafeDelegate(delegate { txtLog.AppendText("Read val: \n" + e.value); });
                    }
                    break;
                // Next connection...

                /*          case 1:
                 *            // Only display char. we know so check the List
                 *            for (int i = 0; i < att_List.Length; i++)
                 *            {
                 *                if (att_List[i] != null && e.atthandle == att_List[i].Handle)
                 *                {
                 *                    measurement = ByteArrayToInt(e.value);
                 *                    att_List[i].Value = measurement;
                 *                    // display actual measurement
                 *                    ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("Conn.: {0}   Sensor Data: {1} ListNr.: {2} ", 1, measurement, i) + Environment.NewLine); });
                 *                }
                 *            }
                 *            break;*/

                default: ThreadSafeDelegate(delegate { txtLog.AppendText(String.Format("!!! No suitable connection {0} for Sensor Data: {1}  with handle {2}", e.connection, e.value, e.atthandle) + Environment.NewLine); });
                    break;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BLEATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                MessageWriter.LogWrite("ble_evt_attclient_attribute_value: ", string.Format("connection={0}, atthandle={1}, type={2}, value={3}",
                                                                                            e.connection,
                                                                                            e.atthandle,
                                                                                            e.type,
                                                                                            BitConverter.ToString(e.value)));

                // Identify peripheral
                BLEPeripheral peripheral;
                if (!connectedDevices.TryGetConnection(e.connection, out peripheral))
                {
                    MessageWriter.LogWrite("Unable to find connection " + e.connection);
                    return;
                }

                // Identify attribute
                Models.Attribute attribute;
                if (!peripheral.TryGetAttribute(e.atthandle, out attribute))
                {
                    MessageWriter.LogWrite("Unable to find attribute " + e.connection);
                    return;
                }

                attribute.Value = e.value;
                WriteRawData(peripheral);
                //MessageWriter.LogWrite(String.Format("Wrote {0} to {1}", BitConverter.ToString(e.value), attribute.ToString()));

                if (peripheral.Services.ContainsKey("PiezoelectricService"))
                {
                    if (peripheral.Services["PiezoelectricService"].Characteristics.ContainsKey("PiezoVoltage"))
                    {
                        if (peripheral.Services["PiezoelectricService"].Characteristics["PiezoVoltage"].ValueAttribute.Handle == e.atthandle)
                        {
                            WritePzVoltData(peripheral);
                        }
                    }
                }

                /*// DATA PACKET
                 * if (peripheral.Characteristics.ContainsKey("Data"))
                 * {
                 *  if (e.atthandle == peripheral.Characteristics["Data"].ValueAttribute.Handle)
                 *  {
                 *      // Decode packet
                 *      // The following decodes each pair of bytes into a single data point
                 *      double[] val = new double[e.value.Length / 2];
                 *      for (int i = 0; i < val.Length; i++)
                 *      {
                 *          short raw = BitConverter.ToInt16(e.value, 2 * i);
                 *          val[i] = raw * 2500 / 2047;
                 *      }
                 *
                 *      peripheral.SetCharacteristicValue("Data", val.Average());
                 *
                 *      WriteData(peripheral, val);
                 *  }
                 * }
                 *
                 * // Battery
                 * if (peripheral.Characteristics.ContainsKey("Battery"))
                 * {
                 *  if (e.atthandle == peripheral.Characteristics["Battery"].ValueAttribute.Handle)
                 *  {
                 *      if (e.value.Length == 2)
                 *      {
                 *          // Get data
                 *          short data = BitConverter.ToInt16(e.value, 0);
                 *
                 *          // Calculate rail
                 *          peripheral.SetCharacteristicValue("Battery", data * 2500 / 2047);
                 *      }
                 *  }
                 * }
                 *
                 * // TEMPERATURE PACKET
                 * if (peripheral.Characteristics.ContainsKey("Temperature"))
                 * {
                 *  if (e.atthandle == peripheral.Characteristics["Temperature"].ValueAttribute.Handle)
                 *  {
                 *      short value = BitConverter.ToInt16(e.value, 0);
                 *
                 *      peripheral.SetCharacteristicValue("Temperature", (value * 2500 / 2047) * 10 / 45 - 169); // Not really characterized, but it should be close
                 *  }
                 * }
                 *
                 * // Low Power Mode
                 * if (peripheral.Characteristics.ContainsKey("LPM"))
                 * {
                 *  if (e.atthandle == peripheral.Characteristics["LPM"].ValueAttribute.Handle)
                 *  {
                 *      // Sleep bit
                 *      if ((e.value[0] & 0x01) == 0x00) // Device is asleep
                 *      {
                 *          peripheral.LowPowerMode = BLEPeripheral.LPM.Enabled;
                 *      }
                 *      else // Device is awake
                 *      {
                 *          peripheral.LowPowerMode = BLEPeripheral.LPM.Disabled;
                 *      }
                 *  }
                 * }*/
            });
        }
Пример #13
0
        //-------------------------------------------------------------------------------------------------------------
        // Event handler for the ATTClientAttributeValue event,
        // triggered when a new attribute value is sent to this application.
        public void ATTClientAttributeValueEvent(object sender, Bluegiga.BLE.Events.ATTClient.AttributeValueEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_attribute_value: connection={0}, atthandle={1}, type={2}, value=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.atthandle,
                                       e.type,
                                       ByteArrayToHexString(e.value)
                                       );

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

            // Check for a new value from the connected peripheral's heart rate measurement attribute.
            if (e.connection == connection_handle && e.atthandle == att_handle_measurement)
            {
                // The first byte of heart rate record contains a set of flags.
                byte flags = e.value[0];

                //---------------------------------------------------------------------------------
                // Code to get the RR intervalues
                // Ref: https://stackoverflow.com/questions/17422218/bluetooth-low-energy-how-to-parse-r-r-interval-value

                ushort offset = 1;

                int hrValue = 0;

                bool HRC2 = (flags & 1) == 1;
                if (HRC2) //this means the BPM is un uint16
                {
                    short hr = BitConverter.ToInt16(e.value, offset);
                    offset += 2;

                    hrValue = hr;
                }
                else //BPM is uint8
                {
                    byte hr = e.value[offset];
                    offset += 1;

                    hrValue = hr;
                }

                //see if EE is available
                //if so, pull 2 bytes
                bool ee = (flags & (1 << 3)) != 0;
                if (ee)
                {
                    offset += 2;
                }

                //see if RR is present
                //if so, the number of RR values is total bytes left / 2 (size of uint16)
                bool          rr             = (flags & (1 << 4)) != 0;
                int           countRR        = 0;
                List <double> rrIntervalList = new List <double>();

                if (rr)
                {
                    countRR = (e.value.Length - offset) / 2;
                    for (int i = 0; i < countRR; i++)
                    {
                        //each existence of these values means an R-Wave was already detected
                        //the ushort means the time (1/1024 seconds) since last r-wave
                        ushort value = BitConverter.ToUInt16(e.value, offset);

                        double intervalLengthInSeconds = value / 1024.0;
                        offset += 2;

                        rrIntervalList.Add(intervalLengthInSeconds);
                    }
                }
                //---------------------------------------------------------------------------------

                // The Heart Rate value in BPM is the second byte
                int hr_measurement = e.value[1];

                // Display the Heart rate and RR interval values here.
                string msg = "Heart rate: " + hr_measurement + Environment.NewLine + "CountRR: " + countRR + Environment.NewLine;
                for (int k = 0; k < countRR; k++)
                {
                    msg += rrIntervalList[k] + " seconds" + Environment.NewLine;
                }
                msg += Environment.NewLine;

                ThreadSafeDelegate(delegate { txtLog.AppendText(msg); });

                //ThreadSafeDelegate(delegate { txtLog.AppendText(
                //    String.Format("Heart rate: {0} bpm", hr_measurement) + Environment.NewLine); });
            }
        }