以下是类AlifCoSerialPort.cs:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace AlifCoSerialPort 8 { 9 /// <summary> 10 /// Alif串口(初始化之后一定要调用Run方法) 11 /// </summary> 12 public class AlifSerialPort : Base 13 { 14 #region 属性 15 16 /// <summary> 17 /// 串口列表 18 /// </summary> 19 private List<Port> _listPort = null; 20 21 /// <summary> 22 /// 串口列表 23 /// </summary> 24 public List<Port> ListPort 25 { 26 get { return this._listPort; } 27 set { this._listPort = value; } 28 } 29 30 /// <summary> 31 /// 32 /// </summary> 33 private List<AlifSerialPortBaseClass> _listAlifSerialPortBaseClass = null; 34 35 /// <summary> 36 /// 37 /// </summary> 38 public List<AlifSerialPortBaseClass> ListAlifSerialPortBaseClass 39 { 40 get { return this._listAlifSerialPortBaseClass; } 41 set { this._listAlifSerialPortBaseClass = value; } 42 } 43 44 public delegate void _delegateSendMsg(Common.Msg msg); 45 46 public _delegateSendMsg sendMsgEvent; 47 48 /// <summary> 49 /// 监视线程超时时间 50 /// </summary> 51 private int _monitorThreadTimeout = 1000; 52 53 /// <summary> 54 /// 55 /// </summary> 56 public int MonitorThreadTimeout 57 { 58 get { return this._monitorThreadTimeout; } 59 set { this._monitorThreadTimeout = value; } 60 } 61 62 /// <summary> 63 /// 是否线程监视 64 /// </summary> 65 private bool _boolThreadMonitor = true; 66 67 /// <summary> 68 /// 是否线程监视 69 /// </summary> 70 public bool BoolThreadMonitor 71 { 72 get { return this._boolThreadMonitor; } 73 set { this._boolThreadMonitor = value; } 74 } 75 76 #endregion 77 78 /// <summary> 79 /// 构造函数 80 /// </summary> 81 public AlifSerialPort() { } 82 83 /// <summary> 84 /// 构造函数 85 /// </summary> 86 public AlifSerialPort(_delegateSendMsg sendMsgEvent) 87 { 88 this.sendMsgEvent = sendMsgEvent; 89 } 90 91 /// <summary> 92 /// 93 /// </summary> 94 private void ThreadMonitorSerialPortStatus() 95 { 96 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 97 Common.MsgLevel.Information, 98 "监视串口状态线程已启动,即将要监视串口状态......")); 99 while (true) 100 { 101 try 102 { 103 if (this.BoolThreadMonitor) 104 { 105 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 106 { 107 108 int flag = 0; 109 foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) 110 { 111 if (s == alifSerialPortBaseClass.port.portName) 112 { 113 flag++; 114 } 115 } 116 117 if (flag == 0) 118 { 119 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 120 Common.MsgLevel.Error, 121 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,请检查串口线......")); 122 alifSerialPortBaseClass.InitSerialPortConnection(); 123 } 124 125 if (alifSerialPortBaseClass.serialPort == null || !alifSerialPortBaseClass.IsOpen()) 126 { 127 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 128 Common.MsgLevel.Error, 129 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,线程正在启动此串口......")); 130 131 alifSerialPortBaseClass.InitSerialPortConnection(); 132 } 133 else 134 { 135 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 136 Common.MsgLevel.Information, 137 "串口" + alifSerialPortBaseClass.port.Details() + " 线程监听此串口正常!!!")); 138 } 139 } 140 } 141 } 142 catch (Exception ex) 143 { 144 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 145 Common.MsgLevel.Exception, 146 "线程监视串口状态发生错误,错误原因:" + ex.Message)); 147 } 148 149 Thread.Sleep(this._monitorThreadTimeout); 150 } 151 } 152 153 /// <summary> 154 /// 构造函数 155 /// </summary> 156 /// <param name="listPort"></param> 157 public AlifSerialPort(List<Port> listPort, _delegateSendMsg sendMsgEvent) 158 { 159 this.ListPort = listPort; 160 this.sendMsgEvent = sendMsgEvent; 161 } 162 163 #region 公共方法 164 165 /// <summary> 166 /// 添加串口 167 /// </summary> 168 /// <param name="port"></param> 169 public void AddPort(Port port) 170 { 171 if (this.ListPort == null) 172 { 173 this.ListPort = new List<Port>(); 174 } 175 176 this.ListPort.Add(port); 177 } 178 179 /// <summary> 180 /// 运行串口 181 /// </summary> 182 public void Run() 183 { 184 Listen(); 185 186 CreateAndStartThread(this._thread, ThreadMonitorSerialPortStatus); 187 } 188 189 /// <summary> 190 /// 191 /// </summary> 192 private void Listen() 193 { 194 try 195 { 196 List<AlifSerialPortBaseClass> list = new List<AlifSerialPortBaseClass>(); 197 198 if (this.ListPort.Count == 0) 199 { 200 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 201 Common.MsgLevel.Error, 202 "没有串口可以监听,请添加串口!!!")); 203 } 204 205 foreach (Port port in this.ListPort) 206 { 207 port.portName = port.portName.ToUpper().Replace("COM", ""); 208 209 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 210 Common.MsgLevel.Information, 211 "正在监听串口:" + port.Details())); 212 213 AlifSerialPortBaseClass alifSerialPortBaseClass = new AlifSerialPortBaseClass(port); 214 215 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 216 Common.MsgLevel.Information, 217 "监听串口:" + port.Details() + "成功!!!")); 218 219 list.Add(alifSerialPortBaseClass); 220 } 221 222 this.ListAlifSerialPortBaseClass = list; 223 } 224 catch (Exception ex) 225 { 226 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 227 Common.MsgLevel.Exception, 228 "监听串口发生错误,错误原因:" + ex.Message)); 229 } 230 } 231 232 /// <summary> 233 /// 发送消息 234 /// </summary> 235 /// <param name="msg">消息内容</param> 236 private void SendMsg(Common.Msg msg) 237 { 238 if (this.sendMsgEvent != null) 239 { 240 this.sendMsgEvent(msg); 241 } 242 } 243 244 /// <summary> 245 /// 获取计算机串口名称 246 /// </summary> 247 /// <returns></returns> 248 public string[] GetSerialPortNames() 249 { 250 return System.IO.Ports.SerialPort.GetPortNames(); 251 } 252 253 /// <summary> 254 /// 初始化串口 255 /// </summary> 256 /// <param name="port"></param> 257 public void InitSerialPort(Port port) 258 { 259 260 } 261 262 /// <summary> 263 /// 发送数据 264 /// </summary> 265 /// <param name="port"></param> 266 /// <param name="bytes"></param> 267 public void SendData(Port port, byte[] bytes) 268 { 269 try 270 { 271 int flag = 0; 272 273 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 274 { 275 if (alifSerialPortBaseClass.port.portName == port.portName) 276 { 277 flag++; 278 alifSerialPortBaseClass.SendData(bytes); 279 } 280 } 281 282 if (flag == 0) 283 { 284 throw new Exception(string.Format(@"没有指定的串口!!!")); 285 } 286 287 } 288 catch (Exception ex) 289 { 290 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 291 Common.MsgLevel.Exception, 292 string.Format(@"往串口[0]发送数据发送失败,失败原因:{1}", port.Details(), ex.Message))); 293 } 294 } 295 296 /// <summary> 297 /// 设置参数 298 /// </summary> 299 /// <param name="port"></param> 300 public void SetParameters(Port port) 301 { 302 303 } 304 305 /// <summary> 306 /// 关闭串口 307 /// </summary> 308 /// <param name="port"></param> 309 public void Close(Port port) 310 { 311 try 312 { 313 int flag = 0; 314 315 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 316 { 317 if (alifSerialPortBaseClass.port.portName == port.portName) 318 { 319 flag++; 320 alifSerialPortBaseClass.Close(); 321 } 322 } 323 324 if (flag == 0) 325 { 326 throw new Exception(string.Format(@"没有指定的串口!!!")); 327 } 328 329 } 330 catch (Exception ex) 331 { 332 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 333 Common.MsgLevel.Exception, 334 string.Format(@"关闭串口[0]失败,失败原因:{1}", port.Details(), ex.Message))); 335 } 336 } 337 338 #endregion 339 } 340 }
以下是类AlifSerialPortBaseClass.cs:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace AlifCoSerialPort 8 { 9 /// <summary> 10 /// Alif串口(初始化之后一定要调用Run方法) 11 /// </summary> 12 public class AlifSerialPort : Base 13 { 14 #region 属性 15 16 /// <summary> 17 /// 串口列表 18 /// </summary> 19 private List<Port> _listPort = null; 20 21 /// <summary> 22 /// 串口列表 23 /// </summary> 24 public List<Port> ListPort 25 { 26 get { return this._listPort; } 27 set { this._listPort = value; } 28 } 29 30 /// <summary> 31 /// 32 /// </summary> 33 private List<AlifSerialPortBaseClass> _listAlifSerialPortBaseClass = null; 34 35 /// <summary> 36 /// 37 /// </summary> 38 public List<AlifSerialPortBaseClass> ListAlifSerialPortBaseClass 39 { 40 get { return this._listAlifSerialPortBaseClass; } 41 set { this._listAlifSerialPortBaseClass = value; } 42 } 43 44 public delegate void _delegateSendMsg(Common.Msg msg); 45 46 public _delegateSendMsg sendMsgEvent; 47 48 /// <summary> 49 /// 监视线程超时时间 50 /// </summary> 51 private int _monitorThreadTimeout = 1000; 52 53 /// <summary> 54 /// 55 /// </summary> 56 public int MonitorThreadTimeout 57 { 58 get { return this._monitorThreadTimeout; } 59 set { this._monitorThreadTimeout = value; } 60 } 61 62 /// <summary> 63 /// 是否线程监视 64 /// </summary> 65 private bool _boolThreadMonitor = true; 66 67 /// <summary> 68 /// 是否线程监视 69 /// </summary> 70 public bool BoolThreadMonitor 71 { 72 get { return this._boolThreadMonitor; } 73 set { this._boolThreadMonitor = value; } 74 } 75 76 #endregion 77 78 /// <summary> 79 /// 构造函数 80 /// </summary> 81 public AlifSerialPort() { } 82 83 /// <summary> 84 /// 构造函数 85 /// </summary> 86 public AlifSerialPort(_delegateSendMsg sendMsgEvent) 87 { 88 this.sendMsgEvent = sendMsgEvent; 89 } 90 91 /// <summary> 92 /// 93 /// </summary> 94 private void ThreadMonitorSerialPortStatus() 95 { 96 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 97 Common.MsgLevel.Information, 98 "监视串口状态线程已启动,即将要监视串口状态......")); 99 while (true) 100 { 101 try 102 { 103 if (this.BoolThreadMonitor) 104 { 105 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 106 { 107 108 int flag = 0; 109 foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) 110 { 111 if (s == alifSerialPortBaseClass.port.portName) 112 { 113 flag++; 114 } 115 } 116 117 if (flag == 0) 118 { 119 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 120 Common.MsgLevel.Error, 121 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,请检查串口线......")); 122 alifSerialPortBaseClass.InitSerialPortConnection(); 123 } 124 125 if (alifSerialPortBaseClass.serialPort == null || !alifSerialPortBaseClass.IsOpen()) 126 { 127 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 128 Common.MsgLevel.Error, 129 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,线程正在启动此串口......")); 130 131 alifSerialPortBaseClass.InitSerialPortConnection(); 132 } 133 else 134 { 135 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 136 Common.MsgLevel.Information, 137 "串口" + alifSerialPortBaseClass.port.Details() + " 线程监听此串口正常!!!")); 138 } 139 } 140 } 141 } 142 catch (Exception ex) 143 { 144 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 145 Common.MsgLevel.Exception, 146 "线程监视串口状态发生错误,错误原因:" + ex.Message)); 147 } 148 149 Thread.Sleep(this._monitorThreadTimeout); 150 } 151 } 152 153 /// <summary> 154 /// 构造函数 155 /// </summary> 156 /// <param name="listPort"></param> 157 public AlifSerialPort(List<Port> listPort, _delegateSendMsg sendMsgEvent) 158 { 159 this.ListPort = listPort; 160 this.sendMsgEvent = sendMsgEvent; 161 } 162 163 #region 公共方法 164 165 /// <summary> 166 /// 添加串口 167 /// </summary> 168 /// <param name="port"></param> 169 public void AddPort(Port port) 170 { 171 if (this.ListPort == null) 172 { 173 this.ListPort = new List<Port>(); 174 } 175 176 this.ListPort.Add(port); 177 } 178 179 /// <summary> 180 /// 运行串口 181 /// </summary> 182 public void Run() 183 { 184 Listen(); 185 186 CreateAndStartThread(this._thread, ThreadMonitorSerialPortStatus); 187 } 188 189 /// <summary> 190 /// 191 /// </summary> 192 private void Listen() 193 { 194 try 195 { 196 List<AlifSerialPortBaseClass> list = new List<AlifSerialPortBaseClass>(); 197 198 if (this.ListPort.Count == 0) 199 { 200 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 201 Common.MsgLevel.Error, 202 "没有串口可以监听,请添加串口!!!")); 203 } 204 205 foreach (Port port in this.ListPort) 206 { 207 port.portName = port.portName.ToUpper().Replace("COM", ""); 208 209 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 210 Common.MsgLevel.Information, 211 "正在监听串口:" + port.Details())); 212 213 AlifSerialPortBaseClass alifSerialPortBaseClass = new AlifSerialPortBaseClass(port); 214 215 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 216 Common.MsgLevel.Information, 217 "监听串口:" + port.Details() + "成功!!!")); 218 219 list.Add(alifSerialPortBaseClass); 220 } 221 222 this.ListAlifSerialPortBaseClass = list; 223 } 224 catch (Exception ex) 225 { 226 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 227 Common.MsgLevel.Exception, 228 "监听串口发生错误,错误原因:" + ex.Message)); 229 } 230 } 231 232 /// <summary> 233 /// 发送消息 234 /// </summary> 235 /// <param name="msg">消息内容</param> 236 private void SendMsg(Common.Msg msg) 237 { 238 if (this.sendMsgEvent != null) 239 { 240 this.sendMsgEvent(msg); 241 } 242 } 243 244 /// <summary> 245 /// 获取计算机串口名称 246 /// </summary> 247 /// <returns></returns> 248 public string[] GetSerialPortNames() 249 { 250 return System.IO.Ports.SerialPort.GetPortNames(); 251 } 252 253 /// <summary> 254 /// 初始化串口 255 /// </summary> 256 /// <param name="port"></param> 257 public void InitSerialPort(Port port) 258 { 259 260 } 261 262 /// <summary> 263 /// 发送数据 264 /// </summary> 265 /// <param name="port"></param> 266 /// <param name="bytes"></param> 267 public void SendData(Port port, byte[] bytes) 268 { 269 try 270 { 271 int flag = 0; 272 273 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 274 { 275 if (alifSerialPortBaseClass.port.portName == port.portName) 276 { 277 flag++; 278 alifSerialPortBaseClass.SendData(bytes); 279 } 280 } 281 282 if (flag == 0) 283 { 284 throw new Exception(string.Format(@"没有指定的串口!!!")); 285 } 286 287 } 288 catch (Exception ex) 289 { 290 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 291 Common.MsgLevel.Exception, 292 string.Format(@"往串口[0]发送数据发送失败,失败原因:{1}", port.Details(), ex.Message))); 293 } 294 } 295 296 /// <summary> 297 /// 设置参数 298 /// </summary> 299 /// <param name="port"></param> 300 public void SetParameters(Port port) 301 { 302 303 } 304 305 /// <summary> 306 /// 关闭串口 307 /// </summary> 308 /// <param name="port"></param> 309 public void Close(Port port) 310 { 311 try 312 { 313 int flag = 0; 314 315 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 316 { 317 if (alifSerialPortBaseClass.port.portName == port.portName) 318 { 319 flag++; 320 alifSerialPortBaseClass.Close(); 321 } 322 } 323 324 if (flag == 0) 325 { 326 throw new Exception(string.Format(@"没有指定的串口!!!")); 327 } 328 329 } 330 catch (Exception ex) 331 { 332 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 333 Common.MsgLevel.Exception, 334 string.Format(@"关闭串口[0]失败,失败原因:{1}", port.Details(), ex.Message))); 335 } 336 } 337 338 #endregion 339 } 340 }
以下是类Base.cs:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace AlifCoSerialPort 8 { 9 /// <summary> 10 /// Alif串口(初始化之后一定要调用Run方法) 11 /// </summary> 12 public class AlifSerialPort : Base 13 { 14 #region 属性 15 16 /// <summary> 17 /// 串口列表 18 /// </summary> 19 private List<Port> _listPort = null; 20 21 /// <summary> 22 /// 串口列表 23 /// </summary> 24 public List<Port> ListPort 25 { 26 get { return this._listPort; } 27 set { this._listPort = value; } 28 } 29 30 /// <summary> 31 /// 32 /// </summary> 33 private List<AlifSerialPortBaseClass> _listAlifSerialPortBaseClass = null; 34 35 /// <summary> 36 /// 37 /// </summary> 38 public List<AlifSerialPortBaseClass> ListAlifSerialPortBaseClass 39 { 40 get { return this._listAlifSerialPortBaseClass; } 41 set { this._listAlifSerialPortBaseClass = value; } 42 } 43 44 public delegate void _delegateSendMsg(Common.Msg msg); 45 46 public _delegateSendMsg sendMsgEvent; 47 48 /// <summary> 49 /// 监视线程超时时间 50 /// </summary> 51 private int _monitorThreadTimeout = 1000; 52 53 /// <summary> 54 /// 55 /// </summary> 56 public int MonitorThreadTimeout 57 { 58 get { return this._monitorThreadTimeout; } 59 set { this._monitorThreadTimeout = value; } 60 } 61 62 /// <summary> 63 /// 是否线程监视 64 /// </summary> 65 private bool _boolThreadMonitor = true; 66 67 /// <summary> 68 /// 是否线程监视 69 /// </summary> 70 public bool BoolThreadMonitor 71 { 72 get { return this._boolThreadMonitor; } 73 set { this._boolThreadMonitor = value; } 74 } 75 76 #endregion 77 78 /// <summary> 79 /// 构造函数 80 /// </summary> 81 public AlifSerialPort() { } 82 83 /// <summary> 84 /// 构造函数 85 /// </summary> 86 public AlifSerialPort(_delegateSendMsg sendMsgEvent) 87 { 88 this.sendMsgEvent = sendMsgEvent; 89 } 90 91 /// <summary> 92 /// 93 /// </summary> 94 private void ThreadMonitorSerialPortStatus() 95 { 96 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 97 Common.MsgLevel.Information, 98 "监视串口状态线程已启动,即将要监视串口状态......")); 99 while (true) 100 { 101 try 102 { 103 if (this.BoolThreadMonitor) 104 { 105 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 106 { 107 108 int flag = 0; 109 foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) 110 { 111 if (s == alifSerialPortBaseClass.port.portName) 112 { 113 flag++; 114 } 115 } 116 117 if (flag == 0) 118 { 119 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 120 Common.MsgLevel.Error, 121 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,请检查串口线......")); 122 alifSerialPortBaseClass.InitSerialPortConnection(); 123 } 124 125 if (alifSerialPortBaseClass.serialPort == null || !alifSerialPortBaseClass.IsOpen()) 126 { 127 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 128 Common.MsgLevel.Error, 129 "串口" + alifSerialPortBaseClass.port.Details() + " 没有正常运行,线程正在启动此串口......")); 130 131 alifSerialPortBaseClass.InitSerialPortConnection(); 132 } 133 else 134 { 135 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 136 Common.MsgLevel.Information, 137 "串口" + alifSerialPortBaseClass.port.Details() + " 线程监听此串口正常!!!")); 138 } 139 } 140 } 141 } 142 catch (Exception ex) 143 { 144 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 145 Common.MsgLevel.Exception, 146 "线程监视串口状态发生错误,错误原因:" + ex.Message)); 147 } 148 149 Thread.Sleep(this._monitorThreadTimeout); 150 } 151 } 152 153 /// <summary> 154 /// 构造函数 155 /// </summary> 156 /// <param name="listPort"></param> 157 public AlifSerialPort(List<Port> listPort, _delegateSendMsg sendMsgEvent) 158 { 159 this.ListPort = listPort; 160 this.sendMsgEvent = sendMsgEvent; 161 } 162 163 #region 公共方法 164 165 /// <summary> 166 /// 添加串口 167 /// </summary> 168 /// <param name="port"></param> 169 public void AddPort(Port port) 170 { 171 if (this.ListPort == null) 172 { 173 this.ListPort = new List<Port>(); 174 } 175 176 this.ListPort.Add(port); 177 } 178 179 /// <summary> 180 /// 运行串口 181 /// </summary> 182 public void Run() 183 { 184 Listen(); 185 186 CreateAndStartThread(this._thread, ThreadMonitorSerialPortStatus); 187 } 188 189 /// <summary> 190 /// 191 /// </summary> 192 private void Listen() 193 { 194 try 195 { 196 List<AlifSerialPortBaseClass> list = new List<AlifSerialPortBaseClass>(); 197 198 if (this.ListPort.Count == 0) 199 { 200 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 201 Common.MsgLevel.Error, 202 "没有串口可以监听,请添加串口!!!")); 203 } 204 205 foreach (Port port in this.ListPort) 206 { 207 port.portName = port.portName.ToUpper().Replace("COM", ""); 208 209 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 210 Common.MsgLevel.Information, 211 "正在监听串口:" + port.Details())); 212 213 AlifSerialPortBaseClass alifSerialPortBaseClass = new AlifSerialPortBaseClass(port); 214 215 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 216 Common.MsgLevel.Information, 217 "监听串口:" + port.Details() + "成功!!!")); 218 219 list.Add(alifSerialPortBaseClass); 220 } 221 222 this.ListAlifSerialPortBaseClass = list; 223 } 224 catch (Exception ex) 225 { 226 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 227 Common.MsgLevel.Exception, 228 "监听串口发生错误,错误原因:" + ex.Message)); 229 } 230 } 231 232 /// <summary> 233 /// 发送消息 234 /// </summary> 235 /// <param name="msg">消息内容</param> 236 private void SendMsg(Common.Msg msg) 237 { 238 if (this.sendMsgEvent != null) 239 { 240 this.sendMsgEvent(msg); 241 } 242 } 243 244 /// <summary> 245 /// 获取计算机串口名称 246 /// </summary> 247 /// <returns></returns> 248 public string[] GetSerialPortNames() 249 { 250 return System.IO.Ports.SerialPort.GetPortNames(); 251 } 252 253 /// <summary> 254 /// 初始化串口 255 /// </summary> 256 /// <param name="port"></param> 257 public void InitSerialPort(Port port) 258 { 259 260 } 261 262 /// <summary> 263 /// 发送数据 264 /// </summary> 265 /// <param name="port"></param> 266 /// <param name="bytes"></param> 267 public void SendData(Port port, byte[] bytes) 268 { 269 try 270 { 271 int flag = 0; 272 273 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 274 { 275 if (alifSerialPortBaseClass.port.portName == port.portName) 276 { 277 flag++; 278 alifSerialPortBaseClass.SendData(bytes); 279 } 280 } 281 282 if (flag == 0) 283 { 284 throw new Exception(string.Format(@"没有指定的串口!!!")); 285 } 286 287 } 288 catch (Exception ex) 289 { 290 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 291 Common.MsgLevel.Exception, 292 string.Format(@"往串口[0]发送数据发送失败,失败原因:{1}", port.Details(), ex.Message))); 293 } 294 } 295 296 /// <summary> 297 /// 设置参数 298 /// </summary> 299 /// <param name="port"></param> 300 public void SetParameters(Port port) 301 { 302 303 } 304 305 /// <summary> 306 /// 关闭串口 307 /// </summary> 308 /// <param name="port"></param> 309 public void Close(Port port) 310 { 311 try 312 { 313 int flag = 0; 314 315 foreach (AlifSerialPortBaseClass alifSerialPortBaseClass in this.ListAlifSerialPortBaseClass) 316 { 317 if (alifSerialPortBaseClass.port.portName == port.portName) 318 { 319 flag++; 320 alifSerialPortBaseClass.Close(); 321 } 322 } 323 324 if (flag == 0) 325 { 326 throw new Exception(string.Format(@"没有指定的串口!!!")); 327 } 328 329 } 330 catch (Exception ex) 331 { 332 SendMsg(Common.CommonFunction.SendMsg(Common.InterfaceLocation.ComInterface, 333 Common.MsgLevel.Exception, 334 string.Format(@"关闭串口[0]失败,失败原因:{1}", port.Details(), ex.Message))); 335 } 336 } 337 338 #endregion 339 } 340 }
以下是类Port.cs:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.IO.Ports; 4 using System.Linq; 5 using System.Text; 6 7 namespace AlifCoSerialPort 8 { 9 /// <summary> 10 /// 串口 11 /// </summary> 12 public class Port 13 { 14 #region 属性 15 16 /// <summary> 17 /// 设备编号 18 /// </summary> 19 private string _deviceID = "0"; 20 21 /// <summary> 22 /// 设备编号 23 /// </summary> 24 public string DeviceID 25 { 26 get { return this._deviceID; } 27 set { this._deviceID = value; } 28 } 29 30 private string _portName = "COM0"; 31 32 /// <summary> 33 /// 端口名称 34 /// </summary> 35 public string portName 36 { 37 get { return this._portName; } 38 set 39 { 40 this._portName = "COM" + value.ToUpper().Replace("COM", ""); 41 } 42 } 43 44 private string _baudRate = "9600"; 45 46 /// <summary> 47 /// 波特率 48 /// </summary> 49 public string baudRate 50 { 51 52 get { return this._baudRate; } 53 set { this._baudRate = value; } 54 } 55 56 private string _parity = "0"; 57 58 /// <summary> 59 /// 奇偶校验位 60 /// </summary> 61 public string parity 62 { 63 get { return this._parity; } 64 set { this._parity = value; } 65 } 66 67 private string _dataBits = "8"; 68 69 /// <summary> 70 /// 数据位 71 /// </summary> 72 public string dataBits 73 { 74 get { return this._dataBits; } 75 set { this._dataBits = value; } 76 } 77 78 private string _stopBits = "1"; 79 80 /// <summary> 81 /// 停止位 82 /// </summary> 83 public string stopBits 84 { 85 get { return this._stopBits; } 86 set { this._stopBits = value; } 87 } 88 89 private string _readTimeout = "-1"; 90 91 /// <summary> 92 /// 读取操作未完成时发生超时之前的毫秒数 93 /// </summary> 94 public string readTimeout 95 { 96 get { return this._readTimeout; } 97 set { this._readTimeout = value; } 98 } 99 100 private string _writeTimeout = "-1"; 101 102 /// <summary> 103 /// 写入操作未完成时发生超时之前的毫秒数 104 /// </summary> 105 public string writeTimeout 106 { 107 get { return this._writeTimeout; } 108 set { this._writeTimeout = value; } 109 } 110 111 /// <summary> 112 /// 113 /// </summary> 114 private string _discardInBuffer = "true"; 115 116 /// <summary> 117 /// 丢弃来自串行驱动程序的接收缓冲区的数据 118 /// </summary> 119 public string discardInBuffer 120 { 121 get { return this._discardInBuffer; } 122 set { this._discardInBuffer = value; } 123 } 124 125 private string _discardOutBuffer = "true"; 126 127 /// <summary> 128 /// 丢弃来自串行驱动程序的传输缓冲区的数据 129 /// </summary> 130 public string discardOutBuffer 131 { 132 get { return this._discardOutBuffer; } 133 set { this._discardOutBuffer = value; } 134 } 135 136 public string _WriteOffset = "0"; 137 138 /// <summary> 139 /// 写数据偏移量 140 /// </summary> 141 public string WriteOffset 142 { 143 get { return this._WriteOffset; } 144 set { this._WriteOffset = value; } 145 } 146 147 private string _ReadOffset = "0"; 148 149 /// <summary> 150 /// 读数据偏移量 151 /// </summary> 152 public string ReadOffset 153 { 154 get { return this._ReadOffset; } 155 set { this._ReadOffset = value; } 156 } 157 158 private string _dataReceivedBufferLength = "1024"; 159 160 /// <summary> 161 /// 数据接收缓冲区大小 162 /// </summary> 163 public string DataReceivedBufferLength 164 { 165 get { return this._dataReceivedBufferLength; } 166 set { this._dataReceivedBufferLength = value; } 167 } 168 169 /// <summary> 170 /// 设置属性值 171 /// </summary> 172 /// <param name="name">名称</param> 173 /// <param name="value">值</param> 174 public void SetAttributeValue(string name, string value) 175 { 176 switch (name) 177 { 178 case "DeviceID"://设备编号 179 this.DeviceID = value; 180 break; 181 case "portName"://端口名称 182 this.portName = value; 183 break; 184 case "baudRate"://波特率 185 this.baudRate = value; 186 break; 187 case "parity"://奇偶校验位 188 this.parity = value; 189 break; 190 case "dataBits"://数据位 191 this.dataBits = value; 192 break; 193 case "stopBits"://停止位 194 this.stopBits = value; 195 break; 196 case "readTimeout"://读取操作未完成时发生超时之前的毫秒数 197 this.readTimeout = value; 198 break; 199 case "writeTimeout"://写入操作未完成时发生超时之前的毫秒数 200 this.writeTimeout = value; 201 break; 202 case "discardInBuffer"://丢弃来自串行驱动程序的接收缓冲区的数据 203 this.discardInBuffer = value; 204 break; 205 case "discardOutBuffer"://丢弃来自串行驱动程序的传输缓冲区的数据 206 this.discardOutBuffer = value; 207 break; 208 case "WriteOffset"://写数据偏移量 209 this.WriteOffset = value; 210 break; 211 case "ReadOffset"://读数据偏移量 212 this.ReadOffset = value; 213 break; 214 case "DataReceivedBufferLength"://数据接收缓冲区大小 215 this.DataReceivedBufferLength = value; 216 break; 217 default: 218 break; 219 } 220 } 221 222 /// <summary> 223 /// 接收数据委托事件 224 /// </summary> 225 public AlifSerialPortBaseClass._delegateSerialReveivedData serialReveivedDataEvent; 226 227 /// <summary> 228 /// 错误委托事件 229 /// </summary> 230 public AlifSerialPortBaseClass._delegateSerialErrorReceived serialErrorReceivedEvent; 231 232 /// <summary> 233 /// 串行管脚更改委托事件 234 /// </summary> 235 public AlifSerialPortBaseClass._delegateSerialPinChanged serialPinChangedEvent; 236 237 /// <summary> 238 /// 释放委托事件 239 /// </summary> 240 public AlifSerialPortBaseClass._delegateDisposed disposedEvent; 241 242 public AlifSerialPortBaseClass._delegateSerialExceptionMsg serialExceptionMsgEvent; 243 244 public AlifSerialPortBaseClass._delegateSerialLogMsg serialLogMsgEvent; 245 246 #endregion 247 248 /// <summary> 249 /// 获取串口信息 250 /// </summary> 251 /// <returns></returns> 252 public string Details() 253 { 254 StringBuilder sb = new StringBuilder(); 255 256 sb.Append("【"); 257 sb.Append("端口名称:" + this.portName); 258 sb.Append(",波特率:" + this.baudRate); 259 sb.Append(",奇偶校验位:" + this.parity); 260 sb.Append(",数据位:" + this.dataBits); 261 sb.Append(",停止位:" + this.stopBits); 262 sb.Append("】"); 263 //sb.Append(",读取操作未完成时发生超时之前的毫秒数:" + this.readTimeout); 264 //sb.AppendLine(",写入操作未完成时发生超时之前的毫秒数:" + this.writeTimeout); 265 266 return sb.ToString(); 267 } 268 269 /// <summary> 270 /// 设置停止位(StopBits) 271 272 /// </summary> 273 /// <param name="value">只能是0:StopBits.None 1:StopBits.One 2:StopBits.Two 3:StopBits.OnePointFive 里面的数字,不然抛出异常</param> 274 public void SetStopBits(int value) 275 { 276 StopBits temp = StopBits.One; 277 278 switch (value) 279 { 280 case 0: 281 temp = StopBits.None; 282 break; 283 case 1: 284 temp = StopBits.One; 285 break; 286 case 2: 287 temp = StopBits.Two; 288 break; 289 case 3: 290 temp = StopBits.OnePointFive; 291 break; 292 default: 293 throw new Exception("设置停止位(StopBits)只能是0:StopBits.None 1:StopBits.One 2:StopBits.Two 3:StopBits.OnePointFive 里面的数字,不然抛出异常"); 294 } 295 296 this.stopBits = temp.ToString(); 297 } 298 299 /// <summary> 300 /// 设置奇偶校验位 301 302 /// </summary> 303 /// <param name="value">奇偶校验位只能是0,1,2,3,4里面的值</param> 304 public void SetParity(int value) 305 { 306 Parity tem = Parity.None; 307 308 switch (value) 309 { 310 case 0: 311 tem = Parity.None; 312 break; 313 case 1: 314 tem = Parity.Odd; 315 break; 316 case 2: 317 tem = Parity.Even; 318 break; 319 case 3: 320 tem = Parity.Mark; 321 break; 322 case 4: 323 tem = Parity.Space; 324 break; 325 default: 326 throw new Exception("奇偶校验位只能是0,1,2,3,4里面的值"); 327 } 328 329 this.parity = tem.ToString(); 330 } 331 } 332 }