C#对于处理window操作系统下的设备有天然的优势,对于大多数设备读写等操作来说基本上够了,这里只讨论通过普通的大多数的设备的操作。涉及到两大类SerialPort类,Socket的一些操作。不一定好,但希望分享出去,让更多的人受益。。
由于设备的读写方式不同,串口,网口,usb,等各种各样不同的方式,所以对外的操作,可能就达不到统一,没法集中处理,造成很大程度代码冗余,会给维护带来很大不便。需要一个父类来对不同操作进行统一的一个约束,同时可以对外有一个统一的j接口,方便业务上边的一些处理。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace EquipmentOption 7 { 8 public abstract class Equipment 9 { 10 11 /// <summary> 12 /// 读取到的Code 13 /// </summary> 14 public string Code; 15 /// <summary> 16 /// 错误消息 17 /// </summary> 18 public string Error = string.Empty; 19 public BaseEquipment EquipmentModel; 20 21 public int ReadTimeOut=500; 22 public Equipment(BaseEquipment Model) 23 { 24 this.EquipmentModel = Model; 25 } 26 /// <summary> 27 /// 扫描事件 28 /// </summary> 29 private int scanning; 30 public int Scanning 31 { 32 get 33 { 34 return this.scanning; 35 } 36 set 37 { 38 this.scanning = value; 39 EquipmentArgs e = new EquipmentArgs(this.Code, this.Error); 40 OnSetVelues(e); 41 } 42 } 43 public event SetEventHandler SetEvent; 44 public delegate void SetEventHandler(object sender, EquipmentArgs e); 45 public class EquipmentArgs : EventArgs 46 { 47 public string Code; 48 public string Error; 49 public EquipmentArgs(string SnCode,string error) 50 { 51 this.Code = SnCode; 52 this.Error = error; 53 } 54 } 55 public void OnSetVelues(EquipmentArgs e) 56 { 57 if (this.SetEvent != null) 58 { 59 this.SetEvent(this, e); 60 } 61 } 62 /// <summary> 63 /// 检测设备 64 /// </summary> 65 /// <param name="message">错误消息返回值,仅当返回false才有值</param> 66 /// <returns></returns> 67 public abstract bool test(out string message); 68 /// <summary> 69 /// 给设备发送指令 70 /// </summary> 71 /// <param name="command">指令内容</param> 72 /// <param name="type">指令类型</param> 73 /// <returns></returns> 74 public abstract string SendMessage(String command, CommandType type); 75 } 76 77 }