private List<byte> receivedBuffer = new List<byte>();
 private void btnConnect_Click(object sender, EventArgs e)
 {
     this.btnConnect.Enabled = false;
     this.btnDisconnect.Enabled = true;

     _deviceAdapter = new ComDeviceAdapter(this.cbxComPorts.SelectedItem?.ToString() ?? "", 9600);
     _deviceAdapter.Connect();
     _deviceAdapter.DataReceived += (s, e) =>
     {
         receivedBuffer.AddRange(e);

         foreach (var item in this.ParseJson(receivedBuffer))
         {
             AppendLog(Encoding.UTF8.GetString(item));
         }
     };
 }

 private List<byte[]> ParseJson(List<byte> buffer)
 {
     int startIndex = 0;
     int endIndex = -1;
     int depth = 0;
     List<byte[]> jsonArray = new List<byte[]>();

     // 寻找JSON数据的起始位置和结束位置
     for (int i = 0; i < buffer.Count; i++)
     {
         char ch = (char)buffer[i];

         if (ch == '{' || ch == '[')
         {
             if (depth == 0)
             {
                 startIndex = i;
             }
             depth++;
         }
         else if (ch == '}' || ch == ']')
         {
             depth--;
             if (depth == 0)
             {
                 endIndex = i;

                 //解析成功
                 byte[] jsonBytes = buffer.GetRange(startIndex, endIndex - startIndex + 1).ToArray();
                 jsonArray.Add(jsonBytes);
             }
         }
     }

     if (endIndex != -1)
     {
         buffer.RemoveRange(0, endIndex + 1);
     }

     return jsonArray;
 }

  

串口读取到的数据不是完整的,应该先存放缓冲区然后用上面解析方法提取。

posted on 2024-12-09 16:24  又是没有bug的一天  阅读(33)  评论(0)    收藏  举报