.net 串口操作学习记录
由于既没有实际串口也没有虚拟串口,上面的代码都没有进行实际测试,改进空间应该还比较巨大;
首先需要一个单例:
private static MSerialPort _instance = null; private static Object _mutex = new Object(); public static MSerialPort GetInstance(int ComPortNum) { if (_instance == null) { lock (_mutex) // now I can claim some form of thread safety... { if (_instance == null) { _instance = new MSerialPort(ComPortNum); } } } return _instance; } private MSerialPort(int ComPortNum):base(){ ... }
异步写:
public async Task<bool> WriteStr(string value) { if (!base.IsOpen) { if (!doConnect(_ComPortNum)) { return false; } } byte[] buffer = new byte[128]; Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0); bool flag = false; try { base.BaseStream.WriteTimeout = 2; await base.BaseStream.WriteAsync(buffer, 0, 128); flag = true; } catch (Exception ex) { Console.WriteLine("MSerialPort exception: " + ex); } return flag; }
异步读一次:
public async Task<Tuple<bool,string>> readStr()//ref string value { if (!base.IsOpen) { doConnect(_ComPortNum); } byte[] buffer = new byte[128]; bool flag = false; try { base.BaseStream.ReadTimeout = 2; await base.BaseStream.ReadAsync(buffer, 0, 128);//这种一旦读到任何内容就结束 flag = true; } catch (Exception ex) { Console.WriteLine("MSerialPort exception: " + ex); } return new Tuple<bool, string>(flag, System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length)); }
异步读到特征值:
public async Task<Tuple<bool, MatchCollection>> readUntil(Regex reg)//ref string value, { Console.WriteLine("readUntil"); if (!base.IsOpen) { doConnect(_ComPortNum); } DateTime beforDT = System.DateTime.Now; byte[] buffer = new byte[128]; base.BaseStream.ReadTimeout = 2; double spend = 0; bool flag = false; StringBuilder sb = new StringBuilder(); MatchCollection matchx = null; await Task.Run(() => { do { Array.Clear(buffer, 0, buffer.Length); try { base.BaseStream.Read(buffer, 0, 128); }catch(Exception ex) { //Console.WriteLine("MSerialPort exception: " + ex); } sb.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length)); string value = sb.ToString(); if(value != "") { matchx = reg.Matches(value); if (matchx.Count > 0) { flag = true; break; } } DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforDT); spend = ts.TotalMilliseconds; } while (spend <= 5000.0); }); return new Tuple<bool, MatchCollection>(flag, matchx); }
测试调用:
单例: static async void MyAsyncMethod() { MSerialPort s = GetInstance(1); Task<bool> calculateResult = s.WriteStr("123"); await calculateResult; Regex rx = new Regex(@"(\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); Task<Tuple<bool, MatchCollection>> calculateResult1 = s.readUntil(rx); await calculateResult1; }
看到这种建议:
Strongly recommend PInvokeSerialPort, it fires one event for every byte, and more stable than .net built in one ===>(一个c++串口的wrapper)
https://stackoverflow.com/questions/42568662/serial-port-on-c-read-until-a-byte-sequence
其他参考:
https://stackoverflow.com/questions/18716928/how-to-write-a-async-method-with-out-parameter
https://stackoverflow.com/questions/40686776/what-exactly-is-a-reference-in-c-sharp
https://www.tutorialspoint.com/csharp/csharp_reference_parameters.htm+&cd=16&hl=en&ct=clnk&gl=sg
https://stackoverflow.com/questions/11654562/how-to-convert-byte-array-to-string
https://msdn.microsoft.com/en-us/magazine/cc301786.aspx
https://www.codeproject.com/Questions/1060886/Continuosly-serial-port-read
https://blog.csdn.net/xzjxylophone/article/details/6832160
https://blog.csdn.net/u013658041/article/details/78203931
https://stackoverflow.com/questions/51658706/await-async-on-anonymous-function
https://stackoverflow.com/questions/1897555/what-is-the-equivalent-of-memset-in-c
https://stackoverflow.com/questions/1407715/how-to-quickly-zero-out-an-array/43188508
https://www.geeksforgeeks.org/destructors-in-c-sharp/+&cd=1&hl=en&ct=clnk&gl=sg
https://stackoverflow.com/questions/5732282/using-the-destructor-dispose-of-the-base-class
https://csharpindepth.com/articles/singleton+&cd=1&hl=en&ct=clnk&gl=sg
https://stackoverflow.com/questions/4203634/singleton-with-parameters
https://stackoverflow.com/questions/24894774/how-to-use-await-within-main
https://recaffeinate.co/post/how-to-await-console-application/+&cd=4&hl=en&ct=clnk&gl=sg
https://github.com/ebraminio/PInvokeSerialPort
/*-------------------------C#有名管道-------------------------------------*/
https://bytes.com/topic/c-sharp/answers/277259-readtoend-blocking+&cd=2&hl=en&ct=clnk&gl=sg
https://www.codeproject.com/Articles/864679/Creating-a-Server-Using-Named-Pipes
https://gist.github.com/Suplanus/f652a15a55bff64b6ccb33836041f8bb
https://gist.github.com/AArnott/0d5f4645ad7e9a765cee
https://stackoverflow.com/questions/23304311/async-namedpipeclientstream-implementation-feedback
https://stackoverflow.com/questions/49838628/named-pipe-input-output-in-c-sharp
1.ReadToEnd阻塞的原因(https://bytes.com/topic/c-sharp/answers/277259-readtoend-blocking+&cd=2&hl=en&ct=clnk&gl=sg)
--No - there's no real sense of "all data" until the stream has been
closed, because the server could always have sent some more since you
2.WaitForPipeDrain();//等待管道另一端读取所有
/*-------------------------C#单元测试-------------------------------------*/
https://blog.csdn.net/lang791534167/article/details/50778246
/*-------------------------C#异步-------------------------------------*/
https://blog.csdn.net/madongchunqiu/article/details/69855744
https://blog.csdn.net/jl1134069094/article/details/50511418
https://blog.csdn.net/a_little_a_day/article/details/78519265
https://codeday.me/bug/20190223/699688.html
https://blog.csdn.net/lxrj2008/article/details/78677810
https://blog.csdn.net/wlk1229/article/details/81276970
https://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c
/*-------------------------C#异步-------------------------------------*/
https://msdn.microsoft.com/en-us/magazine/cc164086.aspx
https://stackoverflow.com/questions/1949051/is-there-a-fiber-api-in-net
https://paoloseverini.wordpress.com/tag/fibers/+&cd=5&hl=zh-CN&ct=clnk&gl=sg
https://blog.csdn.net/mawming/article/details/52385405
https://docs.microsoft.com/en-us/windows/win32/procthread/fibers
https://stackoverflow.com/questions/31221210/fibers-vs-async-await
https://www.zhihu.com/question/23955356
https://github.com/markpapadakis/coros-fibers
- 点赞
- 收藏
- 关注作者
评论(0)