|
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using System.IO.Ports;
- using System.Threading;
- using System.Collections.Concurrent;
- using BPA.Helper;
-
- namespace BPASmartClient.SerialPort
- {
- public class RobotGripperHelper
- {
-
- private System.IO.Ports.SerialPort comPort = new System.IO.Ports.SerialPort();
- public bool IsOpen => comPort.IsOpen;
-
- public bool Open(string portName, int baudRate)
- {
- if (!System.IO.Ports.SerialPort.GetPortNames().Contains(portName))
- {
- MessageLog.GetInstance.Show($"{portName} 串口不存在");
- }
- if (!comPort.IsOpen)
- {
- comPort.PortName = portName;
- comPort.BaudRate = baudRate;
- comPort.DataBits = 8;
- comPort.Parity = Parity.None;
- comPort.StopBits = StopBits.One;
- /*comPort.ReadTimeout = 1000;
- comPort.WriteTimeout = 1000;*/
- //comPort.RtsEnable = true; //设置为 true后会读取不到数据
- comPort.DtrEnable = true;//获取或设置一个值,该值在串行通信过程中启用数据终端就绪 (DTR) 信号。
- //comPort.RtsEnable = true;//获取或设置一个值,该值指示在串行通信中是否启用请求发送 (RTS) 信号
- try
- {
- comPort.Open();
- }
- catch (Exception ex)
- {
- MessageLog.GetInstance.ShowEx(ex.ToString());
- }
- }
- /* TaskManage.GetInstance.StartLong(new Action(() =>
- {
-
- Thread.Sleep(5000);
- }), $"开启电爪设备通讯", true);*/
- MessageLog.GetInstance.Show($"{portName} 串口打开成功");
- return comPort.IsOpen;
- }
- public bool Stop(string portName)
- {
- comPort.Close();
- MessageLog.GetInstance.Show($"{portName} 串口关闭成功");
- return comPort.IsOpen;
- }
- /// <summary>
- /// 舵机控制 #000P1300T1000!
- /// </summary>
- /// <param name="index">通道号 0 - 5</param>
- /// <param name="value">夹爪幅度 0500 - 2500</param>
- /// <param name="time">夹爪时间 0000-9999</param>
- public void Write(byte index, string value, string time = "1000")
- {
- byte[] PwmNumber = Encoding.ASCII.GetBytes(value);
- byte[] Times = Encoding.ASCII.GetBytes(time);
- //byte[] buffers = new byte[15] { 0x23, 0x30, 0x30, 0x30, 0x50, PwmNumber[0], PwmNumber[1], PwmNumber[2], PwmNumber[3], 0x54, Times[0], Times[1], Times[2], Times[3], 0x21 };
- byte[] buffers = new byte[15] { 0x23, 0x30, 0x30, 0x30, 0x50, 0x31, 0x30, 0x35, 0x30, 0x54, 0x31, 0x30, 0x30, 0x30, 0x21 };
- if (IsOpen) comPort.Write(buffers, 0, buffers.Length);
- }
- }
- }
|