1、A-3E報(bào)文回顧
?
?具體細(xì)節(jié)請(qǐng)看:
C#上位機(jī)與三菱PLC的通信05--MC協(xié)議之QnA-3E報(bào)文解析
C#上位機(jī)與三菱PLC的通信06--MC協(xié)議之QnA-3E報(bào)文測(cè)試
2、為何要開發(fā)自己的通訊庫(kù) ??
?前面開發(fā)了自己的A-1E協(xié)議的通訊庫(kù),實(shí)現(xiàn)了數(shù)據(jù)的讀寫,對(duì)于封裝的通訊庫(kù),其實(shí)是一個(gè)dll文件,請(qǐng)看上節(jié)的dll文件,有了這個(gè)文件,就可以在項(xiàng)目中直接引用 。
我們只要引用并調(diào)用相關(guān)的方法即可實(shí)現(xiàn)目的, 但寫一個(gè)通訊庫(kù)需要非凡的技術(shù),需要考慮的東西很多,比如擴(kuò)展性,通用性,等等之類的。通過封裝通訊庫(kù)達(dá)到更高的層次, 大師就是這樣鍛造出來的,接下來馬上安排A-3E協(xié)議的封裝,代碼是基于上節(jié)的基礎(chǔ)上添加。
?3、說干就干
1、添加類文件
2、編寫核心的通信類A3E.cs
A3E.cs完整代碼
using Mitsubishi.Communication.MC.Mitsubishi.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Mitsubishi.Communication.MC.Mitsubishi
{
/// <summary>
/// A3E報(bào)文通訊庫(kù)
/// </summary>
public class A3E : MelsecBase
{
byte _netCode = 0x00, _stationCode = 0x00;
public A3E(string ip, short port, byte net_code = 0x00, byte station_code = 0x00) : base(ip, port)
{
_netCode = net_code;
_stationCode = station_code;
}
#region 讀數(shù)據(jù)
/// <summary>
/// 讀取數(shù)據(jù)
/// </summary>
/// <typeparam name="T">讀取的數(shù)據(jù)類型</typeparam>
/// <param name="address">存儲(chǔ)區(qū)地址</param>
/// <param name="count">讀取長(zhǎng)度</param>
/// <returns></returns>
public Result<T> Read<T>(string address, short count)
{
AreaCode areaCode; string start;
(areaCode, start) = this.AnalysisAddress(address);
return Read<T>(areaCode, start, count);
}
/// <summary>
/// 讀取數(shù)據(jù)
/// </summary>
/// <typeparam name="T">讀取的數(shù)據(jù)類型</typeparam>
/// <param name="areaCode">存儲(chǔ)區(qū)代碼</param>
/// <param name="startAddr">開始地址</param>
/// <param name="count">讀取長(zhǎng)度</param>
/// <returns></returns>
public Result<T> Read<T>(AreaCode areaCode, string startAddr, short count)
{
Result<T> result = new Result<T>();
try
{
// 連接
var connectState = this.Connect();
if (!connectState.IsSuccessed)
{
throw new Exception(connectState.Message);
}
// 子命令(位/字)
byte readCode = (byte)(typeof(T) == typeof(bool) ? 0x01 : 0x00);
//開始地址
List<byte> startBytes = this.StartToBytes(areaCode, startAddr);
// 讀取長(zhǎng)度
int typeLen = this.CalculatLength<T>();
// 讀取報(bào)文
List<byte> bytes = new List<byte>
{
0x50,0x00,//請(qǐng)求副頭部,固定50 00
_netCode,// 網(wǎng)絡(luò)號(hào),根據(jù)PLC的設(shè)置
0xFF,//PLC編號(hào),固定值
0xFF,0x03,//目標(biāo)模塊IO編號(hào),固定FF 03
_stationCode,// 目標(biāo)模塊站號(hào)
0x0C,0x00, // 剩余字節(jié)長(zhǎng)度
0x0A,0x00,//PLC響應(yīng)超時(shí)時(shí)間,以250ms為單位計(jì)算
0x01,0x04,// 成批讀取
readCode,0x00,// 字操作 0x0001
startBytes[0],startBytes[1],startBytes[2],// 起始地址
(byte)areaCode,// 區(qū)域代碼
(byte)(typeLen*count%256),
(byte)(typeLen*count/256%256) //長(zhǎng)度
};
//發(fā)送報(bào)文
List<byte> dataBytes = this.Send(bytes, 0);
//數(shù)據(jù)解析
result.Datas = this.AnalysisDatas<T>(dataBytes, typeLen);
}
catch (Exception ex)
{
result = new Result<T>(false, ex.Message);
}
return result;
}
#endregion
#region 寫數(shù)據(jù)
/// <summary>
/// 寫入數(shù)據(jù)
/// </summary>
/// <typeparam name="T">寫入的數(shù)據(jù)類型</typeparam>
/// <param name="values">寫入的數(shù)據(jù)列表</param>
/// <param name="address">開始地址</param>
/// <returns></returns>
public Result Write<T>(List<T> values, string address)
{
AreaCode areaCode; string start;
(areaCode, start) = this.AnalysisAddress(address);
return this.Write<T>(values, areaCode, start);
}
/// <summary>
/// 寫入數(shù)據(jù)
/// </summary>
/// <typeparam name="T">寫入的數(shù)據(jù)類型</typeparam>
/// <param name="values">寫入的數(shù)據(jù)列表</param>
/// <param name="areaCode">存儲(chǔ)區(qū)代碼</param>
/// <param name="address">開始地址</param>
/// <returns></returns>
public Result Write<T>(List<T> values, AreaCode areaCode, string startAddr)
{
Result result = new Result();
try
{
// 連接
var connectState = this.Connect();
if (!connectState.IsSuccessed)
{
throw new Exception(connectState.Message);
}
// 子命令(位/字)
byte writeCode = (byte)(typeof(T) == typeof(bool) ? 0x01 : 0x00);
// 起始地址 XY 直接翻譯 100 00 01 00 D100 64 00 00
List<byte> startBytes = this.StartToBytes(areaCode, startAddr);
//計(jì)算數(shù)據(jù)類型的長(zhǎng)度
int typeLen = this.CalculatLength<T>();
int count = values.Count;
//計(jì)算數(shù)據(jù)的字節(jié)列表
List<byte> datas = this.GetDataBytes<T>(values);
List<byte> baseBytes = new List<byte>
{
0x50,0x00,
this._netCode,// 可變,根據(jù)PLC的設(shè)置
0xFF,//PLC編號(hào),固定值
0xFF,0x03,//目標(biāo)模塊IO編號(hào),固定FF 03
this._stationCode,// 可變,目標(biāo)模塊站號(hào)
};
//0x0E,0x00, // 剩余字節(jié)長(zhǎng)度
List<byte> commandBytes = new List<byte> {
0x0A,0x00,//超時(shí)時(shí)間
0x01,0x14,// 成批寫入
writeCode,0x00,// 字操作
startBytes[0],startBytes[1],startBytes[2],// 起始地址
(byte)areaCode,// 區(qū)域代碼
(byte)(typeLen*count%256),
(byte)(typeLen*count/256%256), //長(zhǎng)度
};
commandBytes.AddRange(datas);
baseBytes.Add((byte)(commandBytes.Count % 256));
baseBytes.Add((byte)(commandBytes.Count / 256 % 256));
baseBytes.AddRange(commandBytes);
socket.Send(baseBytes.ToArray());
// 解析響應(yīng)
byte[] respBytes = new byte[11];
socket.Receive(respBytes, 0, 11, SocketFlags.None);
// 狀態(tài)
if ((respBytes[9] | respBytes[10]) != 0x00)
{
throw new Exception("響應(yīng)異常。" + respBytes[9].ToString() + respBytes[10].ToString());
}
}
catch (Exception ex)
{
result.IsSuccessed = false;
result.Message = ex.Message;
}
return result;
}
#endregion
#region 私有方法
/// <summary>
/// 地址解析
/// </summary>
/// <param name="address">地址字符串</param>
/// <returns></returns>
public Tuple<AreaCode, string> AnalysisAddress(string address)
{
// 取兩個(gè)字符
string area = address.Substring(0, 2);
if (!new string[] { "TN", "TS", "CS", "CN" }.Contains(area))
{
area = address.Substring(0, 1);
}
string start = address.Substring(area.Length);
// 返回一個(gè)元組對(duì)象
return new Tuple<AreaCode, string>((AreaCode)Enum.Parse(typeof(AreaCode), area), start);
}
/// <summary>
/// 發(fā)送報(bào)文
/// </summary>
/// <param name="reqBytes">字節(jié)列表</param>
/// <param name="count"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public override List<byte> Send(List<byte> reqBytes, int count)
{
socket.Send(reqBytes.ToArray());
// 解析
byte[] respBytes = new byte[11];
socket.Receive(respBytes, 0, 11, SocketFlags.None);
// 狀態(tài)
if ((respBytes[9] | respBytes[10]) != 0x00)
{
throw new Exception("響應(yīng)異常。" + respBytes[9].ToString() + respBytes[10].ToString());
}
// 數(shù)據(jù)長(zhǎng)度
int dataLen = BitConverter.ToUInt16(new byte[] { respBytes[7], respBytes[8] },0) - 2; // -2 的意思去除響應(yīng)代碼(狀態(tài))
byte[] dataBytes = new byte[dataLen];
socket.Receive(dataBytes, 0, dataLen, SocketFlags.None);
return new List<byte>(dataBytes);
}
#endregion
#region plc控制
/// <summary>
/// PLC遠(yuǎn)程啟動(dòng)
/// </summary>
/// <returns></returns>
public Result Run()
{
return PlcStatus(0x01, new List<byte> { 0x00, 0x00 });
}
/// <summary>
/// PLC遠(yuǎn)程停止
/// </summary>
/// <returns></returns>
public Result Stop()
{
return PlcStatus(0x02);
}
/// <summary>
/// PLC運(yùn)行狀態(tài)
/// </summary>
/// <param name="cmdCode"></param>
/// <param name="cmd"></param>
/// <returns></returns>
private Result PlcStatus(byte cmdCode, List<byte> cmd = null)
{
Result result = new Result();
try
{
var connectState = this.Connect();
if (!connectState.IsSuccessed)
{
throw new Exception(connectState.Message);
}
List<byte> commandBytes = new List<byte>
{
0x50,0x00,
this._netCode,// 可變,根據(jù)PLC的設(shè)置
0xFF,
0xFF,0x03,
this._stationCode,// 可變
};
//0x08,0x00, // 剩余字節(jié)長(zhǎng)度
List<byte> cmdBytes = new List<byte> {
0x0A,0x00,
cmdCode,0x10,
0x00,0x00,
0x01,0x00,//模式
};
if (cmd != null)
{
cmdBytes.AddRange(cmd);
}
commandBytes.Add((byte)(commandBytes.Count % 256));
commandBytes.Add((byte)(commandBytes.Count / 256 % 256));
commandBytes.AddRange(cmdBytes);
socket.Send(commandBytes.ToArray());
byte[] respBytes = new byte[11];
socket.Receive(respBytes, 0, 11, SocketFlags.None);
// 狀態(tài)
if ((respBytes[9] | respBytes[10]) != 0x00)
{
throw new Exception("響應(yīng)異常。" + respBytes[1].ToString());
}
}
catch (Exception ex)
{
result.IsSuccessed = false;
result.Message = ex.Message;
}
return result;
}
#endregion
}
}
?4、測(cè)試通訊庫(kù)
1、啟動(dòng)MC服務(wù)器
2、利用通訊庫(kù)讀寫數(shù)據(jù)
1、讀取D區(qū)100開始的3個(gè)short數(shù)據(jù)
?
2、讀取M區(qū)100開始的5個(gè)float數(shù)據(jù)
?
?
3、讀取X區(qū)100開始的4個(gè)bool數(shù)據(jù)
?
4、寫入M區(qū)200開始的2個(gè)short數(shù)據(jù)
?
5、寫入D區(qū)200開始的5個(gè)float數(shù)據(jù)
?
?
3、完整代碼
/// <summary>
/// 測(cè)試A-3E通訊庫(kù)
/// </summary>
static void MCLibTestA3E()
{
A3E qNA3E = new A3E("192.168.1.7", 6000);
#region 讀數(shù)據(jù)
//Console.WriteLine("讀取D區(qū)100開始的3個(gè)short數(shù)據(jù)");
//var result1 = qNA3E.Read<short>("D100", 3);
//if (result1.IsSuccessed)
//{
// result1.Datas.ForEach(d => Console.WriteLine(d));
//}
//else
//{
// Console.WriteLine(result1.Message);
//}
//Console.WriteLine("讀取M區(qū)100開始的5個(gè)float數(shù)據(jù)");
//var result2 = qNA3E.Read<float>("M100", 5);
//if (result2.IsSuccessed)
//{
// result2.Datas.ForEach(d => Console.WriteLine(d));
//}
//else
//{
// Console.WriteLine(result2.Message);
//}
//Console.WriteLine("讀取X區(qū)100開始的4個(gè)bool數(shù)據(jù)");
//var result3 = qNA3E.Read<bool>(AreaCode.X, "100", 4);
//if (result3.IsSuccessed)
//{
// result3.Datas.ForEach(d => Console.WriteLine(d));
//}
//else
//{
// Console.WriteLine(result3.Message);
//}
#endregion
#region 寫數(shù)據(jù)
Console.WriteLine("寫入M區(qū)200開始的2個(gè)short數(shù)據(jù)");
var result4 = qNA3E.Write<short>(new List<short> { -541, 982 }, "M200");
if (result4.IsSuccessed)
{
Console.WriteLine(result4.Message);
}
Console.WriteLine("寫入D區(qū)200開始的5個(gè)float數(shù)據(jù)");
var result5 = qNA3E.Write<float>(new List<float> { 111, 0, -8076, 13.67f, -985.325f }, "D200");
if (result5.IsSuccessed)
{
Console.WriteLine(result5.Message);
}
#endregion
}
5、小結(jié)
原創(chuàng)真的不容易,走過路過不要錯(cuò)過,點(diǎn)贊關(guān)注收藏又圈粉,共同致富。
原創(chuàng)真的不容易,走過路過不要錯(cuò)過,點(diǎn)贊關(guān)注收藏又圈粉,共同致富。
原創(chuàng)真的不容易,走過路過不要錯(cuò)過,點(diǎn)贊關(guān)注收藏又圈粉,共同致富文章來源:http://www.zghlxwxcb.cn/news/detail-835546.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-835546.html
到了這里,關(guān)于C#上位機(jī)與三菱PLC的通信09---開發(fā)自己的通訊庫(kù)(A-3E版)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!