C# 运用开放协议连接拧紧枪控制器(马头)

5 篇文章 0 订阅

 以下为简单通讯测试源码,只提供参考

            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("127.0.0.1", 4545);//端口默认4545
            {
                //建立通讯
                var command = "00200001000000000000" + (char)0;
                byte[] commandbyte = Encoding.Default.GetBytes(command);
                tcpClient.Client.Send(commandbyte, SocketFlags.None);

                byte[] byteCommand = new byte[1024];
                int icommand= tcpClient.Client.Receive(byteCommand);
                var outputCommandValue = System.Text.Encoding.ASCII.GetString(byteCommand,0,icommand);
                Console.WriteLine(outputCommandValue);
            }

            {
                //发送心跳
                var heart = "00209999000000000000" + (char)0;
                byte[] heartData = Encoding.Default.GetBytes(heart);
                tcpClient.Client.Send(heartData);

                byte[] byteheart = new byte[1024];
                var iheartdata=tcpClient.Client.Receive(byteheart);
                string outputHeartValue = System.Text.Encoding.ASCII.GetString(byteheart,0,iheartdata);
                Console.WriteLine(outputHeartValue);
            }

            {
                //发送订阅拧紧数据
                var tightening = "00200060000000000000" + (char)0;
                byte[] tighteningbyte = Encoding.Default.GetBytes(tightening);
                tcpClient.Client.Send(tighteningbyte);

                byte[] bytesTightening = new byte[1024];
                var itightening=tcpClient.Client.Receive(bytesTightening);
                var outputTighteningValue = System.Text.Encoding.ASCII.GetString(bytesTightening,0,itightening);
                Console.WriteLine(outputTighteningValue);
            }

tcp 建立建立连接后,需要发送开始通讯指令(和S7等私有协议一样,连接后有两次通讯握手,拧紧控制器只有一次),拧紧控制器未收到通讯指令15秒后会强制断开连接。

开始通讯指令代码

00200001000000000000+(char)0;

拧紧控制器确认收到开始指令后回回复允许通讯指令(回复指令为测试指令,每把控制器可能略有差异,主要构成部分,由消息长度0000  指令代码0000 以及后续信息为主,以下回复报文不准确只作为解读参考)

如下:

0057代表报文长度,0002代表功能码

如上《开始通讯报文指令》组成结构一致  0020   0001,拼接时一定要注意长度是否满足规范,否则将无法通讯,马头控制器通讯报文结尾需要NUL 为标示符

拧紧控制器允许通讯指令

00570002001         010000020003                          

以下为完整带重连机制拧紧枪扭矩角度获取方式

        string communication = "00200001000000000000\0";
		byte[] communicationbyte = Encoding.ASCII.GetBytes(communication);
		string heart = "00209999000000000000\0";
		byte[] heartbyte = Encoding.ASCII.GetBytes(heart);
		string sub60 = "00200060000000000000\0";
		byte[] sub60byte = Encoding.ASCII.GetBytes(sub60);
		string sub61 = "00200062000000000000\0";
		byte[] sub62byte = Encoding.ASCII.GetBytes(sub61);
		var tcpClient = new TcpClient();
		Task.Run(async delegate
		{
			try
			{
				IAsyncResult async2 = tcpClient.Client.BeginConnect(ip, port, null, null);
				if (!async2.AsyncWaitHandle.WaitOne(1500))
				{
					tcpClient.Client.EndConnect(async2);
					Console.WriteLine("连接失败");
				}
				else
				{
					tcpClient.Client.EndConnect(async2);
					IAsyncResult sendsync3 = tcpClient.Client.BeginSend(communicationbyte, 0, communicationbyte.Length, SocketFlags.None, null, null);
					tcpClient.Client.EndSend(sendsync3);
					await Task.Delay(1000);
					IAsyncResult sendsyncsub = tcpClient.Client.BeginSend(sub60byte, 0, sub60byte.Length, SocketFlags.None, null, null);
					tcpClient.Client.EndSend(sendsyncsub);
				}
			}
			catch (Exception ex)
			{
				LogHelper.Log("拧紧连接", ex.Message.ToString());
			}
		});
		Task.Run(async delegate
		{
			while (true)
			{
				if (tcpClient != null && tcpClient.Connected)
					try
					{
						LogHelper.Log("拧紧连接", tcpClient.Connected.ToString());
						byte[] result = new byte[1024];
						IAsyncResult resultasync = tcpClient.Client.BeginReceive(result, 0, result.Length, SocketFlags.None, delegate{}, null);
						int releg = tcpClient.Client.EndReceive(resultasync);
						string output = Encoding.Default.GetString(result, 0, releg);
					    Console.WriteLine("扭矩角度MID0061报文:" + output);
					}
					catch (Exception ex)
					{
						LogHelper.Log("拧紧连接", ex.Message.ToString());
					}
				else
					await Task.Delay(3000);
			}
		});
		Task.Run(async delegate
		{
			while (true)
			{
				try
				{
					await Task.Delay(5000);
					IAsyncResult sendsync = tcpClient.Client.BeginSend(heartbyte, 0, heartbyte.Length, SocketFlags.None, null, null);
					tcpClient.Client.EndSend(sendsync);
				}
				catch (Exception)
				{
					if (tcpClient?.Connected ?? false)
						tcpClient?.Client?.Shutdown(SocketShutdown.Both);
					try
					{
						tcpClient = new TcpClient();
						IAsyncResult async = tcpClient.Client.BeginConnect(ip, port, null, null);
						if (!async.AsyncWaitHandle.WaitOne(1500))
						{
							tcpClient.Client.EndConnect(async);
							Console.WriteLine("连接失败");
						}
						else
						{
							tcpClient.Client.EndConnect(async);
							IAsyncResult sendsync2 = tcpClient.Client.BeginSend(communicationbyte, 0, communicationbyte.Length, SocketFlags.None, null, null);
							tcpClient.Client.EndSend(sendsync2);
							Console.WriteLine("连接  communicationbyte");
							await Task.Delay(1000);
							IAsyncResult sendsyncsub60byte = tcpClient.Client.BeginSend(sub60byte, 0, sub60byte.Length, SocketFlags.None, null, null);
							tcpClient.Client.EndSend(sendsyncsub60byte);
							Console.WriteLine("连接 sendsyncsub60byte");
						}
					}
					catch (Exception ex)
					{
						LogHelper.Log("拧紧连接", ex.Message.ToString());
					}
				}
			}
		});

  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的C#实现拧紧OpenProtocol开放协议订阅的示例代码: ```csharp using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace OpenProtocolSubscriber { public class OpenProtocolClient { private TcpClient client; private NetworkStream stream; private StreamReader reader; private StreamWriter writer; private Thread thread; private bool running; public event EventHandler<string> MessageReceived; public OpenProtocolClient(string ipAddress, int port) { client = new TcpClient(ipAddress, port); stream = client.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream); } public void Connect() { running = true; thread = new Thread(new ThreadStart(Receive)); thread.Start(); } public void Disconnect() { running = false; thread.Join(); client.Close(); } public void Subscribe(int messageId) { writer.WriteLine($"0015SUB_{messageId}"); writer.Flush(); } public void Unsubscribe(int messageId) { writer.WriteLine($"0015UNSUB_{messageId}"); writer.Flush(); } public void Receive() { while (running) { try { string message = reader.ReadLine(); MessageReceived?.Invoke(this, message); } catch (Exception ex) { Console.WriteLine(ex.Message); running = false; } } } } } ``` 该代码中OpenProtocolClient类实现了OpenProtocol开放协议的订阅和消息接收功能,通过Subscribe方法可以订阅指定的消息ID,通过MessageReceived事件可以接收到服务推送的消息。需要注意的是,该代码仅为示例代码,具体实现过程可能需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值