C#对于处理window操作系统下的设备有天然的优势,对于大多数设备读写等操作来说基本上够了,这里只讨论通过普通的大多数的设备的操作。涉及到两大类SerialPort类,Socket的一些操作。不一定好,但希望分享出去,让更多的人受益。。

由于设备的读写方式不同,串口,网口,usb,等各种各样不同的方式,所以对外的操作,可能就达不到统一,没法集中处理,造成很大程度代码冗余,会给维护带来很大不便。需要一个父类来对不同操作进行统一的一个约束,同时可以对外有一个统一的j接口,方便业务上边的一些处理。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace EquipmentOption
{
public abstract class Equipment
{ /// <summary>
/// 读取到的Code
/// </summary>
public string Code;
/// <summary>
/// 错误消息
/// </summary>
public string Error = string.Empty;
public BaseEquipment EquipmentModel; public int ReadTimeOut=;
public Equipment(BaseEquipment Model)
{
this.EquipmentModel = Model;
}
/// <summary>
/// 扫描事件
/// </summary>
private int scanning;
public int Scanning
{
get
{
return this.scanning;
}
set
{
this.scanning = value;
EquipmentArgs e = new EquipmentArgs(this.Code, this.Error);
OnSetVelues(e);
}
}
public event SetEventHandler SetEvent;
public delegate void SetEventHandler(object sender, EquipmentArgs e);
public class EquipmentArgs : EventArgs
{
public string Code;
public string Error;
public EquipmentArgs(string SnCode,string error)
{
this.Code = SnCode;
this.Error = error;
}
}
public void OnSetVelues(EquipmentArgs e)
{
if (this.SetEvent != null)
{
this.SetEvent(this, e);
}
}
/// <summary>
/// 检测设备
/// </summary>
/// <param name="message">错误消息返回值,仅当返回false才有值</param>
/// <returns></returns>
public abstract bool test(out string message);
/// <summary>
/// 给设备发送指令
/// </summary>
/// <param name="command">指令内容</param>
/// <param name="type">指令类型</param>
/// <returns></returns>
public abstract string SendMessage(String command, CommandType type);
} }

父类里边主要定义了一些公用的属性,以及一个简单的事件转发。这个事件转发用于统一网口设备和串口设备的获取数据方式

调用方式如下:

        private void Form1_Load(object sender, EventArgs e)
{
Equipment Comquip = new ComEquipment(new BaseEquipment());
Comquip.SetEvent += Equipment_GetCodeEvent;
Equipment IPEquip = new IPEquipment(new BaseEquipment());
IPEquip.SetEvent += Equipment_GetCodeEvent;
}
void Equipment_GetCodeEvent(object sender, Equipment.EquipmentArgs e)
{
string code = e.Code;//这里的Code就是从设备中读取到的值
}

可以把需要用到的基础消息丢到baseEquipment中用来初始化对应的设备,然后,把对于设备读取到的信息就是这里的e.code。不管网口串口都是一样的返回.

设备的操作无非读写

对于用串口连接的设备:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace EquipmentOption
{
public class ComEquipment : Equipment
{
private SerialPort Port;
public ComEquipment(BaseEquipment baseModel) :
base(baseModel)
{
this.Port = new SerialPort(baseModel.Port);
Port.BaudRate = baseModel.BaudRate;
Port.StopBits = (StopBits)baseModel.StopBit;
Port.Parity = (Parity)baseModel.ParityCheck;
this.Port.DataReceived += Port_DataReceived;
}
//事件转发
void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(this.EquipmentModel.SleepTime);
this.Error = string.Empty;
this.Code = string.Empty;
try
{
switch (this.EquipmentModel.ReadType)
{
case :
this.Code = (sender as SerialPort).ReadLine();
break;
case :
this.Code = (sender as SerialPort).ReadExisting();
break;
default:
Error = string.Concat(this.EquipmentModel.EquipmentName, "读取有误");
break;
}
++this.Scanning;//这里切记是属性值变化才会触发事件 }
catch
{
Error = string.Concat(this.EquipmentModel.EquipmentName, "配置错误,请调整");
}
} /// <summary>
/// 检测
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public override bool test(out string message)
{
message = "";
bool result = false;
if (this.Port != null)
{
try
{
Port.Open();
result = true;
}
catch
{
message = string.Concat("设备", this.EquipmentModel.EquipmentName, "异常");
result = false;
}
finally
{
if (Port.IsOpen)
{
Port.Close();
}
}
}
else
{
message = string.Concat("设备", this.EquipmentModel.EquipmentName, "初始化失败");
result = false;
}
return result;
}
/// <summary>
/// 发送命令
/// </summary>
/// <param name="command">命令</param>
public override string SendMessage(String command, CommandType type)
{
if (!String.IsNullOrEmpty(command) && this.Port.IsOpen)
{
switch (type)
{
case CommandType.GetBytes:
Byte[] commandsGetBytes = CommandConvert.CommandByGetBytes(command);
this.Port.Write(commandsGetBytes, , commandsGetBytes.Length);
break;
case CommandType.Command16:
Byte[] commands16 = CommandConvert.CommandFrom16(command);
this.Port.Write(commands16, , commands16.Length);
break;
case CommandType.Command10:
Byte[] commands10 = CommandConvert.CommandFrom10(command);
this.Port.Write(commands10, , commands10.Length);
break;
case CommandType.CommandText:
this.Port.Write(command);
break;
}
return this.Port.PortName + "发送数据:" + command;
}
else
{
return "串口" + this.Port.PortName + "未打开";
}
}
}
}

对于用网口连接的设备:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading; namespace EquipmentOption
{
public class IPEquipment : Equipment
{
private IPEndPoint IPPort;
private IPAddress IP;
public IPEquipment(BaseEquipment baseModel) :
base(baseModel)
{
int Port = ;
if (int.TryParse(baseModel.Port, out Port))
{
this.IP = IPAddress.Parse(baseModel.IPAddress);
this.IPPort = new IPEndPoint(IP, Port);
Thread t = new Thread(new ParameterizedThreadStart(ScanEvent));
t.Start(IPPort);
}
} public override bool test(out string message)
{
bool result = false; message = "";
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 创建Socket
try
{
c.SendTimeout = ;
c.Connect(IPPort); //连接到服务器
result = true;
}
catch
{
message =string.Concat("设备" , this.EquipmentModel.EquipmentName , "异常");
result = false;
}
finally
{
c.Close();
}
return result;
}
public void ScanEvent(object ipe)
{
while (true)
{
try
{
//创建Socket并连接到服务器
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 创建Socket
c.Connect((IPEndPoint)ipe); //连接到服务器
//接受从服务器返回的信息
byte[] recvBytes = new byte[];
int bytes;
//bytes = c.Receive(recvBytes, recvBytes.Length, 0); //从服务器端接受返回信息
bytes = c.Receive(recvBytes);
string Code = Encoding.Default.GetString(recvBytes, , bytes);
Code = Code.Replace(EquipmentModel.Suffix, "");
this.Code = Code;
c.Close();
++this.Scanning;
}
catch(Exception ex)
{
Error = ex.ToString();
continue;
}
}
} public override string SendMessage(string command, CommandType type)
{
//new mothed to SendMessage;
return "";
}
}
}

对于扩展而言,需要做的仅仅是不同类别的设备再增加不同的子类去继承抽象类.

C#设备处理类操作的更多相关文章

  1. 在Android下通过ExifInterface类操作图片的Exif信息

    什么是Exif 先来了解什么是Exif.Exif是一种图像文件格式,它的数据存储于JPEG格式是完全相同的,实际上Exif格式就是JPEG格式头插入了 数码照片的信息,包括拍摄的光圈.快门.平衡白.I ...

  2. HTML5 01. 布局、语义化标签、智能化表单、表单元素/标签/属性/事件、多媒体、类操作、自定义属性

    1.知识点 lang = “en”   所用语言是英文 文档结构更简洁 IE8一下不支持h5c3 书写更宽松 div没有语义 标签语义化:在合适的地方使用合适的标签 对seo优化友谊 网页经典布局 页 ...

  3. 谢欣伦 - OpenDev原创教程 - 设备查找类CxDeviceFind & CxDeviceMapFind

    这是一个精练的设备查找类,类名.函数名和变量名均采用匈牙利命名法.小写的x代表我的姓氏首字母(谢欣伦),个人习惯而已,如有雷同,纯属巧合. CxDeviceFind的使用如下: void CUsbSc ...

  4. Arrays 类操作 Java 的数组排序

    使用 Arrays 类操作 Java 中的数组 Arrays 类是 Java 中提供的一个工具类,在 java.util 包中.该类中包含了一些方法用来直接操作数组,比如可直接实现数组的排序.搜索等( ...

  5. .net使用SqlBulkCopy类操作DataTable批量插入数据库数据,然后分页查询坑

    在使用SqlBulkCopy类操作DataTable批量插入数据,这种操作插入数据的效率很高,就会导致每一条数据在保存的时间基本一样,在我们分页查询添加的数据是,使用数据的添加时间来排序就会出现每页的 ...

  6. 移动设备检测类Mobile_Detect.php

    移动设备检测类Mobile_Detect.php http://mobiledetect.net/ 分类:PHP 时间:2015年11月28日 Mobile_Detect.php是一个轻量级的开源移动 ...

  7. PDF.NET数据开发框架实体类操作实例

    PDF.NET数据开发框架实体类操作实例(MySQL)的姊妹篇,两者使用了同一个测试程序,不同的只是使用的类库和数据库不同,下面说说具体的使用过程. 1,首先在App.config文件中配置数据库连接 ...

  8. iostat相关参数说明——await:平均每次设备I/O操作的等待时间 (毫秒),如果%util接近 100%,说明产生的I/O请求太多

    iostat是I/O statistics(输入/输出统计)的缩写,iostat工具将对系统的磁盘操作活动进行监视.它的特点是汇报磁盘活动统计情况,同时也会汇报出 CPU使用情况.同vmstat一样, ...

  9. 使用File类操作文件或目录的属性

    在学I/O流之前,我先总结一下使用File类操作文件或目录的属性. package com.File; import java.io.File; import java.io.IOException; ...

随机推荐

  1. CSS常用渐变

    边框渐变: border-image: -webkit-linear-gradient( red , blue) 30 30; border-image: -moz-linear-gradient( ...

  2. JavaScript学习笔记5 之 计时器 & scroll、offset、client系列属性 & 图片无缝滚动

    一.计时器 setInterval ( 函数/名称 , 毫秒数 )表示每经过一定的毫秒后,执行一次相应的函数(重复) setTimeout ( 函数/名称 , 毫秒数 ) 表示经过一定的毫秒后,只执行 ...

  3. 错误:当你使用id作为sharepoint的自定义页面的查询参数时,总会提示项目不存在!

    No item exists at http://SERVER/SITE/mypage.aspx?ID=1. It may have been deleted or renamed by anothe ...

  4. jQuery解决iframe高度自适应代码

    网上查了好多用着都不行,自己搞定了:在包含iframe的页面中加入以下脚本,基本思想是在iframe加载内容后重新设置高度,下面代码尽在IE6中用过,没在其他浏览器中测试. 代码如下: <scr ...

  5. GitHub + VSTS 开源代码双向同步

    GitHub已经是全球开源代码的大本营了,通过以下统计你可以看到仅仅javascript在github就有超过32万个活动的repo.很多开发人员都会把自己的一部分代码分享到github上进行开源,一 ...

  6. Yii2 vendor出现bower-asset这么解决

    yii\base\InvalidParamException: The file or directory to be published does not exist: /data/wwwroot/ ...

  7. monkey之monkey命令详解

    四大类-- 常用选项.事件选项.约束选项.调试选项 1.常用选项 --help:打印帮助信息 -v:指定打印信息的详细级别,一个-v增加一个级别 ,默认级别为 0 .用于指定反馈信息级别(信息级别就是 ...

  8. wamp下Apache配置vhost

    1.由于后面虚拟机中需要用到Rewrite所以先编辑Apache的conf目录下的httpd.conf文件.(我的文件位置是:D:\Program Files\wamp\bin\apache\apac ...

  9. XIB——AutoLayout添加约束

    仿QQ登录界面: 说明:以下各图背景红色只是方便看清楚: 1.创建工程:创建xib文件,不会,可看上上上篇:初识xib: 2.打开xib文件: (1).创建头像: 拖控件:uiimageview--& ...

  10. [转]实现一个无法被继承的C++类

    From:http://blog.csdn.net/lazy_tiger/article/details/2224899 一个类不能被继承,也就是说它的子类不能构造父类,这样子类就没有办法实例化整个子 ...