WriteByte() public method

public WriteByte ( byte value ) : void
value byte
return void
コード例 #1
0
        //private uint sizeOfPixel = 4;
        private async void createTile(IRandomAccessStream tileStream, Color color)
        {
            // Create the data writer object backed by the in-memory stream.
            using (var dataWriter = new Windows.Storage.Streams.DataWriter(tileStream))
            {
                for (uint y = 0; y < sizeOfMapTile; y++)
                {
                    for (uint x = 0; x < sizeOfMapTile; x++)
                    {
                        // RGBA
                        dataWriter.WriteByte(color.R);
                        dataWriter.WriteByte(color.G);
                        dataWriter.WriteByte(color.B);
                        dataWriter.WriteByte(color.A);
                    }
                }

                // Send the contents of the writer to the backing stream.
                await dataWriter.StoreAsync();

                // For the in-memory stream implementation we are using, the flushAsync call
                // is superfluous,but other types of streams may require it.
                await dataWriter.FlushAsync();

                // In order to prolong the lifetime of the stream, detach it from the
                // DataWriter so that it will not be closed when Dispose() is called on
                // dataWriter. Were we to fail to detach the stream, the call to
                // dataWriter.Dispose() would close the underlying stream, preventing
                // its subsequent use by the DataReader below.
                dataWriter.DetachStream();
            }
        }
コード例 #2
0
        /// <summary>
        /// Extension method to SmartCardConnection class to perform a transparent exchange to the ICC
        /// </summary>
        /// <param name="connection">
        /// SmartCardConnection object
        /// </param>
        /// <param name="commandData">
        /// Command object to send to the ICC
        /// </param>
        /// <returns>Response received from the ICC</returns>
        public static async Task<byte[]> TransparentExchangeAsync(this SmartCardConnection connection, byte[] commandData)
        {
            byte[] responseData = null;
            ManageSessionResponse apduRes = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.StartTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes.Succeeded)
            {
                throw new Exception("Failure to start transparent session, " + apduRes.ToString());
            }

            using (DataWriter dataWriter = new DataWriter())
            {
                dataWriter.WriteByte((byte)TransparentExchange.DataObjectType.Transceive);
                dataWriter.WriteByte((byte)commandData.Length);
                dataWriter.WriteBytes(commandData);

                TransparentExchangeResponse apduRes1 = await TransceiveAsync(connection, new TransparentExchange(dataWriter.DetachBuffer().ToArray())) as TransparentExchangeResponse;

                if (!apduRes1.Succeeded)
                {
                    throw new Exception("Failure transceive with card, " + apduRes1.ToString());
                }

                responseData = apduRes1.IccResponse;
            }

            ManageSessionResponse apduRes2 = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.EndTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes2.Succeeded)
            {
                throw new Exception("Failure to end transparent session, " + apduRes2.ToString());
            }

            return responseData;
        }
コード例 #3
0
        private static byte[] GetDataIn(byte serviceCount, byte[] serviceCodeList, byte blockCount, byte[] blockList)
        {
            DataWriter dataWriter = new DataWriter();

            dataWriter.WriteByte(serviceCount);
            dataWriter.WriteBytes(serviceCodeList);
            dataWriter.WriteByte(blockCount);
            dataWriter.WriteBytes(blockList);

            return dataWriter.DetachBuffer().ToArray();
        }
コード例 #4
0
ファイル: CommandWorker.cs プロジェクト: Eggies/SDK
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            try
            {
                // Connect to the Drone
                udpClient = new DatagramSocket();
                await udpClient.BindServiceNameAsync(_ServiceName);
                await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                udpWriter = new DataWriter(udpClient.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();

                _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
                _Started = true;
            }
            catch (Exception)
            {
                Stop();
            }
        }
コード例 #5
0
        async Task<bool> onewireReset(string deviceId)
        {
            try
            {
                if (serialPort != null)
                    serialPort.Dispose();

                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 9600;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;

                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataWriteObject.WriteByte(0xF0);
                await dataWriteObject.StoreAsync();

                dataReaderObject = new DataReader(serialPort.InputStream);
                await dataReaderObject.LoadAsync(1);
                byte resp = dataReaderObject.ReadByte();
                if (resp == 0xFF)
                {
                    System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                    return false;
                }
                else if (resp == 0xF0)
                {
                    System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                    return false;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Response: " + resp);
                    serialPort.Dispose();
                    serialPort = await SerialDevice.FromIdAsync(deviceId);

                    // Configure serial settings
                    serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.BaudRate = 115200;
                    serialPort.Parity = SerialParity.None;
                    serialPort.StopBits = SerialStopBitCount.One;
                    serialPort.DataBits = 8;
                    serialPort.Handshake = SerialHandshake.None;
                    dataWriteObject = new DataWriter(serialPort.OutputStream);
                    dataReaderObject = new DataReader(serialPort.InputStream);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
                return false;
            }
        }
コード例 #6
0
        // ---------------------------------------------------
        //     Hardware Configuration Helper Functions
        // ---------------------------------------------------

        // Retrieve Barometer Calibration data
        private async void calibrateBarometer()
        {
            GattDeviceService gattService = serviceList[BAROMETRIC_PRESSURE];

            if (gattService != null)
            {
                // Set Barometer configuration to 2, so that calibration data is saved
                var characteristicList = gattService.GetCharacteristics(new Guid("F000AA42-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteByte((Byte)0x02);
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }

                // Save Barometer calibration data
                characteristicList = gattService.GetCharacteristics(new Guid("F000AA43-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached);
                    baroCalibrationData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData);
                }
            }
        }
コード例 #7
0
ファイル: MainPage.xaml.cs プロジェクト: bfjelds/samples
        // ---------------------------------------------------
        //     Hardware Configuration Helper Functions
        // ---------------------------------------------------

        // Retrieve Barometer Calibration data
        private async void calibrateBarometer()
        {
            GattDeviceService service;

            if (_serviceList.TryGetValue(BAROMETRIC_PRESSURE, out service))
            {
                // Set Barometer configuration to 2, so that calibration data is saved
                var characteristicList = service.GetCharacteristics(BAROMETER_CONFIGURATION_GUID);
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteByte((Byte)0x02);
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }

                // Save Barometer calibration data
                characteristicList = service.GetCharacteristics(BAROMETER_CALIBRATION_GUID);
                if (characteristicList != null)
                {
                    GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached);
                    baroCalibrationData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData);
                }
            }
        }
コード例 #8
0
            public static async void SetSensorPeriod(SensorChars sensorCharacteristics, int period)
            {
                SensorServicesCls.SensorIndexes SensorIndex = sensorCharacteristics.Sensor_Index;
                Debug.WriteLine("Begin SetSensorPeriod(): " + SensorIndex.ToString());


                try
                {
                    if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Period))
                    {
                        GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Period];
                        {
                            if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                            {
                                var writer = new Windows.Storage.Streams.DataWriter();
                                // Accelerometer period = [Input * 10]ms
                                writer.WriteByte((Byte)(period / 10));
                                await characteristic.WriteValueAsync(writer.DetachBuffer());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: SetSensorPeriod(): " + SensorIndex.ToString() + " " + ex.Message);
                }
                Debug.WriteLine("End SetSensorPeriod(): " + SensorIndex.ToString());
            }
コード例 #9
0
        /// <summary>
        /// Creates the SDP record that will be revealed to the Client device when pairing occurs.  
        /// </summary>
        /// <param name="rfcommProvider">The RfcommServiceProvider that is being used to initialize the server</param>
        private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider)
        {
            var sdpWriter = new DataWriter();

            // Write the Service Name Attribute.
            sdpWriter.WriteByte(Constants.SdpServiceNameAttributeType);

            // The length of the UTF-8 encoded Service Name SDP Attribute.
            sdpWriter.WriteByte((byte)Constants.SdpServiceName.Length);

            // The UTF-8 encoded Service Name value.
            sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sdpWriter.WriteString(Constants.SdpServiceName);

            // Set the SDP Attribute on the RFCOMM Service Provider.
            rfcommProvider.SdpRawAttributes.Add(Constants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer());
        }
コード例 #10
0
        public HidOutputReport GetFilledReport()
        {
            var dataWriter = new DataWriter();
            dataWriter.WriteByte(Id);
            dataWriter.WriteBytes(Data.Array);
            report.Data = dataWriter.DetachBuffer();

            return report;
        }
コード例 #11
0
ファイル: UdpClient.cs プロジェクト: pisker/mDNS
        public async Task Send(byte[] data, int length, IPEndPoint iPEndPoint)
        {
            var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(iPEndPoint.Address.ToString()), iPEndPoint.Port.ToString());

            DataWriter writer = new DataWriter(stream);
            for (int i = 0; i < length; i++)
                writer.WriteByte(data[i]);
      
            await writer.StoreAsync();
        }
コード例 #12
0
        private async void cutTile(IRandomAccessStream stream, int pixeloffsetX, int pixeloffsetY, int levelOfDetail)
        {
            // Create the data writer object backed by the in-memory stream.
            using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
            {
                //dataWriter.dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                for (int y = 0; y < sizeOfMapTile; y++)
                {
                    for (int x = 0; x < sizeOfMapTile; x++)
                    {
                        double lat, lon = 0.0;

                        Microsoft.MapPoint.TileSystem.PixelXYToLatLong(pixeloffsetX + x, pixeloffsetY + y, levelOfDetail, out lat, out lon);
                        BasicGeoposition point = new BasicGeoposition {
                            Latitude = lat, Longitude = lon
                        };

                        if (PathCache.pointInPolygon(point.Longitude, point.Latitude))
                        {
                            // RGBA
                            dataWriter.WriteByte(ColorIn.R);
                            dataWriter.WriteByte(ColorIn.G);
                            dataWriter.WriteByte(ColorIn.B);
                            dataWriter.WriteByte(ColorIn.A);
                        }
                        else
                        {
                            // RGBA
                            dataWriter.WriteByte(ColorOut.R);
                            dataWriter.WriteByte(ColorOut.G);
                            dataWriter.WriteByte(ColorOut.B);
                            dataWriter.WriteByte(ColorOut.A);
                        }
                    }
                }

                // Send the contents of the writer to the backing stream.
                await dataWriter.StoreAsync();

                // For the in-memory stream implementation we are using, the flushAsync call
                // is superfluous,but other types of streams may require it.
                await dataWriter.FlushAsync();

                // In order to prolong the lifetime of the stream, detach it from the
                // DataWriter so that it will not be closed when Dispose() is called on
                // dataWriter. Were we to fail to detach the stream, the call to
                // dataWriter.Dispose() would close the underlying stream, preventing
                // its subsequent use by the DataReader below.
                dataWriter.DetachStream();
            }
        }
コード例 #13
0
        void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(MINIMUM_SERVICE_VERSION);

            IBuffer data = writer.DetachBuffer();

            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
コード例 #14
0
ファイル: ParrotSendData.cs プロジェクト: modulexcite/events
        public async void SendMotorCommand(Boolean on, int tilt, int forward, int turn, int up, float scale)
        {
            var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors);
            var characteristic = characteristics[0];
            var writer = new DataWriter();
            try
            {
                writer.WriteByte(2);
                writer.WriteByte((byte)_motorCounter);
                writer.WriteByte(2);
                writer.WriteByte(0);
                writer.WriteByte(2);
                writer.WriteByte(0);
                if (on)
                {
                    writer.WriteByte(1);
                }
                else
                {
                    writer.WriteByte(0);
                }
                // is byte casting necessary???
                writer.WriteByte((byte)(tilt & 0xFF));
                writer.WriteByte((byte)(forward & 0xFF));
                writer.WriteByte((byte)(turn & 0xFF));
                writer.WriteByte((byte)(up & 0xFF));
                //writer.WriteDouble(scale); // well, but I need different endian :(

                await characteristic.WriteValueAsync(writer.DetachBuffer());
            }
            catch (IOException e)
            {
                Debug.WriteLine(e);
            }

            //var gattTransaction = new GattReliableWriteTransaction();
            //gattTransaction.WriteValue(characteristic, writer.DetachBuffer());
            //var status = await gattTransaction.CommitAsync();
            //switch (status)
            //{
            //    case GattCommunicationStatus.Success:
            //        AddLogAction("Writing to your device OK !");
            //        break;
            //    case GattCommunicationStatus.Unreachable:
            //        AddLogAction("Writing to your device Failed !");
            //        break;
            //}

        }
コード例 #15
0
ファイル: BarometerSensor.cs プロジェクト: JMLIT/WP8Meteo
        public override async System.Threading.Tasks.Task<SensorBase.InitResult> Init()
        {
            var r = await base.Init();

            if (r == InitResult.Ok)
            {
                // Lecture des données de calibration

                GattCommunicationStatus s;

                using (var writer = new DataWriter())
                {
                    writer.WriteByte(2);
                    s = await pConfigurationCharacteristic.WriteValueAsync(writer.DetachBuffer());
                }

                if (s == GattCommunicationStatus.Success)
                {
                    var calib = GetCharacteristic(pDeviceService, BAROMETER_CALIBRATION_UUID);

                    if (calib != null)
                    {
                        var result = await calib.ReadValueAsync(BluetoothCacheMode.Uncached);

                        if (result.Status == GattCommunicationStatus.Success && result.Value.Length == 16)
                        {
                            byte[] b = new byte[16];
                            DataReader wReader = DataReader.FromBuffer(result.Value);

                            using (wReader)
                            {
                                wReader.ReadBytes(b);

                            }

                            pBarometerCalibrationData[0] = BitConverter.ToUInt16(b, 0);
                            pBarometerCalibrationData[1] = BitConverter.ToUInt16(b, 2);
                            pBarometerCalibrationData[2] = BitConverter.ToUInt16(b, 4);
                            pBarometerCalibrationData[3] = BitConverter.ToUInt16(b, 6);
                            pBarometerCalibrationData[4] = BitConverter.ToInt16(b, 8);
                            pBarometerCalibrationData[5] = BitConverter.ToInt16(b, 10);
                            pBarometerCalibrationData[6] = BitConverter.ToInt16(b, 12);
                            pBarometerCalibrationData[7] = BitConverter.ToInt16(b, 14);
                        }
                    }
                }
            }

            return r;
        }
コード例 #16
0
        /// <summary>
        /// Packs the current command into contiguous buffer bytes
        /// </summary>
        /// <returns>
        /// buffer holds the current wire/air format of the command
        /// </returns>
        public IBuffer GetBuffer()
        {
            using (DataWriter writer = new DataWriter())
            {
                writer.WriteByte(CLA);
                writer.WriteByte(INS);
                writer.WriteByte(P1);
                writer.WriteByte(P2);

                if (CommandData != null && CommandData.Length > 0)
                {
                    writer.WriteByte((byte)CommandData.Length);
                    writer.WriteBytes(CommandData);
                }

                if (Le != null)
                {
                    writer.WriteByte((byte)Le);
                }

                return writer.DetachBuffer();
            }
        }
コード例 #17
0
ファイル: TCP.cs プロジェクト: cyberh0me/IoT
        public async void Reboot(string HostName)
        {
            HostName remoteHostName = new HostName(HostName);

            using (StreamSocket socket = new StreamSocket())
            {
                socket.Control.KeepAlive = false;
                await socket.ConnectAsync(remoteHostName, "6");

                using (DataWriter writer = new DataWriter(socket.OutputStream))
                {
                    // set payload length
                    writer.ByteOrder = ByteOrder.LittleEndian;
                    writer.WriteUInt32(2);
                    // set payload type
                    writer.WriteByte((byte)PayloadType.Byte);
                    // set payload
                    writer.WriteByte(0x01);
                    // transmit
                    await writer.StoreAsync();
                    writer.DetachStream();
                }
            }
        }
コード例 #18
0
            public static async Task TurnOnSensor(SensorChars sensorCharacteristics)
            {
                SensorServicesCls.SensorIndexes sensor = sensorCharacteristics.Sensor_Index;
                Debug.WriteLine("Begin turn on sensor: " + sensor.ToString());
                // Turn on sensor
                try
                {
                    if (sensor >= 0 && sensor != SensorServicesCls.SensorIndexes.KEYS && sensor != SensorServicesCls.SensorIndexes.IO_SENSOR && sensor != SensorServicesCls.SensorIndexes.REGISTERS)
                    {
                        if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Enable))
                        {
                            GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Enable];
                            if (characteristic != null)
                            {
                                if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                                {
                                    var writer = new Windows.Storage.Streams.DataWriter();
                                    if (sensor == SensorServicesCls.SensorIndexes.MOVEMENT)
                                    {
                                        byte[] bytes = new byte[] { 0x7f, 0x00 };
                                        writer.WriteBytes(bytes);
                                    }
                                    else
                                    {
                                        writer.WriteByte((Byte)0x01);
                                    }

                                    var status = await characteristic.WriteValueAsync(writer.DetachBuffer());
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    //IncProgressCounter();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: TurnOnSensor() : " + sensor.ToString() + " " + ex.Message);
                }

                Debug.WriteLine("End turn on sensor: " + sensor.ToString());
            }
コード例 #19
0
 private async Task SendDataAync(byte data)
 {
     try
     {
         var ip = ApplicationData.Current.LocalSettings.Values["address"].ToString();
         using (chatSocket = new StreamSocket())
         {
             await chatSocket.ConnectAsync(new HostName(ip), "5000");
             var stream = chatSocket.OutputStream;
             chatWriter = new DataWriter(stream);
             chatWriter.WriteByte(data);
             await chatWriter.StoreAsync();
         }
     }
     catch (Exception ex)
     {
         var dialog = new MessageDialog(ex.Message);
         await dialog.ShowAsync();
     }
 }
コード例 #20
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            // Find all paired instances of the Rfcomm chat service
            try {

                using (chatSocket = new StreamSocket())
                {
                    await chatSocket.ConnectAsync(new HostName(textBoxIp.Text), "5000");
                    var stream = chatSocket.OutputStream;
                    chatWriter = new DataWriter(stream);
                    chatWriter.WriteByte(1);
                    await chatWriter.StoreAsync();
                }
                              
            }catch(Exception ex)
            {
                var dialog = new MessageDialog(ex.Message);
                await dialog.ShowAsync();
            }
        }
コード例 #21
0
        public async void setSensorPeriod(int period)
        {
            GattDeviceService gattService = GattService;

            if (SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && gattService != null)
            {
                var characteristicList = gattService.GetCharacteristics(new Guid(UUIDBase[(int)SensorIndex] + SENSOR_PERIOD_GUID_SUFFFIX));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        // Accelerometer period = [Input * 10]ms
                        writer.WriteByte((Byte)(period / 10));
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }
            }
        }
コード例 #22
0
        // Set sensor update period
        private async void setSensorPeriod(int sensor, int period)
        {
            GattDeviceService gattService = serviceList[sensor];

            if (sensor != KEYS && gattService != null)
            {
                var characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_PERIOD_GUID_SUFFFIX));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        // Accelerometer period = [Input * 10]ms
                        writer.WriteByte((Byte)(period / 10));
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }
            }
        }
コード例 #23
0
ファイル: TCP.cs プロジェクト: cyberh0me/IoT
        public async void WriteString(string HostName, string Message)
        {
            HostName remoteHostName = new HostName(HostName);

            using (StreamSocket socket = new StreamSocket())
            {
                socket.Control.KeepAlive = false;
                await socket.ConnectAsync(remoteHostName, "6");

                using (DataWriter writer = new DataWriter(socket.OutputStream))
                {
                    // set payload length
                    writer.ByteOrder = ByteOrder.LittleEndian;
                    writer.WriteUInt32(writer.MeasureString(Message));
                    // set payload type
                    writer.WriteByte((byte)PayloadType.String);
                    // set payload
                    writer.WriteString(Message);
                    // transmit
                    await writer.StoreAsync();
                    writer.DetachStream();
                }

                using (DataReader reader = new DataReader(socket.InputStream))
                {
                    int length;
                    string response;
                    // receive payload length
                    reader.ByteOrder = ByteOrder.LittleEndian;
                    await reader.LoadAsync(4);
                    length = reader.ReadInt32();
                    // receive payload
                    await reader.LoadAsync((uint)length);
                    response = reader.ReadString((uint)length);

                    Debug.WriteLine(string.Format("response: {0}", response));
                    reader.DetachStream();
                }
            }
        }
コード例 #24
0
        void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            try
            {
                var writer = new Windows.Storage.Streams.DataWriter();

                // First write the attribute type
                writer.WriteByte(Constants.SERVICE_VERSION_ATTRIBUTE_TYPE);
                // Then write the data
                writer.WriteUInt32(Constants.SERVICE_VERSION);

                var data = writer.DetachBuffer();
                provider.SdpRawAttributes.Add(Constants.SERVICE_VERSION_ATTRIBUTE_ID, data);
                //Check attributes
                try
                {
                    var attributes = provider.SdpRawAttributes;
                    // BluetoothCacheMode.Uncached);
                    var attribute = attributes[Constants.SERVICE_VERSION_ATTRIBUTE_ID];
                    var reader    = DataReader.FromBuffer(attribute);

                    // The first byte contains the attribute' s type
                    byte attributeType = reader.ReadByte();
                    if (attributeType == Constants.SERVICE_VERSION_ATTRIBUTE_TYPE)
                    {
                        // The remainder is the data
                        uint version = reader.ReadUInt32();
                        bool ret     = (version >= Constants.MINIMUM_SERVICE_VERSION);
                    }
                }
                catch (Exception ex)
                {
                    PostMessage("OBEX_Recv.InitializeServiceSdpAttributes_Check", ex.Message);
                }
            }
            catch (Exception ex)
            {
                PostMessage("OBEX_Receiver.InitializeServiceSdpAttributes", ex.Message);
            }
        }
コード例 #25
0
ファイル: CommandWorker.cs プロジェクト: napolini/SDK
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            // Connect To Drone
            udpClient = new DatagramSocket();
            await udpClient.BindServiceNameAsync(_ServiceName);
            await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
            udpWriter = new DataWriter(udpClient.OutputStream);

            //string path = string.Format("AR.Drone-CommandHistory_{0:yyyy-MM-dd-HH-mm}.txt", DateTime.Now);
            //commandHistoryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
            // Write first message
            //byte[] firstMessage = BitConverter.GetBytes(1);
            //WriteString(firstMessage.ToString());

            udpWriter.WriteByte(1);
            await udpWriter.StoreAsync();

            _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
            _Started = true;
        }
コード例 #26
0
ファイル: ParrotSendData.cs プロジェクト: modulexcite/events
        public async Task<bool> SendMotorCommand(bool @on, int tilt, int forward, int turn, int up, float scale, IReadOnlyList<GattCharacteristic> characteristics)
        {
            var res = false;
            var characteristic = characteristics[0];
            try
            {
                Debug.WriteLine("    Send Motor Command");
                Debug.WriteLine("    Try to write to " + CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid));
                Debug.WriteLine("    Char props" + characteristic.CharacteristicProperties);

                var writer = new DataWriter();
                writer.WriteByte(2);
                writer.WriteByte((byte)_motorCounter);
                writer.WriteByte(2);
                writer.WriteByte(0);
                writer.WriteByte(2);
                writer.WriteByte(0);
                if (on)
                {
                    writer.WriteByte(1);
                }
                else
                {
                    writer.WriteByte(0);
                }
                // is byte casting necessary???
                writer.WriteByte((byte)(tilt & 0xFF));
                writer.WriteByte((byte)(forward & 0xFF));
                writer.WriteByte((byte)(turn & 0xFF));
                writer.WriteByte((byte)(up & 0xFF));
                writer.WriteDouble(scale); // well, but I need different endian :(

                await characteristic.WriteValueAsync(writer.DetachBuffer());
                Debug.WriteLine("      Write sucessfull");
                res = true;
            }
            catch (Exception exception)
            {
                Debug.WriteLine("      Write error");
            }
            return res;
        }
コード例 #27
0
        private async Task enableSensor(int sensor)
        {
            Debug.WriteLine("Begin enable sensor: " + sensor.ToString());
            GattDeviceService gattService = serviceList[sensor];

            if (gattService != null)
            {
                // Turn on notifications
                IReadOnlyList <GattCharacteristic> characteristicList;
                if (sensor >= 0 && sensor <= 2)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX));
                }
                else
                {
                    characteristicList = gattService.GetCharacteristics(LUXOMETER_CONFIGURATION_GUID);
                }

                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        switch (sensor)
                        {
                        case (IR_SENSOR):
                            characteristic.ValueChanged += tempChanged;
                            break;

                        case (HUMIDITY):
                            characteristic.ValueChanged += humidChanged;
                            break;

                        case (LUXOMETER):
                            characteristic.ValueChanged += luxChanged;
                            //BaroTitle.Foreground = new SolidColorBrush(Colors.Green);
                            break;

                        default:
                            break;
                        }

                        // Save a reference to each active characteristic, so that handlers do not get prematurely killed
                        activeCharacteristics[sensor] = characteristic;

                        // Set the notify enable flag
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }

                // Turn on sensor
                if (sensor >= 0 && sensor <= 7)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX));
                    if (characteristicList != null)
                    {
                        GattCharacteristic characteristic = characteristicList[0];
                        if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            // Special value for Gyroscope to enable all 3 axes
                            writer.WriteByte((Byte)0x01);

                            await characteristic.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }
            }
            Debug.WriteLine("End enable sensor: " + sensor.ToString());
        }
コード例 #28
0
        private async void OnPerformAction()
        {
            var stream = socket.OutputStream;
            using (var writer = new DataWriter(stream))
            {
                writer.ByteOrder = ByteOrder.LittleEndian;
                //writer.WriteInt16(6);
                //writer.WriteByte(0x00);
                //writer.WriteByte(3);
                //writer.WriteUInt16(1500);
                //writer.WriteUInt16(1000);

                //var bytes = new byte[] { 6, 0, 0, 3, 220, 5, 232, 3 };
                //writer.WriteBytes(bytes);

                writer.WriteInt16(12);
                writer.WriteByte(Byte0);
                writer.WriteByte(Byte1);
                writer.WriteByte(Byte2);
                writer.WriteByte(Byte3);
                writer.WriteByte(Byte4);
                writer.WriteByte(Byte5);
                writer.WriteByte(Byte6);
                writer.WriteByte(Byte7);
                writer.WriteUInt32(FourBytes);

                await writer.StoreAsync();
                writer.DetachStream();
            }
            using (var reader = new DataReader(socket.InputStream))
            {
                reader.ByteOrder = ByteOrder.LittleEndian;
                await reader.LoadAsync(5);
                var length = reader.ReadUInt16();
                var byte1 = reader.ReadByte();
                var byte2 = reader.ReadByte();
                var status = reader.ReadByte();

                reader.DetachStream();
            }
        }
コード例 #29
0
ファイル: TourTheStairs.cs プロジェクト: modulexcite/events
        public async Task<bool> SendMotorCmd(bool on, int tilt, int forward, int turn, int up, float scale)
        {
            var packet = new DataWriter();
            try
            {
                packet.WriteByte(2);
                packet.WriteByte((byte)_motorCounter);
                packet.WriteByte(2);
                packet.WriteByte(0);
                packet.WriteByte(2);
                packet.WriteByte(0);
                if (on)
                {
                    packet.WriteByte(1);
                }
                else
                {
                    packet.WriteByte(0);
                }
                // is byte casting necessary???
                packet.WriteByte((byte)(tilt & 0xFF));
                packet.WriteByte((byte)(forward & 0xFF));
                packet.WriteByte((byte)(turn & 0xFF));
                packet.WriteByte((byte)(up & 0xFF));
                packet.WriteDouble(scale); // well, but I need different endian :(
                                           //byte[] tmpArr = stream.toByteArray();
                                           //byte tmp;
                                           //tmp = tmpArr[11]; // temporary hack - swapping float ordering
                                           //tmpArr[11] = tmpArr[14];
                                           //tmpArr[14] = tmp;
                                           //tmp = tmpArr[12];
                                           //tmpArr[12] = tmpArr[13];
                                           //tmpArr[13] = tmp;
                                           //characteristics.setValue(tmpArr);
                await _motorChar.WriteValueAsync(packet.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
            }
            catch (Exception exception)
            {
                AddException(exception);
            }

            await Sleep(50);
            _motorCounter++;
            return true;
        }
コード例 #30
0
ファイル: Scenario3.xaml.cs プロジェクト: mbin/Win81App
        private async void WriteCharacteristicValue_Click(object sender, RoutedEventArgs args)
        {
            WriteCharacteristicValueButton.IsEnabled = false;
            try
            {
                var heartRateControlPointCharacteristic = HeartRateService.Instance.Service.GetCharacteristics(
                    GattCharacteristicUuids.HeartRateControlPoint)[0];
                 
                DataWriter writer = new DataWriter();
                writer.WriteByte(1);

                GattCommunicationStatus status = await heartRateControlPointCharacteristic.WriteValueAsync(
                    writer.DetachBuffer());

                if (status == GattCommunicationStatus.Success)
                {
                    rootPage.NotifyUser("Expended Energy successfully reset.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Your device is unreachable, most likely the device is out of range, " +
                        "or is running low on battery, please make sure your device is working and try again.",
                        NotifyType.StatusMessage);
                }
            }
            catch (Exception e)
            {
                rootPage.NotifyUser("Error: " + e.Message, NotifyType.ErrorMessage);
            }
            WriteCharacteristicValueButton.IsEnabled = true;
        }
        /// <summary>
        /// Uses an output report to write data to the device so that it can be read back using input report.
        /// 
        /// Please note that when we create an OutputReport, all data is nulled out in the report. Since we will only be modifying 
        /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
        /// all bits are zeroed out except for the bits we care about).
        /// 
        /// We will modify the data buffer directly. See GetBooleanInputReportAsync for how to use controls.
        ///
        /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled 
        /// at the end of the task chain.
        /// </summary>
        /// <param name="bitValue"></param>
        /// <param name="buttonNumber">Button to change value of (1-4)</param>
        /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
        private async Task SendBooleanOutputReportAsync(Boolean bitValue, Byte buttonNumber)
        {
            var buttonIndex = buttonNumber - 1;

            var outputReport = EventHandlerForDevice.Current.Device.CreateOutputReport(SuperMutt.ReadWriteBufferControlInformation.ReportId);

            Byte byteToMask = (Byte)(bitValue ? 0xFF : 0x00);
            Byte dataByte = (Byte)(byteToMask & SuperMutt.ReadWriteBufferControlInformation.ButtonDataMask[buttonIndex]);

            var dataWriter = new DataWriter();

            // First byte is always the report id
            dataWriter.WriteByte((Byte)outputReport.Id);
            dataWriter.WriteByte(dataByte);

            outputReport.Data = dataWriter.DetachBuffer();

            UInt32 bytesWritten = await EventHandlerForDevice.Current.Device.SendOutputReportAsync(outputReport);

            var valueWritten = bitValue ? "1" : "0";
            rootPage.NotifyUser("Bit value written: " + valueWritten, NotifyType.StatusMessage);
        }
        /// <summary>
        /// Uses an output report to write data to the device so that it can be read back using input report.
        ///
        /// Please note that when we create an OutputReport, all data is nulled out in the report. Since we will only be modifying 
        /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
        /// all bits are zeroed out except for the bits we care about).
        ///
        /// We will modify the data buffer directly. See GetNumericInputReportAsync for how to use controls.
        ///
        /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled 
        /// at the end of the task chain.
        /// </summary>
        /// <param name="valueToWrite"></param>
        /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
        private async Task SendNumericOutputReportAsync(Byte valueToWrite)
        {
            var outputReport = EventHandlerForDevice.Current.Device.CreateOutputReport(SuperMutt.ReadWriteBufferControlInformation.ReportId);

            Byte dataByte = (Byte)(valueToWrite << SuperMutt.ReadWriteBufferControlInformation.VolumeDataStartBit);

            var dataWriter = new DataWriter();

            // First byte is always the report id
            dataWriter.WriteByte((Byte)outputReport.Id);
            dataWriter.WriteByte(dataByte);

            outputReport.Data = dataWriter.DetachBuffer();

            uint bytesWritten = await EventHandlerForDevice.Current.Device.SendOutputReportAsync(outputReport);

            rootPage.NotifyUser("Value written: " + valueToWrite, NotifyType.StatusMessage);
        }
コード例 #33
0
        // Enable and subscribe to specified GATT characteristic
        private async void enableSensor(int sensor)
        {
            GattDeviceService gattService = serviceList[sensor];
            if (gattService != null)
            {
                // Turn on notifications
                IReadOnlyList<GattCharacteristic> characteristicList;
                if (sensor >= 0 && sensor <= 5)
                    characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "1-0451-4000-B000-000000000000"));
                else
                    characteristicList = gattService.GetCharacteristics(new Guid("0000FFE1-0000-1000-8000-00805F9B34FB"));

                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];
                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        switch (sensor)
                        {
                            case (IR_SENSOR):
                                characteristic.ValueChanged += tempChanged;
                                IRTitle.Foreground = new SolidColorBrush(Colors.Green);
                                break;
                            case (ACCELEROMETER):
                                characteristic.ValueChanged += accelChanged;
                                AccelTitle.Foreground = new SolidColorBrush(Colors.Green);
                                setSensorPeriod(ACCELEROMETER, 250);
                                break;
                            case (HUMIDITY):
                                characteristic.ValueChanged += humidChanged;
                                HumidTitle.Foreground = new SolidColorBrush(Colors.Green);
                                break;
                            case (MAGNETOMETER):
                                characteristic.ValueChanged += magnoChanged;
                                MagnoTitle.Foreground = new SolidColorBrush(Colors.Green);
                                break;
                            case (BAROMETRIC_PRESSURE):
                                characteristic.ValueChanged += pressureChanged;
                                BaroTitle.Foreground = new SolidColorBrush(Colors.Green);
                                calibrateBarometer();
                                break;
                            case (GYROSCOPE):
                                characteristic.ValueChanged += gyroChanged;
                                GyroTitle.Foreground = new SolidColorBrush(Colors.Green);
                                break;
                            case (KEYS):
                                characteristic.ValueChanged += keyChanged;
                                KeyTitle.Foreground = new SolidColorBrush(Colors.Green);
                                break;
                            default:
                                break;
                        }

                        // Save a reference to each active characteristic, so that handlers do not get prematurely killed
                        activeCharacteristics[sensor] = characteristic;

                        // Set the notify enable flag
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }

                // Turn on sensor
                if (sensor >= 0 && sensor <= 5)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "2-0451-4000-B000-000000000000"));
                    if (characteristicList != null)
                    {
                        GattCharacteristic characteristic = characteristicList[0];
                        if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            // Special value for Gyroscope to enable all 3 axes
                            if (sensor == GYROSCOPE)
                                writer.WriteByte((Byte)0x07);
                            else
                                writer.WriteByte((Byte)0x01);

                            await characteristic.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }
            }
        }
コード例 #34
0
ファイル: Utils.cs プロジェクト: orenafek/AirHockey
        public static async void SendToServer(Command c,Frame current)
        {
            //while (!connected) { }
            try {
                writer = new DataWriter(socket.OutputStream);
                writer.WriteByte(Convert.ToByte((char)c));
                await writer.StoreAsync();
            } catch(Exception ex)
            {
                //MessageDialog msgDialog = new MessageDialog("The Connection Has Been Closed.");
                //UICommand OK = new UICommand("OK");
                //OK.Invoked += (IUICommand command) =>
                //{
                //    Server.Dispose(); current.Navigate(typeof(MainMenu), null);
                //};

                //Utils.Show(msgDialog, new List<UICommand> { OK });
            }
            
        }
コード例 #35
0
        // Enable and subscribe to specified GATT characteristic
        private async void enableSensor(int sensor)
        {
            GattDeviceService gattService = serviceList[sensor];

            if (gattService != null)
            {
                // Turn on notifications
                IReadOnlyList <GattCharacteristic> characteristicList;
                if (sensor >= 0 && sensor <= 5)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "1-0451-4000-B000-000000000000"));
                }
                else
                {
                    characteristicList = gattService.GetCharacteristics(new Guid("0000FFE1-0000-1000-8000-00805F9B34FB"));
                }

                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];
                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        switch (sensor)
                        {
                        /*
                         * case (IR_SENSOR):
                         *  characteristic.ValueChanged += tempChanged;
                         *  IRTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  break;
                         * case (ACCELEROMETER):
                         *  characteristic.ValueChanged += accelChanged;
                         *  AccelTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  setSensorPeriod(ACCELEROMETER, 250);
                         *  break;
                         * case (HUMIDITY):
                         *  characteristic.ValueChanged += humidChanged;
                         *  HumidTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  break;
                         * case (MAGNETOMETER):
                         *  characteristic.ValueChanged += magnoChanged;
                         *  MagnoTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  break;
                         * case (BAROMETRIC_PRESSURE):
                         *  characteristic.ValueChanged += pressureChanged;
                         *  BaroTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  calibrateBarometer();
                         *  break;
                         * case (GYROSCOPE):
                         *  characteristic.ValueChanged += gyroChanged;
                         *  GyroTitle.Foreground = new SolidColorBrush(Colors.Green);
                         *  break;
                         */
                        case (KEYS):
                            characteristic.ValueChanged += keyChanged;
                            // KeyTitle.Foreground = new SolidColorBrush(Colors.Green);
                            break;

                        default:
                            break;
                        }

                        // Save a reference to each active characteristic, so that handlers do not get prematurely killed
                        activeCharacteristics[sensor] = characteristic;

                        // Set the notify enable flag
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }

                // Turn on sensor
                if (sensor >= 0 && sensor <= 5)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "2-0451-4000-B000-000000000000"));
                    if (characteristicList != null)
                    {
                        GattCharacteristic characteristic = characteristicList[0];
                        if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            // Special value for Gyroscope to enable all 3 axes
                            if (sensor == GYROSCOPE)
                            {
                                writer.WriteByte((Byte)0x07);
                            }
                            else
                            {
                                writer.WriteByte((Byte)0x01);
                            }

                            await characteristic.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }
            }
        }
コード例 #36
0
    private async Task InitBrowseWpToWin()
    {
      provider = await RfcommServiceProvider.CreateAsync(
                       RfcommServiceId.FromUuid(rfcommServiceUuid));

      var listener = new StreamSocketListener();
      listener.ConnectionReceived += HandleConnectionReceived;

      await listener.BindServiceNameAsync(
        provider.ServiceId.AsString(),
        SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

      using (var writer = new DataWriter())
      {
        writer.WriteByte(ServiceVersionAttributeType);
        writer.WriteUInt32(ServiceVersion);

        var data = writer.DetachBuffer();
        provider.SdpRawAttributes.Add(ServiceVersionAttributeId, data);
        provider.StartAdvertising(listener);
      }
    }
コード例 #37
0
        /// <summary>
        /// Uses a feature report to set the blink pattern on the SuperMutt's LED. 
        /// 
        /// Please note that when we create a FeatureReport, all data is nulled out in the report. Since we will only be modifying 
        /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
        /// all bits are zeroed out except for the bits we care about).
        /// 
        /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled 
        /// at the end of the task chain.
        ///
        /// The SuperMutt has the following patterns:
        /// 0 - LED always on
        /// 1 - LED flash 2 seconds on, 2 off, repeat
        /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
        /// ...
        /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
        /// </summary>
        /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
        /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
        async Task SetLedBlinkPatternAsync(Byte pattern)
        {
            var featureReport = EventHandlerForDevice.Current.Device.CreateFeatureReport(SuperMutt.LedPattern.ReportId);

            var dataWriter = new DataWriter();

            // First byte is always the report id
            dataWriter.WriteByte((Byte) featureReport.Id);
            dataWriter.WriteByte(pattern);

            featureReport.Data = dataWriter.DetachBuffer();

            await EventHandlerForDevice.Current.Device.SendFeatureReportAsync(featureReport);

            rootPage.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage);
        }
コード例 #38
0
        // Enable and subscribe to specified GATT characteristic
        private async Task enableSensor(int sensor)
        {
            Debug.WriteLine("Begin enable sensor: " + sensor.ToString());
            GattDeviceService gattService = serviceList[sensor];

            if (gattService != null)
            {
                // Turn on notifications
                IReadOnlyList <GattCharacteristic> characteristicList;
                if (sensor >= 0 && sensor <= 5)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX));
                }
                else
                {
                    characteristicList = gattService.GetCharacteristics(BUTTONS_NOTIFICATION_GUID);
                }

                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];
                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        switch (sensor)
                        {
                        case (IR_SENSOR):
                            characteristic.ValueChanged += tempChanged;
                            IRTitle.Foreground           = new SolidColorBrush(Colors.Green);
                            break;

                        case (ACCELEROMETER):
                            characteristic.ValueChanged += accelChanged;
                            AccelTitle.Foreground        = new SolidColorBrush(Colors.Green);
                            setSensorPeriod(ACCELEROMETER, 250);
                            break;

                        case (HUMIDITY):
                            characteristic.ValueChanged += humidChanged;
                            HumidTitle.Foreground        = new SolidColorBrush(Colors.Green);
                            break;

                        case (MAGNETOMETER):
                            characteristic.ValueChanged += magnoChanged;
                            MagnoTitle.Foreground        = new SolidColorBrush(Colors.Green);
                            break;

                        case (BAROMETRIC_PRESSURE):
                            characteristic.ValueChanged += pressureChanged;
                            BaroTitle.Foreground         = new SolidColorBrush(Colors.Green);
                            calibrateBarometer();
                            break;

                        case (GYROSCOPE):
                            characteristic.ValueChanged += gyroChanged;
                            GyroTitle.Foreground         = new SolidColorBrush(Colors.Green);
                            break;

                        case (KEYS):
                            characteristic.ValueChanged += keyChanged;
                            KeyTitle.Foreground          = new SolidColorBrush(Colors.Green);
                            break;

                        default:
                            break;
                        }

                        // Save a reference to each active characteristic, so that handlers do not get prematurely killed
                        activeCharacteristics[sensor] = characteristic;

                        // Set the notify enable flag
                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }

                // Turn on sensor
                if (sensor >= 0 && sensor <= 5)
                {
                    characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX));
                    if (characteristicList != null)
                    {
                        GattCharacteristic characteristic = characteristicList[0];
                        if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            // Special value for Gyroscope to enable all 3 axes
                            if (sensor == GYROSCOPE)
                            {
                                writer.WriteByte((Byte)0x07);
                            }
                            else
                            {
                                writer.WriteByte((Byte)0x01);
                            }

                            await characteristic.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }
            }
            Debug.WriteLine("End enable sensor: " + sensor.ToString());
        }
コード例 #39
0
ファイル: MainPage.xaml.cs プロジェクト: bfjelds/samples
        // Enable and subscribe to specified GATT characteristic
        private async Task enableSensor(int sensor)
        {
            GattDeviceService sensorDevice;

            if (_serviceList.TryGetValue(sensor, out sensorDevice))
            {
                GattCharacteristic notification;
                lock (_notifyList)
                {
                    if (!_notifyList.TryGetValue(sensor, out notification))
                    {
                        IReadOnlyList <GattCharacteristic> notificationList;
                        if (sensor >= 0 && sensor <= 5)
                        {
                            notificationList = sensorDevice.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX));
                        }
                        else
                        {
                            notificationList = sensorDevice.GetCharacteristics(BUTTONS_NOTIFICATION_GUID);
                        }
                        if (notificationList != null)
                        {
                            _notifyList.Add(sensor, notificationList[0]);
                        }
                    }
                }

                if (_notifyList.TryGetValue(sensor, out notification))
                {
                    Debug.WriteLine($"Begin enable sensor {sensor} - {notification.UserDescription}");
                    if (notification.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
                    {
                        switch (sensor)
                        {
                        case (IR_SENSOR):
                            notification.ValueChanged += tempChanged;
                            break;

                        case (ACCELEROMETER):
                            notification.ValueChanged += accelChanged;
                            setSensorPeriod(ACCELEROMETER, 250);
                            break;

                        case (HUMIDITY):
                            notification.ValueChanged += humidChanged;
                            break;

                        case (MAGNETOMETER):
                            notification.ValueChanged += magnoChanged;
                            break;

                        case (BAROMETRIC_PRESSURE):
                            notification.ValueChanged += pressureChanged;
                            calibrateBarometer();
                            break;

                        case (GYROSCOPE):
                            notification.ValueChanged += gyroChanged;
                            break;

                        case (KEYS):
                            notification.ValueChanged += keyChanged;
                            break;

                        default:
                            break;
                        }

                        // Set the notify enable flag
                        var unused = await notification.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                    }
                }

                // Turn on sensor
                if (sensor >= 0 && sensor <= 5)
                {
                    IReadOnlyList <GattCharacteristic> enableCharacteristicList = sensorDevice.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX));
                    if (enableCharacteristicList != null)
                    {
                        GattCharacteristic characteristic = enableCharacteristicList[0];
                        if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            // Special value for Gyroscope to enable all 3 axes
                            if (sensor == GYROSCOPE)
                            {
                                writer.WriteByte((Byte)0x07);
                            }
                            else
                            {
                                writer.WriteByte((Byte)0x01);
                            }

                            await characteristic.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }

                // update UI and set value changed
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    switch (sensor)
                    {
                    case (IR_SENSOR):
                        IRTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (ACCELEROMETER):
                        AccelTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (HUMIDITY):
                        HumidTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (MAGNETOMETER):
                        MagnoTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (BAROMETRIC_PRESSURE):
                        BaroTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (GYROSCOPE):
                        GyroTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    case (KEYS):
                        KeyTitle.Foreground = new SolidColorBrush(Colors.Green);
                        break;

                    default:
                        break;
                    }
                });
            }
        }
コード例 #40
0
        /// <summary>
        /// Tells the SuperMutt device to stop creating interrupts. The app will stop getting event raises unless we start the interrupts again.
        /// 
        /// We are using an output report to start the interrupts, please go to Scenario4_InputOutputReports for more information on how to use
        /// output reports.
        /// </summary>
        private async void StopSuperMuttInputReports()
        {
            var outputReport = EventHandlerForDevice.Current.Device.CreateOutputReport(SuperMutt.DeviceInputReportControlInformation.ReportId);

            var dataWriter = new DataWriter();

            // First byte is always the report id
            dataWriter.WriteByte((Byte)outputReport.Id);
            dataWriter.WriteByte(SuperMutt.DeviceInputReportControlInformation.DataTurnOff);

            outputReport.Data = dataWriter.DetachBuffer();

            await EventHandlerForDevice.Current.Device.SendOutputReportAsync(outputReport);
        }
コード例 #41
0
        private static IBuffer getsdpRecordBlob(string serviceName, string serviceDescriptor)
        {
            DataWriter helperWriter = new DataWriter();
            DataWriter NameWriter = new DataWriter();

            // The length of the UTF-8 encoded string.
            NameWriter.WriteByte((byte)serviceName.Length);
            // The UTF-8 encoded string.
            NameWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            NameWriter.WriteString(serviceName);

            // UINT16 (0x09) value = 0x0100 [ServiceName]
            helperWriter.WriteByte(0x09);
            helperWriter.WriteByte(0x01);
            helperWriter.WriteByte(0x00);

            IBuffer serviceNameBuf = NameWriter.DetachBuffer();
            helperWriter.WriteByte(0x25); //TextString(0x25)
            helperWriter.WriteByte((byte)serviceNameBuf.Length);
            helperWriter.WriteBuffer(serviceNameBuf);

            DataWriter DescriptorWriter = new DataWriter();
            // The length of the UTF-8 encoded string.
            DescriptorWriter.WriteByte((byte)serviceDescriptor.Length);
            // The UTF-8 encoded string.
            DescriptorWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            DescriptorWriter.WriteString(serviceDescriptor);

            // UINT16 (0x09) value = 0x0101 [ServiceDescription]
            helperWriter.WriteByte(0x09);
            helperWriter.WriteByte(0x01);
            helperWriter.WriteByte(0x01);

            IBuffer descriptorBuf = DescriptorWriter.DetachBuffer();
            helperWriter.WriteByte(0x25); //TextString(0x25)
            helperWriter.WriteByte((byte)descriptorBuf.Length);
            helperWriter.WriteBuffer(descriptorBuf);

            DataWriter SdpRecordWriter = new DataWriter();
            SdpRecordWriter.WriteByte(0x35);

            IBuffer dataBuf = helperWriter.DetachBuffer();
            SdpRecordWriter.WriteByte((byte)dataBuf.Length);
            SdpRecordWriter.WriteBuffer(dataBuf);

            return SdpRecordWriter.DetachBuffer();
        }
コード例 #42
0
        // Set sensor update period 
        private async void setSensorPeriod(int sensor, int period)
        {
            GattDeviceService gattService = serviceList[sensor];
            if (sensor != KEYS && gattService != null)
            {
                var characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "3-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        // Accelerometer period = [Input * 10]ms
                        writer.WriteByte((Byte)(period / 10));
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }
            }
        }
コード例 #43
0
        void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(SERVICE_VERSION);

            var data = writer.DetachBuffer();
            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
コード例 #44
0
        // ---------------------------------------------------
        //     Hardware Configuration Helper Functions
        // ---------------------------------------------------

        // Retrieve Barometer Calibration data
        private async void calibrateBarometer()
        {
            GattDeviceService gattService = serviceList[BAROMETRIC_PRESSURE];
            if (gattService != null)
            {
                // Set Barometer configuration to 2, so that calibration data is saved
                var characteristicList = gattService.GetCharacteristics(new Guid("F000AA42-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteByte((Byte)0x02);
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }

                // Save Barometer calibration data
                characteristicList = gattService.GetCharacteristics(new Guid("F000AA43-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached);
                    baroCalibrationData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData);
                }
            }
        }