基恩士上位机链路通讯_基恩士PLC通讯源码

基恩士PLC KV7000,8000还是比较好用的,那如何和上位机通讯,我把源码写出来了。采用上位链路通讯,基恩士官方给我们留了8501端口,这个端口有意思刚好是我生日。基恩士的资料我觉得做的特别好,能快速写源代码得益于官方资料特别详细,对了,他的通讯采用是ASCII码直接通讯。比如你读到的ASCII码是666,那他的实际值也就是666。好了上代码,如果热度比较高,大家有不清楚的地方,我出视频讲解。

be0fbfd2824b95b01ce68bbf53bb8e89.png
fd4da38be5bf58bd78b71c83fc3d7fbc.png
b25bdd69b452a292463cd2796a70dffb.png
674c65ae260fa620c66c83bae9d41a8d.png
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Threading;using System.Net;namespace WDBaseCommuntionHelper{    public class KV7_8000Service    {        Socket KVTCPClicent;        readonly object LockKVTCP = new object();        public enum DataType        {            ///             /// 16位无符号            ///             U,            ///             /// 16位有符号            ///             S,            ///             /// 32位无符号            ///             D,            ///             /// 32位有符号            ///             L,            ///             /// 16位16进制数            ///             H,            ///             /// 默认            ///             N        }        #region 命令        ///         /// 更改模式        ///         const string Command1 = "M";        ///         /// 清除错误        ///         const string Command2 = "ER";        ///         /// 检查错误编号        ///         const string Command3 = "?E";        ///         /// 查询机型        ///         const string Command4 = "?K";        ///         /// 检查运行模式        ///         const string Command5 = "?M";        ///         /// 时间设定        ///         const string Command6 = "WRT";        ///         /// 强制置位        ///         const string Command7 = "ST";        ///         /// 强制复位        ///         const string Command8 = "RS";        ///         /// 连续强制置位        ///         const string Command9 = "STS";        ///         /// 连续强制复位        ///         const string Command10 = "RSS";        ///         /// 读取数据        ///         const string Command11 = "RD";        ///         /// 读取连续数据        ///         const string Command12 = "RDS";        ///         /// 读取连续数据        ///         const string Command13 = "RDE";        ///         /// 写入数据        ///         const string Command14 = "WR";        ///         /// 写入连续数据        ///         const string Command15 = "WRS";        ///         /// 写入连续数据        ///         const string Command16 = "WRE";        ///         /// 写入设定值        ///         const string Command17 = "WS";        ///         /// 写入连续设定值        ///         const string Command18 = "WSS";        ///         /// 监控器登录        ///         const string Command19 = "MBS";        ///         /// 监控器登录        ///         const string Command20 = "MWS";        ///         /// 读取监控器        ///         const string Command21 = "MBR";        ///         /// 读取监控器        ///         const string Command22 = "MWR";        ///         /// 注释读取        ///         const string Command23 = "RDC";        ///         /// 存储体切换        ///         const string Command24 = "BE";        ///         /// 读取扩展单元缓冲存储器        ///         const string Command25 = "URD";        ///         /// 写入扩展单元缓冲存储器        ///         const string Command26 = "UWR";        ///         /// 回车        ///         const string CR = "";        ///         /// 空格        ///         const string SP = " ";        #endregion        Encoding encoding = Encoding.ASCII;        ///         /// PLC连接状态        ///         public bool IsConnected { get; private set; }        ///         /// 发送超时时间        ///         public int SendTimeout { get; set; } = 2000;        ///         /// 接收超时时间        ///         public int ReceiveTimeout { get; set; } = 2000;        ///         /// 等待PLC响应周期,这里一个周期10ms        ///         public int MaxDelayCycle { get; set; } = 5;        string ip;        int port;        private Dictionary plcValue = new Dictionary();        ///         /// PLC值键值对        ///         public Dictionary PlcValue { get { return plcValue; } }        ///         /// 重连        ///         ///         public bool ReConnext()        {            if (ip == string.Empty || port == 0)            {                throw new Exception("没有IP和端口请调用Connect函数连接"); return false;            }           return  Connect(ip,port);        }        ///         /// 连接PLC        ///         ///         ///         ///         public bool Connect(string ip, int port=8501)        {            if (this.ip != ip) this.ip = ip;            if (this.port != port) this.port = port;            KVTCPClicent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            KVTCPClicent.SendTimeout = SendTimeout;            KVTCPClicent.ReceiveTimeout = ReceiveTimeout;            IAsyncResult asyncResult=  KVTCPClicent.BeginConnect(new IPEndPoint(IPAddress.Parse(ip) ,port),null,null);            asyncResult.AsyncWaitHandle.WaitOne(3000,true);            if (!asyncResult.IsCompleted)            {                KVTCPClicent.Close();                return false;            }            return true;        }        ///         /// 改变PLC运行状态        ///         /// true让PLC运行false让PLC停止        ///         public string ChangeCPU(bool run = true)        {            string str = Command1 + (run ? "1" : "0") + CR;            return SendRecive(str);        }        ///         /// 查看PLC运行状态        ///         ///         public string SeeCPUState()        {            string str = Command5 + CR;            return SendRecive(str);        }        ///         /// 强制置位复位        ///         ///         ///         ///         public string Put(string address, bool value)        {            string str;            if (value)            {                str = Command7 + SP + address + CR;            }            else            {                str = Command8 + SP + address + CR;            }            return SendRecive(str);        }        ///         /// 连续强制置位复位        ///         ///         ///         ///         ///         public string Put(string address, bool Value, int count)        {            string str;            if (Value)            {                str = Command9 + SP + address + count + CR;            }            else            {                str = Command10 + SP + address + count + CR;            }            return SendRecive(str);        }        ///         /// 写入字数据        ///         ///         ///         ///         ///         public string Put(string address, string value, DataType tpye = DataType.N)        {            string str = Command14 + SP + address + GetDataType(tpye) + SP + value + CR;            return SendRecive(str);        }        ///         /// 写入单精度浮点数        ///         ///         ///         ///         public string Put(string address, float value)        {            List result = CalFloatToInt16(value);            return Put(address, result);        }        ///         /// 写入连续字数据        ///         ///         ///         ///         ///         public string Put(string address, List value, DataType tpye = DataType.N)        {            StringBuilder sb = new StringBuilder(Command15 + SP + address + GetDataType(tpye) + SP + value.Count);            for (int i = 0; i < value.Count; i++)            {                sb.Append(SP + value[i]);            }            sb.Append(CR);            return SendRecive(sb.ToString());        }        ///         /// 读取字数据        ///         ///         ///         ///         public string Get(string address, DataType tpye = DataType.N)        {            string str = Command11 + SP + address + GetDataType(tpye) + CR;            return SendRecive(str);        }        ///         /// 读取连续字数据        ///         ///         ///         ///         ///         public string Get(string address, int count, DataType tpye = DataType.N)        {            string str = Command13 + SP + address + GetDataType(tpye) + SP + count + CR;            return SendRecive(str);        }        public string CalRD(string str, string type, int address, int count)        {            string[] s1 = str.Split(' ');            if (count > s1.Length)            {                throw new Exception("映射长度过长");            }            for (int i = 0; i < count; i++)            {                plcValue[type + (address + i)] = s1[i].ToString();            }            return "OK";        }        ///         /// 32位浮点转16位字        ///         ///         ///         public List CalFloatToInt16(float value)        {            byte[] r1 = BitConverter.GetBytes(value);            byte[] r2 = new byte[2] { r1[0], r1[1] };            byte[] r3 = new byte[2] { r1[2], r1[3] };            int r4 = BitConverter.ToUInt16(r2, 0);            int r5 = BitConverter.ToUInt16(r3, 0);            return new List() { r4.ToString(), r5.ToString() };        }        ///         /// 2个16位字转32位浮点        ///         ///         ///         ///         public float CalInt16ToFlaot(string[] value, int startIndex)        {            byte[] r1 = BitConverter.GetBytes(Convert.ToInt16(value[startIndex]));            byte[] r2 = BitConverter.GetBytes(Convert.ToInt16(value[startIndex + 1]));            byte[] r3 = new byte[4] { r1[0], r1[1], r2[0], r2[1] };            return BitConverter.ToSingle(r3, 0);        }        ///         /// ASCII编码解码        ///         ///         ///         public string SendRecive(string str)        {            return encoding.GetString(SendRecive(encoding.GetBytes(str)));        }        ///         /// 发送接收字节数组报文        ///         ///         ///         public byte[] SendRecive(byte[] arry)        {            try            {                Monitor.Enter(LockKVTCP);                int delay = 0;                int reslut = KVTCPClicent.Send(arry);                while (KVTCPClicent.Available == 0)                {                    Thread.Sleep(10);                    delay++;                    if (delay > MaxDelayCycle)                    {                        break;                    }                }                byte[] ResByte = new byte[KVTCPClicent.Available];                reslut = KVTCPClicent.Receive(ResByte);                return ResByte;            }            catch (Exception)            {                IsConnected = false;                return null;            }            finally            {                Monitor.Exit(LockKVTCP);            }        }        ///         /// 根据数据类型生成报文        ///         ///         ///         public string GetDataType(DataType dataType)        {            string str = string.Empty;            switch (dataType)            {                case DataType.U:                    str = ".U";                    break;                case DataType.S:                    str = ".S";                    break;                case DataType.D:                    str = ".D";                    break;                case DataType.L:                    str = ".L";                    break;                case DataType.H:                    str = ".H";                    break;                case DataType.N:                    str = "";                    break;                default:                    str = "";                    break;            }            return str;        }    }}

#上位机# #PLC# #触摸屏# #电工交流圈#

如果对您有帮助,点赞关注转发,持续更新,帮大家解答工控问题

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/269739.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第二次作业+105032014101

1、测试帖链接 http://www.cnblogs.com/ELPSY/p/6605831.html 2、提出的建议 该代码基本符合编码规则所需的正确性、稳定性、可读性的要求。 程序出现错误的地方在对于2月份日期的判定上&#xff0c;以“2000 2 30”的输入语句符合年月日的三个输入条件&#xff0c;但是这并不…

fastq质量值_fastq 数据格式解析

概念介绍Read 读段Read 中文翻译&#xff1a; 读段&#xff0c;来自测序仪的raw data一个Read 可能由多个片段组成&#xff0c; Read的索引是测序时的顺序Sequencing quality 测序质量测序仪在测序的时候&#xff0c;每次测出来的结果可能都不一样(仪器误差 序列长度等各方面因…

画像分析(3-3)标签建模-模型管理-新建关系

1、关系是什么 关系&#xff0c;是实体与实体之间所发生的连接&#xff0c;通常表示某一种行为/一个事实&#xff0c;如成交、搜索、出行。从数据表的角度来看&#xff0c;这样的表通常被称为”事实表“&#xff0c;往往是有多个联合主键&#xff08;或是说都是外键&#xff09…

二进制、八进制、十进制、十六进制之间的转换

在计算机语言中常用的进制有二进制、八进制、十进制和十六进制&#xff0c;十进制是最主要的表达形式。 对于进制&#xff0c;有两个基本的概念&#xff1a;基数和运算规则。 基数&#xff1a;基数是指一种进制中组成的基本数字&#xff0c;也就是不能再进行拆分的数字。二进…

myeclipse mysql 乱码_MyEclipse与mysql增改查现乱码解决方案绝对有效

设置MyEclipse文件编码。且跟mysql的连接编码一致set names gbk; SET character_set_clientutf8;SET character_set_connectionutf8;SET character_set_resultsutf8;show variables like %char%;SET character_set_clientutf8;SET character_set_connection utf8;SET character…

poj3723Conscription

题目链接&#xff1a;http://poj.org/problem?id3723 建图时将女生编号都加n&#xff08;男生数目&#xff09;&#xff0c;求最大生成树。 1 #include <cstdio>2 #include <cstring>3 #include <algorithm>4 using namespace std;5 const int maxn100001;6…

JAVA基础知识之字节和字符

一、字节的概念 1、计算机中的数据都是以二进制的形式进行存储和交换的&#xff0c;字节本质就是二进制&#xff0c;因此字节是最基本的储存单位 2、一个字节本质就是8位二进制&#xff0c;因此1个字节最小的值是0&#xff0c;最大的值是11111111&#xff0c;转换十进制…

mysql 8小时问题_Mysql经典的“8小时问题”

假设你的数据库是mysql&#xff0c;如果数据源配置不当&#xff0c;将可能发生经典的“8小时问题”。原因是mysql在默认情况下&#xff0c;如果发现一个连接的空闲时间超过8小时&#xff0c;将会在数据库端自动关闭这个连接。而数据源并不知道这个连接已经关闭了&#xff0c;当…

【BZOJ 2753】 2753: [SCOI2012]滑雪与时间胶囊 (分层最小树形图,MST)

2753: [SCOI2012]滑雪与时间胶囊 Time Limit: 50 Sec Memory Limit: 128 MBSubmit: 2457 Solved: 859Description a180285非常喜欢滑雪。他来到一座雪山&#xff0c;这里分布着M条供滑行的轨道和N个轨道之间的交点&#xff08;同时也是景点&#xff09;&#xff0c;而且每个景…

SortedMap接口实现排序

SortedMap接口主要提供有序的Map实现。SortedMap接口是排序接口&#xff0c;只要是实现了此接口的子类&#xff0c;都属于排序的子类&#xff0c;TreeMap也是此接口的一个子类 Map的主要实现有HashMap,TreeMap,HashTable,LinkedHashMap。 TreeMap实现了SortedMap接口&#xf…

mysql漏洞包_MySQL npm包中的本地文件泄露漏洞

“A pure node.js javascript Client implementing the MySQL protocol.”漏洞在某次安全评估中&#xff0c;Synacktiv专家无意中发现某个应用可以从另一台MySQL服务器中读取敏感数据&#xff0c;而该应用程序正是使用了mysql的npm软件包。该npm软件包所支持的LOAD DATA LOCAL命…

C# 对象与JSON串互相转换

DoNet2.0 需要借助于Newtonsoft.Json.dll 1 代码2 3 using System;4 using System.IO;5 using System.Text;6 using Newtonsoft.Json;7 8 namespace OfflineAcceptControl.UCTools9 { 10 public class JsonTools 11 { 12 // 从一个对象信息生成Json串 13 …

mysql 日期查询今天_Mysql 日期查询今天、昨天、近7天、近30天、本月、上一月、本季...

今天select * from 表名 where to_days(时间字段名) to_days(now());昨天SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) < 1近7天SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) < date(时间字段名)近30天SELECT * FROM 表名 whe…

java实现MD5加密

MD5加密是一种常见的加密方式&#xff0c;我们经常用在保存用户密码和关键信息上。那么它到底有什么&#xff0c;又什么好处呢&#xff0c;会被这么广泛的运用在应用开发中。 信息-摘要算法&#xff08;Message-digest Algorithm 5&#xff0c;MD5&#xff09;于90年代初由MIT …

THINKPHP5判断当前浏览器请求方式

作用代码是否为 GET 请求if (Request::instance()->isGet())是否为 POST 请求if (Request::instance()->isPost())是否为 PUT 请求if (Request::instance()->isPut())是否为 DELETE 请求if (Request::instance()->isDelete())是否为 Ajax 请求if (Request::instanc…

jspwiki mysql_Wiki.js初体验

利用JSPWiki搭建简易企业wiki平台。今天介绍一下基于NodeJS技术的开源项目Wiki.js&#xff0c;其界面简洁美观&#xff0c;支持多种编辑器、多种用户验证方式、多种备份存储方式&#xff0c;支持国际化、自定义主题(Theme)、流量分析等。更多正在开发中的功能&#xff0c;界面也…

java中Map有哪些实现类

Java中的map是一个很重要的集合&#xff0c;他是一个接口&#xff0c;下面继承它实现了多个实现类&#xff0c;这些类各有千秋&#xff0c;各自有个各自的优点和缺点 如下图 map的主要特点是键值对的形式&#xff0c;一一对应&#xff0c;且一个key只对应1个value。其常用的map…

h2 mysql 兼容_H2内存数据库对sql语句的支持问题 sql放到mysql数据库中能跑

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼### The error may involve com.yrs.modules.classes.stu.teacher.mapper.ClassesStuTeacherMapper.queryStudentInfoByclasses### The error occurred while executing a query### SQL: SELECT ysi.stu_id, ysi.stu_name, ysi.stu…