如何将字符串与传入消息进行比较

问题描述 投票:0回答:1

我知道这听起来很简单,但遇到了一些麻烦。我正在尝试制作一个带有图片微控制器(MCU)和xamarin android应用程序的系统。从应用程序到pic MCU的发送部分已解决,但是当我要将数据从MCU发送到应用程序时,它不会完美无缺。我正在使用HC-06作为接收和发送消息的蓝牙设备。

从MCU接收到应用程序的代码是:

public void beginListenForData()
    {
        try
         {
             inStream = btSocket.InputStream;
         }
         catch (IOException ex)
         {
             Console.WriteLine(ex.Message);
         }
         Task.Factory.StartNew(() => {
             byte[] buffer = new byte[1024];
             int bytes;
             while (true)
             {
                 try
                 {
                     Array.Reverse(buffer, 0, buffer.Length);
                     bytes = inStream.Read(buffer, 0, buffer.Length);
                     if (bytes > 0)
                     {
                         string valor = Encoding.ASCII.GetString(buffer);
                         System.Diagnostics.Debug.WriteLine(buffer);
                         System.Diagnostics.Debug.WriteLine(bytes);
                         System.Diagnostics.Debug.WriteLine(valor);
                         if (valor == "D0O")
                         {
                             System.Diagnostics.Debug.WriteLine("Vergelijking gelukt!");
                             break;
                         }
                         //Result.Text = Result.Text + "\n" + valor;
                     }
                 }
                 catch (Java.IO.IOException)
                 {
                     //Result.Text = string.Empty;
                     break;
                 }
             }
         });
    }

当比较与传入的消息进行调试时,我尝试从MCU发送的消息是D0O(勇气),您可能会对此感到不满:

System.Diagnostics.Debug.WriteLine("Vergelijking gelukt!");

下一部分是检查要输入什么数据:

System.Diagnostics.Debug.WriteLine(buffer);
System.Diagnostics.Debug.WriteLine(bytes);
System.Diagnostics.Debug.WriteLine(valor);

我注意到的是奇怪的输出(见图):

enter image description here

如您所见,每次将消息分为两部分。有谁知道为什么以及如何解决它?

我确实使用以下命令更改了数组顺序:

Array.Reverse(buffer, 0, buffer.Length);

因为我确实注意到它以错误的顺序输入。确实可以按正确的顺序进行操作。

小更新:

我更改了一些代码行,但它的工作方式更“无礼”

while ((count = inStream.Read(buffer, 0, buffer.Length)) > 0)

但是奇怪的是第一位与接收字符串的其余部分分开。如果有人有想法,我不确定是什么原因导致此问题?

提前感谢。

我知道这听起来很简单,但遇到了一些麻烦。我正在尝试制作一个带有图片微控制器(MCU)和xamarin android应用程序的系统。从应用程序到pic MCU的发送部分已解决,但...

c# android xamarin bluetooth
1个回答
0
投票

我找到了解决所面临问题的解决方案。因此,我将分享我的答案和思考过程,以便也许其他人可以使用相同的答案。

© www.soinside.com 2019 - 2024. All rights reserved.