Ejemplo n.º 1
0
        private void OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {

            var data = DataReader.FromBuffer(args.CharacteristicValue).ReadString(args.CharacteristicValue.Length);
            SendMessageToServer(data);

        }
Ejemplo n.º 2
0
 //値の取得
 static private void TemperatureMeasurementChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
 {
     byte[] temperatureData = new byte[eventArgs.CharacteristicValue.Length];
     Windows.Storage.Streams.DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(temperatureData);
     float calx =  BitConverter.ToSingle(temperatureData, 0);
     float caly = BitConverter.ToSingle(temperatureData, 4);
     float calz =  BitConverter.ToSingle(temperatureData, 8);
     pitch = calx;
     roll = caly;
     yaw = calz;
     Console.WriteLine("count:" + temperatureData.Length.ToString() + " " + calx.ToString("0.00") + " " + caly.ToString("0.00") + " " + calz.ToString("0.00"));
 }
Ejemplo n.º 3
0
        // Read data change handler
        async void incomingData_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            string message = System.Text.Encoding.UTF8.GetString(bArray);

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                receiveTextBox.Text = message;
            });
        }
        private void NotifyCharacteristic_ValueChanged(GattCharacteristic sender, 
            GattValueChangedEventArgs args)
        {
            //notification that the NeoPixel color has changed, update the UI with the new value
            byte[] bArray = new byte[args.CharacteristicValue.Length];
            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(bArray);

            var color = Color.FromArgb(0,bArray[0], bArray[1], bArray[2]);
            string result = color.ToString();

            //remove alpha channel from string (only rgb was returned)
            result = result.Remove(1, 2);

            Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { txtLastNotificationHex.Text = result; });
            
        }
Ejemplo n.º 5
0
        private async void DataSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var stream = args.CharacteristicValue.AsStream();
            var br     = new BinaryReader(stream);

            var cmdId    = br.ReadByte();
            var notUid   = br.ReadUInt32();
            var attr1    = (NotificationAttribute)br.ReadByte();
            var attr1len = br.ReadUInt16();
            var attr1val = br.ReadChars(attr1len);
            var attr2    = (NotificationAttribute)br.ReadByte();
            var attr2len = br.ReadUInt16();
            var attr2val = br.ReadChars(attr2len);

            EventFlags?flags = null;

            if (FlagCache.ContainsKey(notUid))
            {
                flags = FlagCache[notUid];
            }

            var not = new PlainNotification()
            {
                EventFlags = flags,
                Uid        = notUid,
                Title      = new string(attr1val),
                Message    = new string(attr2val)
            };

            OnNotification?.Invoke(not);
        }
Ejemplo n.º 6
0
        // Gyroscope change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Gyroscope_2
        async void gyroChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            Int16 data = (Int16)(((UInt16)bArray[1] << 8) + (UInt16)bArray[0]);
            double x = (double)data * (500.0 / 65536);
            data = (Int16)(((UInt16)bArray[3] << 8) + (UInt16)bArray[2]);
            double y = (double)data * (500.0 / 65536);
            data = (Int16)(((UInt16)bArray[5] << 8) + (UInt16)bArray[4]);
            double z = (double)data * (500.0 / 65536);

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                GyroXOut.Text = "X: " + x.ToString();
                GyroYOut.Text = "Y: " + y.ToString();
                GyroZOut.Text = "Z: " + z.ToString();
            });
        }
Ejemplo n.º 7
0
        private void OnHandle_SomethingChanged(object o, GattValueChangedEventArgs args)
        {
            var sender = (GattCharacteristic) o;
            var senderData = sender.Uuid;
            var byteArray = args.CharacteristicValue.ToArray();

            if (senderData == ParrotUuids.Characteristic_B0E_DroneState)
            {
                if ((byteArray[0] == 4)
                    && (byteArray[2] == 2)
                    && (byteArray[3] == 3)
                    && (byteArray[4] == 1))
                {
                    switch (byteArray[6])
                    {
                        case 0:
                            State = DroneState.Landed;
                            break;
                        case 1:
                            State = DroneState.TakeingOff;
                            break;
                        case 2:
                            State = DroneState.Hovering;
                            break;
                        case 3:
                            State = DroneState.Flying;
                            break;
                        case 4:
                            State = DroneState.Landing;
                            break;
                        case 5:
                            State = DroneState.Emergency;
                            break;
                        case 6:
                            State = DroneState.Rolling;
                            break;
                    }

                }

                SomethingChanged?.Invoke(this, new CustomEventArgs("Drone State: " + State));
                return;
            }

            if (senderData == ParrotUuids.Characteristic_B0F_Battery)
            {
                SomethingChanged?.Invoke(this, new CustomEventArgs("Battery: " + BitConverter.ToString(byteArray)));
                return;
            }

            var StateString = BitConverter.ToString(byteArray);
            SomethingChanged?.Invoke(this, new CustomEventArgs(senderData + ": " + StateString));


        }
        void characteristics_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            byte[] data = new byte[args.CharacteristicValue.Length];
            Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);

           //Update properties
            if (sender.Uuid == GattCharacteristicUuids.BatteryLevel)
            {
                BatteryLevel = Convert.ToInt32(data[0]);
            }
        }
 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     // BT_Code: An Indicate or Notify reported that the value has changed.
     // Display the new value with a timestamp.
     var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat);
     var message = $"Value at {DateTime.Now:hh:mm:ss.FFF}: {newValue}";
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
         () => CharacteristicLatestValue.Text = message);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Invoked when Windows receives data from your Bluetooth device.
        /// </summary>
        /// <param name="sender">The GattCharacteristic object whose value is received.</param>
        /// <param name="args">The new characteristic value sent by the device.</param>
        private void Characteristic_ValueChanged(
            GattCharacteristic sender,
            GattValueChangedEventArgs args)
        {
            var data = new byte[args.CharacteristicValue.Length];

            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);

            // Process the raw data received from the device.
            var value = ProcessData(data);
            value.Timestamp = args.Timestamp;

            lock (datapoints)
            {
                datapoints.Add(value);
            }

            if (ValueChangeCompleted != null)
            {
                ValueChangeCompleted(value);
            }
        }
Ejemplo n.º 11
0
        protected virtual void DidCharacteristicNotify(GattCharacteristic characteristic, GattValueChangedEventArgs args)
        {
            byte[] data = args.CharacteristicValue.ToArray();

            if (characteristic.Uuid == BluetoothRobotConstants.RECEIVE_DATA_CHARACTERISTIC_UUID)
            {
                if (IsBTFirmwareUpdateMode())
                {
                    DidReceiveFirmwareData(data);
                }
                else
                {
                    DidNotifyByReceiveDataCharacteristic(BaseService.ConvertBytesFromHexBytes(data));
                }
            }
            else if (characteristic.Uuid == BluetoothRobotConstants.RSSI_REPORT_SERVICE_UUID)
            {
                Debug.WriteLine("RSSI: " + BaseService.ConvertIntFromBytes(data));
            }
            else if (characteristic.Uuid == BluetoothRobotConstants.MODULE_PARAMETER_CUSTOM_BROADCAST_DATA_CHARACTERISTIC_UUID)
            {
                CustomBroadcastData = BaseService.ConvertDictionaryFromBytes(data);
            }
        }
		void recordAccessControlPoint_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
		{
			this.IRecordAccessControlPointCharacteristic.ProcessData(args.CharacteristicValue);
		}
Ejemplo n.º 13
0
        /// <summary>
        /// 鼠标事件收到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void MouseEventCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            using (var reader = DataReader.FromBuffer(args.CharacteristicValue))
            {
                byte[] bytesData = new byte[2 * sizeof(int)];
                reader.ReadBytes(bytesData);
                int mouseEventInt = BitConverter.ToInt32(bytesData, 0);
                switch ((MouseEvent)mouseEventInt)
                {
                case MouseEvent.LeftClick:
                    if (isLeftButtonDown)
                    {
                        mouseSimulator.LeftButtonUp();
                        isLeftButtonDown = false;
                        leftClickNo      = 0;
                        stopwatch.Reset();
                    }
                    else if (++leftClickNo == 2)
                    {
                        leftClickNo = 0;
                        if (stopwatch.IsRunning)
                        {
                            mouseSimulator.LeftButtonDoubleClick();
                        }

                        stopwatch.Reset();
                    }
                    else
                    {
                        stopwatch.Start();
                        await Task.Delay(300);

                        if (stopwatch.IsRunning)
                        {
                            mouseSimulator.LeftButtonClick();
                            leftClickNo = 0;
                            stopwatch.Reset();
                        }
                        Debug.WriteLine("LeftClick");
                    }
                    break;

                case MouseEvent.RightClick:
                    mouseSimulator.RightButtonClick();
                    break;

                case MouseEvent.LeftDown:
                    mouseSimulator.LeftButtonDown();
                    break;

                case MouseEvent.RightDown:
                    mouseSimulator.RightButtonDown();
                    Debug.WriteLine("LeftDown");
                    break;

                case MouseEvent.LeftUp:
                    mouseSimulator.LeftButtonUp();
                    Debug.WriteLine("Up");
                    break;

                case MouseEvent.RightUp:
                    mouseSimulator.RightButtonUp();
                    break;

                case MouseEvent.VerticalScroll:
                    int verticalScrollAmount = BitConverter.ToInt32(bytesData, sizeof(int));
                    if (verticalScrollAmount != 0)
                    {
                        int amount = (verticalScrollAmount - oldVertical) / 5;
                        if (amount > 0)
                        {
                            for (int i = 0; i < amount; ++i)
                            {
                                mouseSimulator.VerticalScroll(1);
                            }
                        }
                        else if (amount < 0)
                        {
                            for (int i = 0; i < -amount; ++i)
                            {
                                mouseSimulator.VerticalScroll(-1);
                            }
                        }
                    }
                    oldVertical = verticalScrollAmount;
                    break;

                case MouseEvent.HorizontalScroll:
                    int horizontalScrollAmount = BitConverter.ToInt32(bytesData, sizeof(int));
                    if (horizontalScrollAmount != 0)
                    {
                        int amount = (horizontalScrollAmount - oldHorizontal) / 5;
                        if (amount > 0)
                        {
                            for (int i = 0; i < amount; ++i)
                            {
                                mouseSimulator.HorizontalScroll(1);
                            }
                        }
                        else if (amount < 0)
                        {
                            for (int i = 0; i < -amount; ++i)
                            {
                                mouseSimulator.HorizontalScroll(-1);
                            }
                        }
                    }
                    oldHorizontal = horizontalScrollAmount;
                    break;
                }
            }
        }
Ejemplo n.º 14
0
        public void Charac_ValueChangedAsync(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            // Dont run if we do not wish to be connected anymore OR we are still waiting for all parameters
            if (BLEdisconnectFlag || !senParamsFilled)
            {
                return;
            }


            if (deltaT > 0)
            {
                timer.Interval = 3 * deltaT;
                timer.Start();
            }

            CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out byte[] data);



            //Asuming Encoding is in ASCII, can be UTF8 or other!
            string dataFromNotify = Encoding.ASCII.GetString(data);

            byte[]   bytes  = Encoding.UTF8.GetBytes(dataFromNotify);
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            Data     data1  = (Data)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Data));

            handle.Free();
            // SetText($"Handle 17: {data1.counter} - {(double)da ta1.time/1000} - {(double)data1.temp/10} - {data1.sens}");

            UInt16 old_ecFlex_timer = ecFlex_timer;
            UInt16 oldDeltaT        = deltaT;

            deltaT = (UInt16)((UInt16)((data[3] << 8) + data[2]) - ecFlex_timer);
            if (deltaT == 0)
            {
                deltaT = oldDeltaT;
            }

            double oldTimeVal = (double)(deltaT * ecFlex_idx / 1000);

            ecFlex_idx   = (UInt16)((data[1] << 8) + data[0]);
            ecFlex_timer = (UInt16)((data[3] << 8) + data[2]);
            ecFlex_temp  = (UInt16)((data[5] << 8) + data[4]);
            ecFlex_adc   = (UInt16)((data[7] << 8) + data[6]);
            double sensorVal = calcSensorVal(ecFlex_adc);



            if (oldTimeVal > 0) // No point of logging data if not ready
            {
                // Workaround for nonsensical time values
                if (((double)deltaT * (double)ecFlex_idx / 1000) > (3 * deltaT / 1000 + timeVal))
                {
                    timeVal = timeVal + (double)deltaT / 1000;
                }
                else
                {
                    timeVal = ((double)deltaT * (double)ecFlex_idx) / 1000;
                }
                SetText($"{ecFlex_idx} - {(deltaT * (float)ecFlex_idx / 1000)} - {(Single)ecFlex_temp / 10} - {ecFlex_adc}");

                this.Invoke((MethodInvoker) delegate { chart1.Series[0].Points.AddY(sensorVal); chart1.Series[0].Points.AddXY((Single)timeVal, sensorVal); });



                try
                {
                    Invoke((MethodInvoker) delegate { File.AppendAllText(fileName, $"{ecFlex_idx},{timeVal},{(Single)ecFlex_temp / 10},{sensorVal}{Environment.NewLine}"); });
                }
                catch (IOException er)
                {
                    //  if (er.Message.Contains("being used"))
                    { // Just append date if unable to access file.
                        string oldFileName = newFileName;
                        newFileName = ($"{fileName.Substring(0, fileName.Length - 4)}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv").Replace("/", "_");
                        File.Copy(oldFileName, newFileName, true);

                        // Dont forget to log the new sample in the new file
                        this.Invoke((MethodInvoker) delegate { File.AppendAllText(newFileName, $"{ecFlex_idx},{timeVal},{(Single)ecFlex_temp / 10},{sensorVal}{Environment.NewLine}"); });
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private void MouseMotionCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            using (var reader = DataReader.FromBuffer(args.CharacteristicValue))
            {
                //如果是长按的话
                if (stopwatch.IsRunning)
                {
                    mouseSimulator.LeftButtonDown();
                    isLeftButtonDown = true;
                    stopwatch.Reset();
                }

                byte[] bytesData = new byte[2 * sizeof(double)];
                reader.ReadBytes(bytesData);
                CursorPoint cursorPoint = new CursorPoint
                {
                    X = BitConverter.ToDouble(bytesData, 0),
                    Y = BitConverter.ToDouble(bytesData, sizeof(double))
                };
                System.Diagnostics.Debug.WriteLine("new: " + cursorPoint.X.ToString() + ", " + cursorPoint.Y.ToString());
                System.Diagnostics.Debug.WriteLine("new: " + oldCursorPoint.X.ToString() + ", " + oldCursorPoint.Y.ToString());
                if (cursorPoint.X == 0 && cursorPoint.Y == 0)
                {
                    oldCursorPoint = cursorPoint;
                    System.Diagnostics.Debug.WriteLine("归0");
                    return;
                }
                var moveX = (cursorPoint.X - oldCursorPoint.X);
                var moveY = (cursorPoint.Y - oldCursorPoint.Y);
                Debug.WriteLine("PC: " + moveX.ToString() + ", " + moveY.ToString());

                int movXTotal = 0;
                int movYTotal = 0;
                while (true)
                {
                    bool stopMovingX = false;
                    bool stopMovingY = false;
                    if (moveX == 0)
                    {
                        stopMovingX = true;
                    }
                    if (moveY == 0)
                    {
                        stopMovingY = true;
                    }

                    if (moveX > 0)
                    {
                        if (++movXTotal < moveX)
                        {
                            mouseSimulator.MoveMouseBy(1, 0);
                        }
                        else
                        {
                            stopMovingX = true;
                        }
                    }
                    else if (moveX < 0)
                    {
                        if (--movXTotal > moveX)
                        {
                            mouseSimulator.MoveMouseBy(-1, 0);
                        }
                        else
                        {
                            stopMovingX = true;
                        }
                    }

                    if (moveY > 0)
                    {
                        if (++movYTotal < moveY)
                        {
                            mouseSimulator.MoveMouseBy(0, 1);
                        }
                        else
                        {
                            stopMovingY = true;
                        }
                    }
                    else if (moveY < 0)
                    {
                        if (--movYTotal > moveY)
                        {
                            mouseSimulator.MoveMouseBy(0, -1);
                        }
                        else
                        {
                            stopMovingY = true;
                        }
                    }
                    if (stopMovingX && stopMovingY)
                    {
                        break;
                    }
                }
                //mouseSimulator.MoveMouseBy((int)moveX, (int)moveY);
                oldCursorPoint = cursorPoint;
            }
        }
Ejemplo n.º 16
0
        static void BatteryLevelChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var reader = Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue);

            Console.WriteLine("{0} = {1}", sender.Uuid, reader.ReadByte());
        }
Ejemplo n.º 17
0
        private async void NotificationSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            //Received 8 bytes about some kind of notification
            var valueBytes = args.CharacteristicValue.ToArray();
            var dat        = ByteArrayToNotificationSourceData(valueBytes);


            if (dat.EventFlags.HasFlag(EventFlags.EventFlagPreExisting))
            {
                //We dont care about old notifications
                return;
            }


            FlagCache[dat.NotificationUID] = dat.EventFlags;

            //Ask for more data through the control point characteristic
            var attributes = new GetNotificationAttributesData
            {
                CommandId          = 0x0,
                NotificationUID    = dat.NotificationUID,
                AttributeId1       = (byte)NotificationAttribute.Title,
                AttributeId1MaxLen = 16,
                AttributeId2       = (byte)NotificationAttribute.Message,
                AttributeId2MaxLen = 32
            };

            var bytes = StructureToByteArray(attributes);

            try
            {
                var status =
                    await
                    this.ControlPointCharacteristic.WriteValueAsync(bytes.AsBuffer(),
                                                                    GattWriteOption.WriteWithResponse);
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 18
0
        private void dataCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var data = new byte[args.CharacteristicValue.Length];

            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);

            OnSensorValueChanged(data, args.Timestamp);
        }
Ejemplo n.º 19
0
 private void characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
 }
Ejemplo n.º 20
0
        private async void NotificationSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            //Received 8 bytes about some kind of notification
            var valueBytes = args.CharacteristicValue.ToArray();
            var dat = ByteArrayToNotificationSourceData(valueBytes);


            if (dat.EventFlags.HasFlag(EventFlags.EventFlagPreExisting))
            {
                //We dont care about old notifications
                return;
            }


            FlagCache[dat.NotificationUID] = dat.EventFlags;

            //Ask for more data through the control point characteristic
            var attributes = new GetNotificationAttributesData
            {
                CommandId = 0x0,
                NotificationUID = dat.NotificationUID,
                AttributeId1 = (byte) NotificationAttribute.Title,
                AttributeId1MaxLen = 16,
                AttributeId2 = (byte) NotificationAttribute.Message,
                AttributeId2MaxLen = 32
            };

            var bytes = StructureToByteArray(attributes);

            try
            {
                var status =
                    await
                        this.ControlPointCharacteristic.WriteValueAsync(bytes.AsBuffer(),
                            GattWriteOption.WriteWithResponse);
            }
            catch (Exception)
            {
                
            }
        }
Ejemplo n.º 21
0
 private void BluetoothNotifyReceivedHandler(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out var bytes);
     InvokeDataReceived(new ButtplugDeviceDataEventArgs("rx", bytes));
 }
Ejemplo n.º 22
0
        private void GattCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            if (args == null) return;
            if (args.CharacteristicValue.Length == 0) return;

            var arrayLenght = (int)args.CharacteristicValue.Length;
            var hrData = new byte[arrayLenght];
            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(hrData);

            //Convert to string  
            var hrValue = ProcessData(hrData);
            Debug.WriteLine(hrValue);
            HeartRateValue = hrValue.ToString();

            HrCollection.Add(new HrModel { HeartRate = hrValue });
            DisplayHrData();

        }
Ejemplo n.º 23
0
 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     SomethingChanged?.Invoke(sender, args);
 }
        /** associated event for a value changed*/
        private void AssociatedCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            byte[] data = new byte[args.CharacteristicValue.Length];
            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);

            String value = Encoding.UTF8.GetString(data, 0, data.Length);

            evResponseReceived?.Invoke(value);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// AuthCharacteristic handler. Checking input requests to device from Band
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void AuthCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            if (sender.Uuid == AUTH_CHARACTERISTIC)
            {
                List <byte> request      = args.CharacteristicValue.ToArray().ToList();
                byte        authResponse = 0x10;
                byte        authSendKey  = 0x01;
                byte        authRequestRandomAuthNumber = 0x02;
                byte        authRequestEncryptedKey     = 0x03;
                byte        authSuccess = 0x01;
                byte        authFail    = 0x04;

                if (request[2] == authFail)
                {
                    Debug.WriteLine("Authentication error");
                    _WaitHandle.Set();
                }

                if (request[0] == authResponse && request[1] == authSendKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 2 started");

                    if (await SendAuthNumberAsync())
                    {
                        Debug.WriteLine("Level 2 success");
                    }
                }
                else if (request[0] == authResponse && request[1] == authRequestRandomAuthNumber && request[2] == authSuccess)
                {
                    Debug.WriteLine("Level 3 started");

                    if (await SendEncryptedRandomKeyAsync(args))
                    {
                        Debug.WriteLine("Level 3 success");
                    }
                }
                else if (request[0] == authResponse && request[1] == authRequestEncryptedKey && request[2] == authSuccess)
                {
                    Debug.WriteLine("Authentication completed");
                    _LocalSettings.Values["isAuthorized"] = true;
                    _WaitHandle.Set();
                }
            }
        }
Ejemplo n.º 26
0
        private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var reader = DataReader.FromBuffer(args.CharacteristicValue);

            Console.WriteLine($"x:{reader.ReadUInt16() / 1000}, y: {reader.ReadUInt16() / 1000}, z: {reader.ReadUInt16() / 1000}");
        }
Ejemplo n.º 27
0
        // ---------------------------------------------------
        //           GATT Notification Handlers
        // ---------------------------------------------------

        // IR temperature change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#IR_Temperature_Sensor
        async void tempChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);
            double AmbTemp = (double)(((UInt16)bArray[3] << 8) + (UInt16)bArray[2]);
            AmbTemp /= 128.0;

            Int16 temp = (Int16)(((UInt16)bArray[1] << 8) + (UInt16)bArray[0]);
            double Vobj2 = (double)temp;
            Vobj2 *= 0.00000015625;
            double Tdie = AmbTemp + 273.15;

            const double S0 = 5.593E-14;            // Calibration factor
            const double a1 = 1.75E-3;
            const double a2 = -1.678E-5;
            const double b0 = -2.94E-5;
            const double b1 = -5.7E-7;
            const double b2 = 4.63E-9;
            const double c2 = 13.4;
            const double Tref = 298.15;

            double S = S0 * (1 + a1 * (Tdie - Tref) + a2 * Math.Pow((Tdie - Tref), 2));
            double Vos = b0 + b1 * (Tdie - Tref) + b2 * Math.Pow((Tdie - Tref), 2);
            double fObj = (Vobj2 - Vos) + c2 * Math.Pow((Vobj2 - Vos), 2);
            double tObj = Math.Pow(Math.Pow(Tdie, 4) + (fObj / S), 0.25);

            tObj = (tObj - 273.15);
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                AmbTempOut.Text = string.Format("Chip:\t{0:0.0####}", AmbTemp);
                ObjTempOut.Text = string.Format("IR:  \t{0:0.0####}", tObj);
            });
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Callback when the read characteristic changes.
        /// 
        /// This method expects a single 32 bit integer to be received.
        /// </summary>
        /// <param name="sender">The characteristic upon which that change occurred</param>
        /// <param name="args">The event arguments</param>
        private async void headingValueChanged(GattCharacteristic sender, 
            GattValueChangedEventArgs args)
        {
            try
            {
                Debug.Assert(args.CharacteristicValue.Length == 4,
                    string.Format("Characteristic length of {0} isn't the expected length of 4",
                    args.CharacteristicValue.Length));

                var bytes = args.CharacteristicValue.ToArray();
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    //
                    // Don't read or write the heading property while not on the main thread
                    //
                    //
                    // Don't read heading property while not on the main thread
                    //
                    var currentHeading = this.Heading;

                    var newHeading = bytes[0] +
                                     (bytes[1] << 8) +
                                     (bytes[2] << 16) +
                                     (bytes[3] << 24);

                    double delta = angleDifference(currentHeading, newHeading);

                    double nextHeading = currentHeading + delta;

                    //Needed to prevent an error
                    this.CompassNeedleAnimation.From = currentHeading;
                    this.CompassNeedleAnimation.To = nextHeading;

                    Storyboard sb = (Storyboard)CompassNeedle.Resources["spin"];
                    sb.Begin();

                    // Update the text
                    this.CurrentHeadingTextBlock.Text = string.Format("{0}°", newHeading);

                    // Save the new heading
                    this.Heading = newHeading;
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 29
0
        // Humidity change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Humidity_Sensor_2
        async void humidChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            double humidity = (double)((((UInt16)bArray[1] << 8) + (UInt16)bArray[0]) & ~0x0003);
            humidity = (-6.0 + 125.0 / 65536 * humidity); // RH= -6 + 125 * SRH/2^16
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                HumidOut.Text = humidity.ToString();
            });
        }
Ejemplo n.º 30
0
 async void NotifyMagnetometer(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     byte[]  rawData = BLE_Utilities.getDataBytes(args);
     float[] vals    = SensorConvert.convertAccelerometer(rawData);
     await this.Dispatcher.BeginInvoke((Action)(() => setMagnetometer(vals[0], vals[1], vals[2])));
 }
 /// <summary>
 /// When the Characteristics value changes.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="args">The <see cref="GattValueChangedEventArgs"/> instance containing the event data.</param>
 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
         Windows.UI.Core.CoreDispatcherPriority.Normal,
         () => { SetValue(args.CharacteristicValue); });
 }
		void bloodPressureMeasurementCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
		{
			var result = this.BloodPressureMeasurementCharacteristicHandler.ProcessData(File.ToBytes(args.CharacteristicValue));
			if (MeasurementNotification != null)
				MeasurementNotification(result);
		}
Ejemplo n.º 33
0
 private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     Console.WriteLine(tag, "Notification recieved from SUOTA_STATUS_NTF_UUID");
 }
Ejemplo n.º 34
0
        // Accelerometer change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Accelerometer_2
        async void accelChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            double x = (SByte)bArray[0] / 64.0;
            double y = (SByte)bArray[1] / 64.0;
            double z = (SByte)bArray[2] / 64.0 * -1;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                RecTranslateTransform.X = x * 90;
                RecTranslateTransform.Y = y * -90;

                AccelXOut.Text = "X: " + x.ToString();
                AccelYOut.Text = "Y: " + y.ToString();
                AccelZOut.Text = "Z: " + z.ToString();

                // 閾値を決めてモーターを動かす
                if (y > 0.15)
                {
                    // 前へ
                    MotorLeft.Text = "Left: forward";
                    MotorRight.Text = "Right: forward";
                }
                else if (y < -0.15)
                {
                    // 後ろへ
                    MotorLeft.Text = "Left: back";
                    MotorRight.Text = "Right: back";
                }
                else if (x < -0.15)
                {
                    // 左へ
                    MotorLeft.Text = "Left: stop";
                    MotorRight.Text = "Right: forward";
                }
                else if (x > 0.15)
                {
                    // 右へ
                    MotorLeft.Text = "Left: forward";
                    MotorRight.Text = "Right: stop";
                }
                else
                {
                    // 停止
                    MotorLeft.Text = "Left: stop";
                    MotorRight.Text = "Right: stop";
                }
                if (RPi.gpio != null)
                {
                    if (y > 0.15)
                    {
                        // 前へ
                        motorLeft.Direction = 1;
                        motorRight.Direction = 1;
                    }
                    else if (y < -0.15)
                    {
                        // 後ろへ
                        motorLeft.Direction = -1;
                        motorRight.Direction = -1;
                    }
                    else if (x < -0.15)
                    {
                        // 左へ
                        motorLeft.Direction = 0;
                        motorRight.Direction = 1;
                    }
                    else if (x > 0.15)
                    {
                        // 右へ
                        motorLeft.Direction = 1;
                        motorRight.Direction = 0;
                    }
                    else
                    {
                        // 停止
                        motorLeft.Direction = 0;
                        motorRight.Direction = 0;
                    }
                }
            });
        }
Ejemplo n.º 35
0
 void recordAccessControlPoint_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     this.IRecordAccessControlPointCharacteristic.ProcessData(args.CharacteristicValue);
 }
Ejemplo n.º 36
0
        // Barometric Pressure change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Barometric_Pressure_Sensor_2
        async void pressureChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            UInt16 c3 = (UInt16)(((UInt16)baroCalibrationData[5] << 8) + (UInt16)baroCalibrationData[4]);
            UInt16 c4 = (UInt16)(((UInt16)baroCalibrationData[7] << 8) + (UInt16)baroCalibrationData[6]);
            Int16 c5 = (Int16)(((UInt16)baroCalibrationData[9] << 8) + (UInt16)baroCalibrationData[8]);
            Int16 c6 = (Int16)(((UInt16)baroCalibrationData[11] << 8) + (UInt16)baroCalibrationData[10]);
            Int16 c7 = (Int16)(((UInt16)baroCalibrationData[13] << 8) + (UInt16)baroCalibrationData[12]);
            Int16 c8 = (Int16)(((UInt16)baroCalibrationData[15] << 8) + (UInt16)baroCalibrationData[14]);

            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            Int64 s, o, p, val;
            UInt16 Pr = (UInt16)(((UInt16)bArray[3] << 8) + (UInt16)bArray[2]);
            Int16 Tr = (Int16)(((UInt16)bArray[1] << 8) + (UInt16)bArray[0]);

            // Sensitivity
            s = (Int64)c3;
            val = (Int64)c4 * Tr;
            s += (val >> 17);
            val = (Int64)c5 * Tr * Tr;
            s += (val >> 34);

            // Offset
            o = (Int64)c6 << 14;
            val = (Int64)c7 * Tr;
            o += (val >> 3);
            val = (Int64)c8 * Tr * Tr;
            o += (val >> 19);

            // Pressure (Pa)
            p = ((Int64)(s * Pr) + o) >> 14;
            double pres = (double)p / 100;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                BaroOut.Text = pres.ToString();
            });
        }
Ejemplo n.º 37
0
 private async void _notifyCommandCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     if (DateTime.Now - _lastButtonReceived < TimeSpan.FromSeconds(5))
     {
         return; // ignore
     }
     _lastButtonReceived = DateTime.Now;
     try{
         if (args?.CharacteristicValue?.Length > 0)
         {
             byte[] bytes = new byte[args.CharacteristicValue.Length];
             DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(bytes);
             var str = BitConverter.ToString(bytes);
             Debug.WriteLine($"*** BUTTON *** {str}");
             if (SensorKit.Settings.IsExperimentOn)
             {
                 Controller.Stop();
             }
             else
             {
                 if (SensorKit.Settings.IsTrackingOn)
                 {
                     Controller.Start();
                 }
                 else
                 {
                     Debug.WriteLine($"Please, enable tracking first");
                 }
             }
         }
     }catch (Exception x) {
         Debug.WriteLine(x);
     }
 }
Ejemplo n.º 38
0
        // Key press change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Simple_Key_Service
        async void keyChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            byte data = bArray[0];

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                if((data & 0x01) == 0x01)
                    KeyROut.Background = new SolidColorBrush(Colors.Green);
                else
                    KeyROut.Background = new SolidColorBrush(Colors.Red);

                if ((data & 0x02) == 0x02)
                    KeyLOut.Background = new SolidColorBrush(Colors.Green);
                else
                    KeyLOut.Background = new SolidColorBrush(Colors.Red);
            });
        }
Ejemplo n.º 39
0
 private static void GattRx_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     Console.WriteLine(args.CharacteristicValue.ToString());
 }
Ejemplo n.º 40
0
        private async void DataSourceCharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var stream = args.CharacteristicValue.AsStream();
            var br = new BinaryReader(stream);

            var cmdId = br.ReadByte();
            var notUid = br.ReadUInt32();
            var attr1 = (NotificationAttribute)br.ReadByte();
            var attr1len = br.ReadUInt16();
            var attr1val = br.ReadChars(attr1len);
            var attr2 = (NotificationAttribute) br.ReadByte();
            var attr2len = br.ReadUInt16();
            var attr2val = br.ReadChars(attr2len);

            EventFlags? flags = null;

            if(FlagCache.ContainsKey(notUid))
            {
                flags = FlagCache[notUid];
            }

            var not = new PlainNotification()
            {
                EventFlags = flags,
                Uid = notUid,
                Title = new string(attr1val),
                Message = new string(attr2val)
            };

            OnNotification?.Invoke(not);
        }
Ejemplo n.º 41
0
 private async void eegNotification(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     var data = new byte[args.CharacteristicValue.Length];
     DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);
     System.Diagnostics.Debug.WriteLine(data[1]);
 }
		private void glucoseMeasurementNotification(GattCharacteristic sender, GattValueChangedEventArgs args)
		{
			var measurementObject = (GlucoseMeasurementValue)this.IGlucoseMeasurementCharacteristic.ProcessData(args.CharacteristicValue);
			if (MeasurementNotification != null)
				MeasurementNotification(measurementObject);
		}
Ejemplo n.º 43
0
 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
 {
     SomethingChanged?.Invoke(sender,args);
 }
        // Handle the recieved data from the notification event.
        void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            string result = string.Empty;
            const byte HEART_RATE_VALUE_FORMAT = 0x01;

            var data = new byte[args.CharacteristicValue.Length];
            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);

            ushort heartRate;

            if (data.Length >= 2)
            {
                byte flags = data[0];
                bool isHeartRateValueSizeLong = ((flags & HEART_RATE_VALUE_FORMAT) != 0);

                int currentOffset = 1;

                if (isHeartRateValueSizeLong)
                {
                    heartRate = (ushort)((data[currentOffset + 1] << 8) + data[currentOffset]);
                    currentOffset += 2;
                }
                else
                {
                    heartRate = data[currentOffset];
                    currentOffset++;
                }

                result =string.Format("{0} bpm", heartRate);
            }

            this.ReturnResult(result);
        }
Ejemplo n.º 45
0
        private async void eegNotification(GattCharacteristic sender, GattValueChangedEventArgs args)
        {

        }
		private void batterLevelCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
		{
			try
			{
				BatteryLevelCharacteristics result;
				var batteryLevelData = new byte[args.CharacteristicValue.Length];
				DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(batteryLevelData);
				result = BatteryLevelCharacteristicsHandler.ProcessDataBatteryLevel(batteryLevelData);
				if(ValueChangeCompleted != null)
				{
					ValueChangeCompleted(result);
				}
			}
			catch (Exception ex)
			{
				var error = ex.StackTrace;
			}
		}
Ejemplo n.º 47
0
        // Accelerometer change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Accelerometer_2
        async void accelChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);

            double x = (SByte)bArray[0] / 64.0;
            double y = (SByte)bArray[1] / 64.0;
            double z = (SByte)bArray[2] / 64.0 * -1;

            tempAccelerometerX = x;
            tempAccelerometerY = y;
            tempAccelerometerZ = z;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                RecTranslateTransform.X = x * 90;
                RecTranslateTransform.Y = y * -90;

                AccelXOut.Text = "X: " + x.ToString();
                AccelYOut.Text = "Y: " + y.ToString();
                AccelZOut.Text = "Z: " + z.ToString();
            });
        }
 public void characteristics_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs EventArgs)
 {
     string base64String = null;
     string JsonString=null;
     byte[] forceData = new byte[EventArgs.CharacteristicValue.Length];
     DataReader.FromBuffer(EventArgs.CharacteristicValue).ReadBytes(forceData);
     Thread.Sleep(waiting_time);
     base64String = System.Convert.ToBase64String(forceData, 0, forceData.Length);
     //currentDeviceCharacteristic[NotifyCharaIndex].Value = currentDeviceCharacteristic[NotifyCharaIndex].Value + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length);
     //JsonString = "\"" + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length)+ "\"";
     JsonString = "\"" + base64String + "\"";
     //JsonString = Regex.Replace(JsonString, "\n", "\\n");
     //JsonString = Regex.Replace(JsonString, "\r", "\\r");
     PluginResult result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"subscribedResult\",\"value\":" + JsonString + "}");
     result.KeepCallback = true;
     DispatchCommandResult(result, callbackId_sub);
 }
Ejemplo n.º 49
0
        private async void dataCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            var data = new byte[args
                                .CharacteristicValue.Length];

            DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);


            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                NotifyAboutChanges(data);
            });
        }