T31P电子秤数据读取
连接串口后先发送"CP\r\n"激活电子秤数据发送,收到的数据包是17字节的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace DotNet.ElecScales
{ using System.IO.Ports;
using System.Text;
using System.Threading;
/// <summary>
/// 针对Defender 3000 - T31P
/// 厂家:奥豪斯仪器(常州)有限公司
/// 设置成 波特率9600, 8位无校验,连续模式
/// 编写:Wdfrog
/// http://www.cnblogs.com/wdfrog/archive/2012/10/25/2738257.html
/// </summary>
public class ElecScalesReader
{
#region 属性d定义 private String ComName; private int C_MaxQueueElem = ;//队列里存放的最多元素个数
private int C_FrameLength = ; private bool Enabled = false;
private Thread WorkThread { get; set; } //公开属性
public Queue<GatherDataInfo> DataQueue { get; private set; }
public SerialPort COMPort { get; private set; }
public Exception LastError { get; set; }
#endregion
/// <summary>
/// 构造
/// </summary>
public ElecScalesReader(string com)
{
ComName = com;
DataQueue = new Queue<GatherDataInfo>(); }
private void EnsureCOMPortOpen()
{
if (COMPort == null)
{
//配置COMPort
COMPort = new SerialPort(ComName.ToUpper(), , Parity.None, , StopBits.One);
COMPort.Handshake = Handshake.XOnXOff;
COMPort.Encoding = Encoding.ASCII;
//COMPort.DtrEnable = true;
}
if (!COMPort.IsOpen)
{
COMPort.Open();
}
} /// <summary>
/// 格式-> 状态,读数,原始数据Ascii字符串,备注
/// 状态-> 1:成功,0:无数据,4:错误
/// </summary>
/// <returns></returns>
public string GetValue()
{ string valueTmp = "{0},{1},[{2}],{3}";//状态{1成功,0无数据,4错误},读数,原始数据16进制表示,备注
var data = GetValueInfo();
return string.Format(valueTmp, data.Status, data.StrValue, data.RawStr == null ? "" : data.RawStr, ""); }
public GatherDataInfo GetValueInfo()
{ try
{
if (WorkThread == null || WorkThread.IsAlive != true)
{
Launch();
Thread.Sleep();
}
}
catch (Exception ex)
{
LastError = ex;
return new GatherDataInfo() { Status = };
} if (DataQueue.Count <= ) Thread.Sleep();
GatherDataInfo data = new GatherDataInfo() { Status = , AddTime = DateTime.Now, RawStr = null, StrValue = Thread.CurrentThread.ManagedThreadId.ToString() + ":" + this.GetHashCode().ToString(), };
lock (DataQueue)
{
if (DataQueue.Count > )
{
data = DataQueue.Last();
}
}
return data;
}
/// <summary>
/// 关闭COM
/// </summary>
public void Close()
{
this.Enabled = false;
while (COMPort != null && COMPort.IsOpen) Thread.Sleep(); } /// <summary>
/// 启动
/// </summary>
private void Launch()
{
EnsureCOMPortOpen();
Enabled = true; WorkThread = new Thread(DoReceive);
WorkThread.IsBackground = true;
WorkThread.Priority = ThreadPriority.Highest;
WorkThread.Start(); }
private void DoReceive()
{
Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId.ToString());
#region
try
{
byte[] buffer = new byte[COMPort.ReadBufferSize];
while (Enabled)
{ Thread.Sleep();
if (COMPort.BytesToRead <= ) continue; var readLine= COMPort.ReadLine();
if (readLine.Length != ) continue; var v = readLine.Substring(, ).Trim() + readLine.Substring(, ).Trim();
COMPort.DiscardInBuffer(); Console.WriteLine(v);
//将数据入队列
var data = new GatherDataInfo() { Status = , AddTime = DateTime.Now, RawStr = readLine, StrValue = v };
lock (DataQueue)
{
DataQueue.Enqueue(data);
if (DataQueue.Count > C_MaxQueueElem)
{
DataQueue.Dequeue();
}
} }
}
catch (Exception ex)
{
LastError = ex;
throw;
}
finally
{ if (COMPort != null && COMPort.IsOpen)
{
COMPort.Close();
}
}
#endregion }
} /// <summary>
/// 获取的有效桢信息
/// </summary>
public class GatherDataInfo
{
public DateTime? AddTime { get; set; }
/// <summary>
/// 字节信息
/// </summary>
public String RawStr { get; set; }
/// <summary>
/// 转化后的信息
/// </summary>
public string StrValue { get; set; } /// <summary>
/// 1,有效果
/// 0,无效
/// </summary>
public int Status { get; set; }
} public class ElecScalesHelper
{
private static Dictionary<String, ElecScalesReader> _Readers;
public static Dictionary<String, ElecScalesReader> Readers
{
get
{ if (_Readers == null)
{ _Readers = new Dictionary<String,ElecScalesReader>(); } return _Readers;
} }
/// <summary>
/// 格式-> 状态,读数,原始数据16进制表示,备注
/// 状态-> 1:成功,0:无数据,4:错误
/// </summary>
/// <returns></returns>
public static string GetValue(String comName)
{
var com=comName.Trim().ToLower();
if (com.IndexOf("com") != ) return "错误的COM名称"; lock (typeof(ElecScalesHelper))
{ ElecScalesReader reader = null;
if (!Readers.ContainsKey(com))
{
reader = new ElecScalesReader(com);
Readers.Add(com, reader);
}
else
{
reader = Readers[com];
}
return reader.GetValue();
} }
/// <summary>
/// 关闭COM
/// </summary>
public static string Close(String comName)
{
var com = comName.Trim().ToLower();
if (!Readers.ContainsKey(com)) return "字典内不存在该串口";
var reader = Readers[com]; lock (typeof(ElecScalesHelper))
{
reader.Close();
reader = null;
}
return "";
}
} }
T31P电子秤数据读取的更多相关文章
- OleDbDataReader快速数据读取方式
查询得到OleDbDataReader后,有三种方式支持数据读取,如下: //方法一**速度中等 OleDbDataReader reader = command.ExecuteReader(); w ...
- DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)
/// <summary> /// DataTable to Excel(将数据表中的数据读取到excel格式内存中) /// </summary> /// <param ...
- geotrellis使用(二)geotrellis-chatta-demo以及geotrellis框架数据读取方式初探
在上篇博客(geotrellis使用初探)中简单介绍了geotrellis-chatta-demo的大致工作流程,但是有一个重要的问题就是此demo如何调取数据进行瓦片切割分析处理等并未说明,经过几天 ...
- GPS数据读取与处理
GPS数据读取与处理 GPS模块简介 SiRF芯片在2004年发布的最新的第三代芯片SiRFstar III(GSW 3.0/3.1),使得民用GPS芯片在性能方面登上了一个顶峰,灵敏度比以前的产品大 ...
- 【原】Learning Spark (Python版) 学习笔记(二)----键值对、数据读取与保存、共享特性
本来应该上周更新的,结果碰上五一,懒癌发作,就推迟了 = =.以后还是要按时完成任务.废话不多说,第四章-第六章主要讲了三个内容:键值对.数据读取与保存与Spark的两个共享特性(累加器和广播变量). ...
- MATLAB对于文本文件(txt)数据读取的技巧总结(经典中的经典)
振动论坛原版主eight的经典贴http://www.chinavib.com/thread-45622-1-1.html MATLAB对于文本文件(txt)进行数据读取的技巧总结(经典中的经典)由于 ...
- TableInputFormat分片及分片数据读取源码级分析
我们在MapReduce中TextInputFormat分片和读取分片数据源码级分析 这篇中以TextInputFormat为例讲解了InputFormat的分片过程以及RecordReader读取分 ...
- Extjs的数据读取器store和后台返回类型简单解析
工作中用到了Extjs,从后台获取数据的时候,用到了extjs自己的Ext.data.store方法,然后封装了ExtGridReturn方法, 目的:前台用到Ext.data.store读取从后台传 ...
- Java学习-028-JSON 之二 -- 数据读取
JSON数据由 JSONObject.JSONArray.key_value 组合而成.通常来说,JSONObject 可以包含 JSONObject.JSONArray.key_value:JSON ...
随机推荐
- CentOS 6.5 下搭建NTP服务器
参考网站: http://www.iyunv.com/thread-64847-1-1.html http://acooly.iteye.com/blog/1993484 1 检查系统 ...
- linux 下 ifcfg-eth0 配置/CentOS_minimal安装和开发环境部署
CentOS_minimal安装和开发环境部署:http://www.th7.cn/system/lin/201305/39002.shtml 网络接口配置文件 [root@localhost ~]# ...
- 启动zookeeper时,jps显示有进程,但是status查看状态时就Error contacting service. It is probably not running
转自:http://www.cnblogs.com/xiaohua92/p/5460515.html#undefined 安装zookeeper时候,可以查看进程启动,但是状态显示报错:Error c ...
- redis与lua
内容大纲 redis里使用eval和evalsha redis管理Lua脚本 php里使用redis的lua脚本 在redis里使用lua脚本的好处 1.Lua脚本在Redis中是原子执行的,执行过 ...
- var和let示例
声明后未赋值,表现相同 (function() { var varTest; let letTest; console.log(varTest); //输出undefined console.log( ...
- Python普通方法、静态方法、类方法
开始 # -*-coding:utf-8-*- # 普通方法,类方法,静态方法的区别 __metaclass__ = type class Tst: name = 'tst' data = 'this ...
- 总结开发中使用到的npm 库
1.Swiper https://github.com/nolimits4web/Swiper 移动端slides插件 2.fetch https://github.com/whatwg/fetch ...
- windows下手动安装pyinstaller(python2.7)
1.首先,安装python2.7.13,官网下载msi版(windows直接安装): https://www.python.org/downloads/ 2.然后,到python包官网依次下载,fut ...
- Space-vim的.spacevim配置备份
安装 windows安装 配置 在C盘的用户目录下,有一个'.spacevim'的文件,可以修改你要的配置 " Let Vim and NeoVim shares the same plug ...
- centOs7 忘记root密码
记录:https://blog.csdn.net/niu_hao/article/details/52882895