Exemple #1
0
        private async Task splitProcess(string str512, ICharacteristic _characteristic)
        {
            int chunkSize    = 512;
            int stringLength = str512.Length;

            byte[] senddata = Encoding.UTF8.GetBytes("start");
            var    bytes    = await _characteristic.WriteAsync(senddata);

            //receiveStr("start");

            for (int i = 0; i < stringLength; i += chunkSize)
            {
                if (i + chunkSize > stringLength)
                {
                    chunkSize = stringLength - i;
                }
                senddata = Encoding.UTF8.GetBytes(str512.Substring(i, chunkSize));
                bytes    = await _characteristic.WriteAsync(senddata);

                //receiveStr(str.512.Substring(i, chunkSize));
            }
            senddata = Encoding.UTF8.GetBytes("end");
            bytes    = await _characteristic.WriteAsync(senddata);

            //receiveStr("end");
        }
Exemple #2
0
 private async void blePing()
 {
     if (IsBleConnected)
     {
         byte[] ping = new byte[] { 0x31, 0x32, 0x33 };
         await dataWriteCharacteristic.WriteAsync(ping);
     }
 }
Exemple #3
0
        async private Task SendCmdAndWait(byte [] command)
        {
            await charCtrl.WriteAsync(command);

            image          = null;
            imageProcessed = null;
            canvasView.InvalidateSurface();
            canvasViewProcessed.InvalidateSurface();
            await NotifyWaitMsg();
        }
Exemple #4
0
        public async Task Subscribe()
        {
            try
            {
                Debug.WriteLine($"***SUBSCRIBING {Data.Name}...");

                if (Data.Id != null)
                {
                    if (_device == null)
                    {
                        var cancellationTokenSource = new CancellationTokenSource(5000);
                        _device = await SensorKit.Instance.Adapter.ConnectToKnownDeviceAsync(Data.Id, default(ConnectParameters), cancellationTokenSource.Token);
                    }

                    if (_device != null && (uart == null || _uartTX == null || _uartRX == null))
                    {
                        _connectedTime = DateTime.Now;

                        uart = await _device.GetServiceAsync(NORDIC_UART_SERVICE);

                        if (uart != null)
                        {
                            _uartRX = await uart.GetCharacteristicAsync(NORDIC_UART_RX);

                            _uartTX = await uart.GetCharacteristicAsync(NORDIC_UART_TX);

                            _uartRX.ValueUpdated += (s, e) =>
                            {
                                var received = Encoding.UTF8.GetString(e.Characteristic.Value, 0, e.Characteristic.Value.Length);
                                ParsePacket(received);
                            };

                            IsConnected = true;

                            await _uartRX.StartUpdatesAsync();
                        }
                    }

                    if (_uartTX != null)
                    {
                        await _uartTX.WriteAsync(Encoding.UTF8.GetBytes(SYNC_COMMAND_HISTORY));
                    }

                    InvokeHelper.Invoke(() =>
                    {
                        Data.NotifyPropertyChanged("IsSubscribed");
                    });
                }
            }catch (Exception x)
            {
                Debug.WriteLine(x);
            }
        }
        private async Task <bool> SendBleMessage(string message)
        {
            bool result = false;

            if (_bleDevice != null && (!String.IsNullOrWhiteSpace(message)))
            {
                _txCharacteristic = _txCharacteristic
                                    ?? await FindBleCharacteristic(BleUartServiceId, BleTxCharacteristicId, _bleDevice);

                if (_txCharacteristic == null)
                {
                    throw new InvalidOperationException("Unable to retrieve the characteristic needed to send commands to the BLE device.");
                }
                else if (!_txCharacteristic.CanWrite)
                {
                    throw new InvalidOperationException("The characteristic needed to send commands to the BLE device does not support this operation.");
                }

                byte[] bytesToSend = Encoding.ASCII.GetBytes(message);
                result = await _txCharacteristic.WriteAsync(bytesToSend);

                _previousValue = 0;
            }

            return(result);
        }
Exemple #6
0
        /// <summary>
        /// Handles the remote date time validation.
        /// </summary>
        /// <remarks>
        /// We validate the DA-12 station time and if it's before 2009 we know
        /// it's not valid, so we set a new time.
        /// We take a Unix timestamp as UTC and formats it into a station command to
        /// update the time.
        /// </remarks>
        /// <param name="txCharacteristic">Bluetooth service characteristic</param>
        /// <param name="remoteUnixDateTime">The remote Unix date time.</param>
        public async Task <bool> HandleRemoteDateTimeValidation(ICharacteristic txCharacteristic, int remoteUnixDateTime)
        {
            // Validate our station Unix time converted to windows time is less
            // than 2009.  If it is we know the station time needs to be set.
            if (remoteUnixDateTime.UnixTimeStampToDateTime().Year < CoreConstants.StationSettingLowestDateTimeYear)
            {
                // Get Unix timestamp "now" as UTC
                Int32 unixTimestampUtc = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                // Format DA-12 station Unix timestamp
                // T - is to set the station time,
                // 0 - is the data type
                // 00 - device index / unused
                // Next set of digits is Unix time UTC (converted to HEX)
                string remoteUnitTimestamp = "{T000" + unixTimestampUtc.ToString("X") + "}";

                // Send set Unix UTC time command to remote
                await txCharacteristic.WriteAsync(remoteUnitTimestamp.StrToByteArray()).ConfigureAwait(true);

                // Wait a couple seconds for remote to process
                await Task.Delay(3000).ConfigureAwait(true);

                // Let caller know we set station time
                return(true);
            }

            // We didn't set station time
            return(false);
        }
Exemple #7
0
        async Task SetColor()
        {
            byte[] rgb = new byte[] { (byte)SliderRed.Value, (byte)SliderGreen.Value, (byte)SliderBlue.Value };
            await charRGB.WriteAsync(rgb);

            ColorIndicator.Color = new Color(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0);
        }
Exemple #8
0
        private async Task GetMovementService()
        {
            try
            {
                IService service = await device.GetServiceAsync(Guid.Parse("f000aa80-0451-4000-b000-000000000000"));

                ICharacteristic dataCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("f000aa81-0451-4000-b000-000000000000"));

                ICharacteristic configCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("f000aa82-0451-4000-b000-000000000000"));

                await configCharacteristic.WriteAsync(new byte[] { 0x7F, 0x00 });

                _gyro    = new Gyroscope();
                _acc     = new Accelerometer();
                _mag     = new Magnetometer();
                Plates   = new List <Plate>();
                database = new StrongPlateDataService();
                dataCharacteristic.ValueUpdated += (o, args) =>
                {
                    byte[] bytes = args.Characteristic.Value;

                    SetGyro(bytes);
                    SetAcc(bytes);
                    SetMag(bytes);
                    addPlate();
                };
                await dataCharacteristic.StartUpdatesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error GetMovementService: " + ex);
            }
        }
        Guid myCharacteristicUuid = Guid.Parse("fe68847f-59ec-4429-9701-74423a4a7ad4"); // UUID of a known characteristic (Dimming Value)

        private async void OnSliderChanged(object sender, ValueChangedEventArgs args)
        {
            if (Service == null)
            {
                try { Service = await device.GetServiceAsync(myServiceUuid); }
                catch { return; }
            }
            if (Characteristic == null)
            {
                try { Characteristic = await Service.GetCharacteristicAsync(myCharacteristicUuid); }
                catch { return; }
            }
            double value = args.NewValue;
            //string valor = String.Format("{0:F0}", value);
            int iValue = (int)Math.Round(value);

            //int iValue = Convert.ToByte(value);
            sLabel.Text = iValue.ToString();
            byte[] sliderValue = BitConverter.GetBytes(iValue);
            if (Characteristic.CanWrite)
            {
                try
                {
                    var res = await Characteristic.WriteAsync(sliderValue);
                }
                catch (Exception ex)
                {
                    //await DisplayAlert("Alert", ex.Message ,"Ok");
                }
            }
            //sLabel.Text = BitConverter.ToString(valorb);
            //var characteristic = await GetCharacteristicById(parameters, Guid.Parse("00002A87-0000-1000-8000-00805f9b34fb"));
            //byte[] array = Encoding.UTF8.GetBytes(UserDataMock.Email);
            //characteristic.WriteAsync(array);
        }
Exemple #10
0
        private async void BtnWOn_Clicked(object sender, EventArgs e)
        {
            //Guid myServiceUuid = new Guid("166e3275-1b3a-465c-b0e1-3cbc24c5acbe"); // UUID of a known service (Dimming Service)
            try
            {
                Service = await device.GetServiceAsync(myServiceUuid);
            }
            catch (Exception ex)
            {
                return;
            }
            //Guid myCharacteristicUuid = Guid.Parse("fe68847f-59ec-4429-9701-74423a4a7ad4"); // UUID of a known characteristic (Dimming Value)
            try
            {
                Characteristic = await Service.GetCharacteristicAsync(myCharacteristicUuid);
            }
            catch
            {
                return;
            }
            if (Characteristic.CanWrite)
            {
                var result = await Characteristic.WriteAsync(new byte[] { 255 });

                if (!result)
                {
                    Debug.WriteLine("CAN'T WRITE TO CHARACTERISTIC");
                }
                else
                {
                    Debug.WriteLine("CHARACTERISTIC WRITTEN");
                }
            }
        }
Exemple #11
0
 public async Task SendAsync(string message)
 {
     if (_characteristic != null)
     {
         await _characteristic.WriteAsync(GetBytes(message));
     }
 }
Exemple #12
0
        private async Task SendDataAsync(string value)
        {
            await _characteristic?.WriteAsync(Encoding.ASCII.GetBytes(value));

            _selectedCommand = value;
            UpdateControlColors();
        }
Exemple #13
0
        private async Task <bool> SendFrame(byte[] frame)
        {
            if (!_isConnected)
            {
                return(await Task.FromResult(false));
            }
            else
            {
                if (_analyzerChar != null)
                {
                    _responseFrame = null;
                    byte[] frameToSend = new byte[8 + frame.Length];

                    // Imposto l'header
                    Encoding.ASCII.GetBytes(_frameMarker).CopyTo(frameToSend, 0);

                    // Imposto il frame da inviare
                    frame.CopyTo(frameToSend, 4);

                    // Calcolo e imposto il crc
                    UInt32 crc = Crc32_STM.CalculateFromBuffer(frameToSend, frameToSend.Length - 4);
                    ArrConverter.SetBufferFromUInt32(crc, frameToSend, frameToSend.Length - 4);

                    await _analyzerChar.WriteAsync(frameToSend);
                }
                else
                {
                    return(await Task.FromResult(false));
                }
            }
            return(await Task.FromResult(true));
        }
Exemple #14
0
        async private void BtnTalk_Released(object sender, EventArgs e)
        {
            await charCtrl.WriteAsync(new byte[1] {
                CMD_MIC_CLOSE
            });

            Player.Stop();

            if (SamplingRatePicker.SelectedIndex != 0)
            {
                return;
            }

            ISpeechRecognition engine;

            switch (EnginePicker.SelectedIndex)
            {
            case 1:
                engine = new TecentAiRecognizer();
                break;

            case 2:
                engine = new GoogleRecognizer("cmn-Hans-CN");
                break;

            case 3:
                engine = new GoogleRecognizer("en-US");
                break;

            default:
                engine = new NullRecognizer();
                break;
            }

            STTResult.Text = "Recognizing ...";
            var samples = AllSamples.ToArray();

            try
            {
                STTResult.Text = await engine.Recognize(samples);
            }
            catch (Exception ex)
            {
                STTResult.Text = "error: " + ex.Message;
            }
        }
        private async Task SendDataAsync(string componentCode, string value)
        {
            //Prefix
            string data = "#$";

            data += componentCode + value + "%";
            await _characteristic?.WriteAsync(Encoding.ASCII.GetBytes(data));
        }
Exemple #16
0
        async Task <bool> Upload(byte[] page, int BLOCK_SIZE, Action <int> onProgress)
        {
            var cmd = new byte[] { ETAG_CMD_IMG_START_WRITE };

            if (!await charCtrl.WriteAsync(cmd))
            {
                return(false);
            }
            if (!await CheckStatus())
            {
                return(false);
            }

            int current = 0;
            int cnt     = 0;

            while (current < page.Length)
            {
                onProgress(current);

                int size  = Math.Min(BLOCK_SIZE, page.Length - current);
                var block = new byte[size];
                Array.Copy(page, current, block, 0, size);
                if (!await charData.WriteAsync(block))
                {
                    return(false);
                }
                current += size;

                cnt++;
                if ((cnt % 4) == 0)
                {
                    if (!await WaitData(current))
                    {
                        return(false);
                    }
                }
            }

            // wait for BLE stack
            if (!await WaitData(current))
            {
                return(false);
            }

            cmd = new byte[] { ETAG_CMD_IMG_COMPLETE, 0, 0, 0, 0 };
            UInt32 sum = (UInt32)page.Sum((x) => x);

            Utils.WriteLittle(sum, cmd, 1);

            if (!await charCtrl.WriteAsync(cmd))
            {
                return(false);
            }
            await Task.Delay(10);

            return(await CheckStatus());
        }
        public async Task <bool> WriteValueAsync(byte[] data)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            return(await _characteristic.WriteAsync(data));
        }
        /// <summary>
        /// Writes the given data in the bluetooth connection interface.
        /// </summary>
        /// <param name="data">The data to be written in the connection interface.</param>
        /// <param name="offset">The start offset in the data to write.</param>
        /// <param name="length">The number of bytes to write.</param>
        /// <exception cref="XBeeException">If there is any XBee error.</exception>
        /// <seealso cref="WriteData(byte[])"/>
        public void WriteData(byte[] data, int offset, int length)
        {
            lock (txLock)
            {
                Debug.WriteLine("----- WriteData " + HexUtils.ByteArrayToHexString(data));
                bool dataWritten = false;

                // Create a task to write in the TX characteristic.
                Task task = Task.Run(async() =>
                {
                    try
                    {
                        byte[] buffer = new byte[length];
                        Array.Copy(data, offset, buffer, 0, length);

                        byte[] dataToWrite = encrypt ? encryptor.TransformFinalBlock(buffer, 0, buffer.Length) : buffer;

                        // Split the data in chunks with a max length of the current MTU.
                        foreach (byte[] chunk in GetChunks(dataToWrite))
                        {
                            // Write the chunk in the TX characteristic.
                            dataWritten = await txCharacteristic.WriteAsync(chunk);
                        }
                    }
                    finally
                    {
                        lock (writeLock)
                        {
                            Monitor.Pulse(writeLock);
                        }
                    }
                });

                if (!task.IsCompleted)
                {
                    // Wait until the task finishes.
                    lock (writeLock)
                    {
                        Monitor.Wait(writeLock, WRITE_TIMEOUT);
                    }
                }

                // If the data could not be written, decrement the counter and throw an exception.
                if (!dataWritten)
                {
                    encryptor.DecrementCounter();
                    throw new XBeeException(ERROR_WRITE);
                }

                // If the task finished with excepction, throw it.
                if (task.Exception != null)
                {
                    throw task.Exception.InnerException;
                }
            }
        }
Exemple #19
0
        async private Task SetFreq(double freq)
        {
            uint f = (uint)Math.Round(freq);

            byte[] cmd = new byte[2] {
                (byte)(f & 0xff), (byte)(f >> 8)
            };

            await charKey.WriteAsync(cmd);
        }
Exemple #20
0
 public async Task <bool> Send(byte[] msg)
 {
     if (IsConnected() && characteristic.CanWrite)
     {
         return(await characteristic.WriteAsync(msg));
     }
     else
     {
         return(false);
     }
 }
Exemple #21
0
        async private void Run(CancellationToken token)
        {
            var  buf       = new byte[MtuSize];
            var  now       = DateTime.Now;
            long total     = 0;
            long dev_total = 0;
            long my_total  = 0;
            var  error     = false;
            int  cnt       = 0;

            while (!error && !token.IsCancellationRequested)
            {
                try
                {
                    if (my_total - dev_total < 2000)
                    {
                        if (await charInput.WriteAsync(buf))
                        {
                            cnt++;
                            total    += MtuSize;
                            my_total += MtuSize;
                        }
                    }
                    else
                    {
                        await Task.Delay(200);
                    }
                }
                catch (Exception) { error = true; }

                if (cnt >= 5)
                {
                    // verify data has been written into device
                    dev_total = await GetTotalBytes() - StartByteNumber;

                    if (my_total - dev_total < 10)
                    {
                        cnt = 0;
                    }
                }

                var    temp = DateTime.Now;
                double span = (temp - now).TotalMilliseconds;
                if (span > 1000.0)
                {
                    SaveSpeed(CurM2STpt, TptM2SSeries, total * 8.0 / span);
                    now   = temp;
                    total = 0;
                }
            }
            Testing = false;
            Device.BeginInvokeOnMainThread(() => CurM2STpt.Text = "Stopped");
        }
 private async void SendCommandButton_Clicked(object sender, EventArgs e)
 {
     try
     {
         if (sendCharacteristic != null)
         {
             var bytes = await sendCharacteristic.WriteAsync(Encoding.ASCII.GetBytes($"{CommandTxt.Text}\r\n"));
         }
     }
     catch
     {
         Output.Text += "Error sending comand to UART." + Environment.NewLine;
     }
 }
Exemple #23
0
        /// <summary>
        /// Sends the request message to the slave device
        /// </summary>
        /// <returns>The message.</returns>
        /// <param name="message">Message.</param>
        public async Task <TransmissionState> SendMessage(byte[] message)
        {
            bool succed = false;

            try
            {
                succed = await writeCharac.WriteAsync(message);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Failed to WriteAsync Message: " + ex.Message.ToString());
                succed = await writeCharac.WriteAsync(message);
            }

            if (succed == true)
            {
                return(TransmissionState.OK);
            }
            else
            {
                return(TransmissionState.ErrorSendMessage);
            }
        }
Exemple #24
0
 async void Reset_Clicked(object sender, System.EventArgs e)
 {
     if (_characteristicSnd != null && _characteristicSnd.CanWrite)
     {
         byte[] cmd = { (byte)'R', (byte)'S', (byte)'T' };
         await _characteristicSnd.WriteAsync(cmd);
     }
     else
     {
         rotationSliderX.Value = 0;
         rotationSliderY.Value = 0;
         rotationSliderZ.Value = 0;
     }
 }
Exemple #25
0
 public bool Send(byte[] pInput)
 {
     try
     {
         mCharacteristic.WriteAsync(pInput);
         return(true);
     }
     catch (Exception e)
     {
         Debug.WriteLine("Failed to Send.");
         Debug.WriteLine(e);
     }
     return(false);
 }
Exemple #26
0
 public async Task <bool> WriteCharacteristics(ICharacteristic ch, byte[] data)
 {
     if (ch == null)
     {
         return(false);
     }
     try
     {
         return(await ch.WriteAsync(data));
     }
     catch
     {
         return(false);
     }
 }
        async void TryWrite(string command)
        {
            if (mainCharacteristic == null || writing == true)
            {
                return;
            }

            writing = true;
            try
            {
                await mainCharacteristic.WriteAsync(Encoding.ASCII.GetBytes(command));
            }
            catch { }
            writing = false;
        }
Exemple #28
0
 public void WriteValueAsyncInCharacteristic(byte[] bytesArray, ICharacteristic characteristic)
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         try
         {
             bool result = await characteristic.WriteAsync(bytesArray);
             System.Diagnostics.Debug.WriteLine("Write ok ! " + result);
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine("Error WriteValueAsyncInCharacteristic " + ex.Message);
         }
     });
 }
Exemple #29
0
        async private void BtnSend_Clicked(object sender, EventArgs e)
        {
            if (Input.Text?.Length < 1)
            {
                return;
            }
            byte[] bytes = Encoding.UTF8.GetBytes(Input.Text);
            var    buf   = new byte[bytes.Length + 1];

            Array.Copy(bytes, buf, bytes.Length);
            buf[bytes.Length] = 0;
            await charInput.WriteAsync(buf);

            DataLog.Text = DataLog.Text + "\n> " + Input.Text + "\n";
            Input.Text   = "";
        }
        private async Task Finish()
        {
            //UUID_EEPROM_CONTROL < -0x09, 0x01(ustawienie trybu bufora cyklicznego)
            //UUID_EEPROM_CONTROL < -0x01, 0x01
            var data = new byte[2];

            data[0] = 0x09;
            data[1] = 0x01;
            await _eepromControlCharacteristic.WriteAsync(data);

            data[0] = 0x01;
            data[1] = 0x01;
            await _eepromControlCharacteristic.WriteAsync(data);
        }