using Community; using DAL; using Model; using Model.HSL; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Views; namespace ViewModel.Robots { public class InoRobotVM : FeiYuRobotVM { /// /// 上报异常的委托事件 /// public override event delegeateExcep eventExcepReport; /// /// 刷新阵列点位 /// public override event ShuaxinPoint ShuaxinPointing; #region 机器人控制器返回信息 private string connectionStatus; /// /// 机器人控制器返回信息 /// public string ConnectionStatus { get { return connectionStatus; } set { connectionStatus = value; this.RaisePropertyChanged("ConnectionStatus"); } } #endregion /// /// 交互返回信息 /// public string RCVInfo { get; set; } /// /// 机器人服务器 /// public RobotSocket RobotServer { get; set; } #region 控制器连接 /// /// 控制器通讯对象(用于对控制器的操作通讯) /// public FeiYuHsl ControllerPLCConn { get; set; } #endregion #region 机器人连接 private bool robotConn; /// /// 机器人连接 /// public bool RobotConn { get { return robotConn; } set { robotConn = value; if (value) { //SendControl("$Login\r\n"); //切换自动模式 ConnectionStatus = ""; if (WritePLCData("4105", true)) { ConnectionStatus = "切换自动模式"; } } else { if (RobotStart) { ServoOn = false; RobotStart = false; } //SendControl("$Logout\r\n"); //切换到手动模式 ConnectionStatus = ""; if (WritePLCData("4105", false)) { ConnectionStatus = "切换手动模式"; } } this.RaisePropertyChanged("RobotConn"); } } #endregion #region 启动机器人开关 private bool robotStart; /// /// 启动机器人开关 /// public bool RobotStart { get { return robotStart; } set { robotStart = value; if (MyThread != null) { if (value) { //SendControl("$Start,0\r\n"); //程序启动 //WritePLCData("4098", true); //程序复位 //WritePLCData("4098", false); //程序复位 WritePLCData("4097", false); //程序停止关 WritePLCData("4096", true); //程序启动开 //WritePLCData("4096", false); //程序启动关 ConnectionStatus = ""; ConnectionStatus = ReadPLCData("x=2;0") == true ? "程序运行中" : ""; } else { //程序停止 WritePLCData("4096", false); WritePLCData("4097", true); //WritePLCData("4097", false); ConnectionStatus = ""; ConnectionStatus = ReadPLCData("x=2;0") == true ? "" : "程序关闭"; } } this.RaisePropertyChanged("RobotStart"); } } #endregion #region 使能开关 private bool servoOn; /// /// 使能开关 /// public bool ServoOn { get { return servoOn; } set { servoOn = value; this.RaisePropertyChanged("ServoOn"); if (RobotConn) { if (value) { WritePLCData("4099", true); ConnectionStatus = ""; ConnectionStatus = ReadPLCData("x=2;3") == true ? "使能开" : "使能关"; } //SendControl("$SetMotorsOn,0\r\n"); else { //SendControl("$SetMotorsOff,0\r\n"); WritePLCData("4099", false); ConnectionStatus = ""; ConnectionStatus = ReadPLCData("x=2;3") == true ? "使能开" : "使能关"; } } } } #endregion #region 机器人重置 /// /// 机器人重置 /// /// public override void Reset(object obj) { //SendControl("$Reset\r\n"); WritePLCData("4100", true); //清除急停 WritePLCData("4101", true); //清除报警 WritePLCData("4101", false); //清除报警 //WritePLCData("4098", true); //程序复位 //WritePLCData("4098", false); //程序复位 ConnectionStatus = ""; ConnectionStatus = ReadPLCData("x=2;6") == true ? "" : "清除异常"; } #endregion #region 读写PLC数据 // 步骤: // 1. 定义一个读写请求的队列(线程安全) // 2. 定义一个后台线程,循环处理队列中的请求 // 3. 每次操作完成后等待500ms再处理下一笔 // 4. 操作失败则立即重试当前请求,不等待,重试5次仍失败则移除 // 5. ReadWritePLCData方法只负责将请求加入队列,并返回操作结果(同步等待) private enum PlcRWType { Read, Write } private class PlcRWRequest { public PlcRWType RWType { get; set; } public string Address { get; set; } public bool? WriteData { get; set; } // 仅写时有值 public TaskCompletionSource Completion { get; set; } public int RetryCount { get; set; } = 0; public bool? ReadResult { get; set; } // 仅读时有值 } private readonly Queue _plcRWQueue = new Queue(); private readonly object _plcRWQueueLock = new object(); private bool _plcRWWorkerStarted = false; /// /// 统一PLC读写方法 /// /// PLC地址 /// true=写,false=读 /// 写入时的数据 /// 读时返回读结果,写时返回写是否成功 public bool ReadWritePLCData(string address, bool isWrite, bool writeData = false) { // 启动后台线程(只启动一次) if (!_plcRWWorkerStarted) { _plcRWWorkerStarted = true; Task.Run(() => PlcRWWorker()); } var tcs = new TaskCompletionSource(); var request = new PlcRWRequest { RWType = isWrite ? PlcRWType.Write : PlcRWType.Read, Address = address, WriteData = isWrite ? (bool?)writeData : null, Completion = tcs }; lock (_plcRWQueueLock) { _plcRWQueue.Enqueue(request); } // 同步等待操作结果 tcs.Task.Wait(); if (!isWrite && request.ReadResult.HasValue) return request.ReadResult.Value; return tcs.Task.Result; } private void PlcRWWorker() { while (true) { PlcRWRequest request = null; lock (_plcRWQueueLock) { if (_plcRWQueue.Count > 0) { request = _plcRWQueue.Peek(); } } if (request != null) { bool result = false; bool isRead = request.RWType == PlcRWType.Read; if (ControllerPLCConn?.PLC != null) { try { if (isRead) { bool readVal = ControllerPLCConn.PLC.ReadBool(request.Address); request.ReadResult = readVal; result = true; } else { result = ControllerPLCConn.PLC.Write(request.Address, request.WriteData ?? false); } } catch { result = false; } } if (result) { // 操作成功,移除队列,通知完成 lock (_plcRWQueueLock) { _plcRWQueue.Dequeue(); } request.Completion.TrySetResult(isRead ? (request.ReadResult ?? false) : true); Thread.Sleep(300); } else { request.RetryCount++; if (request.RetryCount >= 5) { // 超过重试次数,移除队列,返回失败 lock (_plcRWQueueLock) { _plcRWQueue.Dequeue(); } request.Completion.TrySetResult(false); Thread.Sleep(10); } else { // 立即重试,不出队 Thread.Sleep(10); } } } else { Thread.Sleep(50); // 队列为空时稍作等待 } } } public bool WritePLCData(string address, bool data) { return ReadWritePLCData(address, true, data); } public bool ReadPLCData(string address) { return ReadWritePLCData(address, false); } #endregion #region 构造函数 /// /// 构造函数 /// /// public InoRobotVM(MachineModel machine, FeiYuHsl plc) { MyWindow = new InoRobotWind(); MyWindow.DataContext = this; MachineObj = machine; ResetCommand = new DelegateCommand(); ResetCommand.ExecuteAction = new Action(Reset); RunSelectedRobotPointCommand = new DelegateCommand(); RunSelectedRobotPointCommand.ExecuteAction = new Action(RunSelectedRobotPointPoint); EditorRobotPointCommand = new DelegateCommand(); EditorRobotPointCommand.ExecuteAction = new Action(EditorRobotPoint); SaveRobotPointCommand = new DelegateCommand(); SaveRobotPointCommand.ExecuteAction = new Action(SaveRobotPoint); UpToolCoordinateCommand = new DelegateCommand(); UpToolCoordinateCommand.ExecuteAction = new Action(UpToolCoordinate); RobotPGMoveCommand = new DelegateCommand(); RobotPGMoveCommand.ExecuteAction = new Action(RobotPGMove); GoHomeCommand = new DelegateCommand(); GoHomeCommand.ExecuteAction = new Action(GoHome); SaveLaserCommand = new DelegateCommand(); SaveLaserCommand.ExecuteAction = new Action(SaveLaser); RobotPer = dal.GetRobot()[0]; SpeedS = RobotPer.SpeedS; ControllerConn = new RobotSocket(RobotPer.IpStr, RobotPer.Port); CommandInteraction = new RobotSocket(RobotPer.IpStr, RobotPer.Port1); ControllerPLCConn = plc; //控制器PLC连接 // 启动服务器监听并分配客户端 StartRobotServerAndAssignClients(); RobotConn = false; ServoOn = false; RobotStart = false; EditingEnabled = false; TeachShow = new ShowInfo(); AutoShow = new ShowInfo(); WarningShow = new ShowInfo(); SErrorShow = new ShowInfo(); SafeDoorShow = new ShowInfo(); EStopShow = new ShowInfo(); ErrorShow = new ShowInfo(); PausedShow = new ShowInfo(); RunningShow = new ShowInfo(); ReadyShow = new ShowInfo(); //初始化命令参数 CommandModel = new RobotPoint(); MyThread = new Thread(ReceivesRunState); MyThread.IsBackground = true; MyThread.Start(); MyThread1 = new Thread(ReceivesRemoteState); MyThread1.IsBackground = true; MyThread1.Start(); HomeStep = GengralProcessEnum.Start; CommonList = new List() { new CommonClass() { ID=0,CommonName="公共点位"}, //new CommonClass() { ID=1,CommonName="取料盘"}, //new CommonClass() { ID=2,CommonName="放料盘"} }; } /// /// 启动服务器监听并分配客户端连接到ControllerConn和CommandInteraction /// private void StartRobotServerAndAssignClients() { // 启动服务器监听 RobotServer = new RobotSocket("192.168.5.100", 2000); // 监听所有网卡 RobotServer.StartServer(); // 新线程处理客户端分配 new Thread(() => { while (true) { Thread.Sleep(10); // 阻塞等待客户端连接 Socket clientSocket = RobotServer.AcceptClientWithReturn(); if (clientSocket == null) continue; // 获取客户端端口 int remotePort = ((System.Net.IPEndPoint)clientSocket.RemoteEndPoint).Port; // 分配到ControllerConn或CommandInteraction if (remotePort == RobotPer.Port) { if (ControllerConn == null) ControllerConn = new RobotSocket(RobotPer.IpStr, RobotPer.Port); ControllerConn.MySocket = clientSocket; ControllerConn.IsServer = false; } else if (remotePort == RobotPer.Port1) { if (CommandInteraction == null) CommandInteraction = new RobotSocket(RobotPer.IpStr, RobotPer.Port1); CommandInteraction.MySocket = clientSocket; CommandInteraction.IsServer = false; } } }) { IsBackground = true }.Start(); } public override void SaveLaser(object obj) { if (dal.UpdateRobotPointSpareField(SelectedRobotPoint) > 0) { MyMessageBox.Show("保存成功"); } else { MyMessageBox.Show("保存失败"); } } #endregion #region 机器人控制器 #region 连接控制器并接收控制器状态信息 private void ReceivesRunState() { while (true) { try { if (ControllerPLCConn.ConnStatu.StatusBackground == ColorStr.Green) { continue; } try { ControllerPLCConn.Conneced(); //开启控制器连接 } catch (Exception) { ControllerPLCConn.ConnStatu.StatusBackground = ColorStr.Red; ControllerPLCConn.ConnStatu.StatuInfo = "机器人连接失败"; ControllerPLCConn.ConnStatu.StatusForeground = ColorStr.White; ControllerPLCConn.PLC.Disconnect(); //关闭连接 continue; //跳出本次循环 } if (ControllerPLCConn.PLC != null && (ControllerPLCConn.PLC as ModBusTcpHsl).NetworkConn != null) { try { DateTime lastHeartbeat = DateTime.Now; bool lastHeartbeatState = false; while (ControllerPLCConn.PLC != null) { try { // 读取心跳线圈 bool heartbeat = ControllerPLCConn.PLC.ReadBool("x=2;13"); if (heartbeat) { lastHeartbeat = DateTime.Now; lastHeartbeatState = true; ControllerPLCConn.ConnStatu.StatusBackground = ColorStr.Green; ControllerPLCConn.ConnStatu.StatuInfo = "连接正常"; ControllerPLCConn.ConnStatu.StatusForeground = ColorStr.White; break; } else { // 记录上次心跳为false的时间 if (lastHeartbeatState) { lastHeartbeat = DateTime.Now; lastHeartbeatState = false; } } // 超过2秒未检测到心跳 if ((DateTime.Now - lastHeartbeat).TotalMilliseconds > 2000) { ControllerPLCConn.ConnStatu.StatuInfo = "连接异常"; ControllerPLCConn.ConnStatu.StatusBackground = ColorStr.Yellow; ControllerPLCConn.ConnStatu.StatusForeground = ColorStr.Black; ControllerPLCConn.PLC.Disconnect(); break; } Thread.Sleep(100); // 减少CPU占用 } catch (Exception ex) { eventExcepReport?.Invoke("机器人控制连接异常:" + ex.Message); ControllerPLCConn.ConnStatu.StatuInfo = "机器人控制连接异常"; ControllerPLCConn.ConnStatu.StatusBackground = ColorStr.Yellow; ControllerPLCConn.ConnStatu.StatusForeground = ColorStr.Black; ControllerPLCConn.PLC.Disconnect(); //关闭连接 break; } } } catch { } } // 断开后,显示连接异常 //if (ControllerConn != null) //{ // ControllerConn.ConnStatu.StatuInfo = "连接异常"; // ControllerConn.ConnStatu.StatusBackground = ColorStr.Yellow; // ControllerConn.ConnStatu.StatusForeground = ColorStr.Black; //} } catch { // 忽略外层异常,继续循环等待连接 } } } #endregion #region 机器人控制信息分析 /// /// 机器人控制信息分析 /// public void StateAnalytical(string RunStateMsg) { if (RunStateMsg.ToLower().Contains("#getstatus")) { if (RunStateMsg.Substring(12, 1) == "1") { TeachShow.StatusBackground = ColorStr.Green; } else { TeachShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(13, 1) == "1") { AutoShow.StatusBackground = ColorStr.Green; } else { AutoShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(14, 1) == "1") { WarningShow.StatusBackground = ColorStr.Gray; } else { WarningShow.StatusBackground = ColorStr.Green; } if (RunStateMsg.Substring(15, 1) == "1") { SErrorShow.StatusBackground = ColorStr.Gray; } else { SErrorShow.StatusBackground = ColorStr.Green; } if (RunStateMsg.Substring(16, 1) == "1") { SafeDoorShow.StatusBackground = ColorStr.Yellow; } else { SafeDoorShow.StatusBackground = ColorStr.Green; } if (RunStateMsg.Substring(17, 1) == "1") { EStopShow.StatusBackground = ColorStr.Red; } else { EStopShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(18, 1) == "1") { ErrorShow.StatusBackground = ColorStr.Green; } else { ErrorShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(19, 1) == "1") { PausedShow.StatusBackground = ColorStr.Green; } else { PausedShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(20, 1) == "1") { RunningShow.StatusBackground = ColorStr.Green; } else { RunningShow.StatusBackground = ColorStr.Gray; } if (RunStateMsg.Substring(21, 1) == "1") { ReadyShow.StatusBackground = ColorStr.Green; } else { ReadyShow.StatusBackground = ColorStr.Gray; } ErrorMsgShow = RunStateMsg.Substring(23, 4); } if (RunStateMsg.ToLower().Contains("#setmotorson")) { ConnectionStatus = "ServoOn"; } if (RunStateMsg.ToLower().Contains("#setmotorsoff")) { ConnectionStatus = "ServoOff"; } if (RunStateMsg.ToLower().Contains("#login")) { //EditingEnabled = Visibility.Visible; ConnectionStatus = "远程连接开启成功"; } if (RunStateMsg.ToLower().Contains("#logout")) { //EditingEnabled = Visibility.Collapsed; ConnectionStatus = "远程连接已关闭"; } if (RunStateMsg.ToLower().Contains("#start")) { ConnectionStatus = "启动机器人软件"; } if (RunStateMsg.ToLower().Contains("#stop")) { ConnectionStatus = "关闭机器人"; } if (RunStateMsg.ToLower().Contains("#reset")) { ConnectionStatus = "重置成功"; } RunStateMsg = null; } #endregion #region 机器人PLC心跳测试 private void PLC_HeartBeatTest() { try { if (ControllerPLCConn.PLC != null) { ControllerPLCConn.PLC.ReadBool("x=2;13"); } } catch { } } #endregion #endregion #region 指令交互 #region 接收远程控制状态信息 /// /// 接收机器人状态信息 /// private void ReceivesRemoteState() { while (true) { try { // 等待CommandInteraction对象被分配(即有客户端连接到指定端口) if (CommandInteraction == null || CommandInteraction.MySocket == null || !CommandInteraction.MySocket.Connected || (CommandInteraction.MySocket.Poll(1, SelectMode.SelectRead) && CommandInteraction.MySocket.Available == 0)) { CommandInteraction.ConnStatu.StatusBackground = ColorStr.Gray; CommandInteraction.ConnStatu.StatuInfo = "未连接"; CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; continue; //跳出本次循环 } CommandInteraction.ConnStatu.StatusBackground = ColorStr.Green; CommandInteraction.ConnStatu.StatuInfo = "连接正常"; CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; while (true) { try { RunStateAnalytical(CommandInteraction.ReceivesMessageB()); } catch (SocketException) { CommandInteraction.ConnStatu.StatuInfo = "连接异常"; CommandInteraction.ConnStatu.StatusBackground = ColorStr.Red; CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; CommandInteraction.ShutDown(); break; } catch (Exception ex) { eventExcepReport?.Invoke("机器人控制连接异常" + ex.Message); CommandInteraction.ConnStatu.StatuInfo = "远程控制消息接收失败"; CommandInteraction.ConnStatu.StatusBackground = ColorStr.Red; CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; CommandInteraction.ShutDown(); break; } } ////断开后,显示连接异常 //if (CommandInteraction != null) //{ // CommandInteraction.ConnStatu.StatuInfo = "连接异常"; // ControllerConn.ConnStatu.StatusBackground = ColorStr.Yellow; // ControllerConn.ConnStatu.StatusForeground = ColorStr.Black; //} } catch { // 忽略外层异常,继续循环等待连接 } } } //private void ReceivesRemoteState() //{ // while (true) // { // try // { // CommandInteraction.StartConn(); //开启连接 // } // catch (Exception) // { // CommandInteraction.ConnStatu.StatusBackground = ColorStr.Red; // CommandInteraction.ConnStatu.StatuInfo = "未连接"; // CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; // CommandInteraction.ShutDown();//关闭连接 // continue; // } // CommandInteraction.ConnStatu.StatusBackground = ColorStr.Green; // CommandInteraction.ConnStatu.StatuInfo = "连接正常"; // CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; // while (true) // { // try // { // RunStateAnalytical(CommandInteraction.ReceivesMessageB()); // } // catch (SocketException) // { // CommandInteraction.ConnStatu.StatuInfo = "连接异常"; // CommandInteraction.ConnStatu.StatusBackground = ColorStr.Red; // CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; // CommandInteraction.ShutDown();//关闭连接 // break; // } // catch (Exception ex) // { // eventExcepReport("机器人控制连接异常" + ex.Message);//抛出异常 // CommandInteraction.ConnStatu.StatuInfo = "远程控制消息接收失败"; // CommandInteraction.ConnStatu.StatusBackground = ColorStr.Red; // CommandInteraction.ConnStatu.StatusForeground = ColorStr.White; // CommandInteraction.ShutDown();//关闭连接 // break; // } // } // } //} #endregion #region 机器人运行状态解析 string[] RcvStr { get; set; } /// /// 机器人运行状态解析 /// public void RunStateAnalytical(string RemoteStateMsg) { if (string.IsNullOrEmpty(RemoteStateMsg)) { return; } RcvStr = RemoteStateMsg.Replace("\0", "").Split('\r')[0].Split(','); //RcvStr = RcvStr[0].Split(','); switch (RcvStr[0].ToLower()) { case "start": RcvShowInfo = "连接201端口成功"; break; case "movetohome": RcvShowInfo = "回原点成功"; break; case "robotpos": RobotCurPos = new RobotPoint() { PointX = Math.Round(Convert.ToDouble(RcvStr[1]), 4), PointY = Math.Round(Convert.ToDouble(RcvStr[2]), 4), PointZ = Math.Round(Convert.ToDouble(RcvStr[3]), 4), PointU = Math.Round(Convert.ToDouble(RcvStr[4]), 4), PointV = Math.Round(Convert.ToDouble(RcvStr[5]), 4), PointW = Math.Round(Convert.ToDouble(RcvStr[6]), 4) }; break; case "runpointok": //点位运行OK RcvShowInfo = RcvStr[0].ToLower().ToString(); //记录返回日志 RecordLog("(Robot→PC)" + "运行点位完毕,返回代码【" + RcvShowInfo + "】"); break; case "settoolok"://设置工具坐标OK RcvShowInfo = RcvStr[0].ToLower().ToString(); break; case "cpok": //单轴运行OK RcvShowInfo = RcvStr[0].ToLower().ToString(); break; default: RCVInfo = RcvStr[0].ToLower().ToString(); break; } } #endregion #endregion #region 发送控制命令 /// /// 发送控制命令给机器人 /// public void SendControl(string strMgs) { if (ControllerConn != null) { ControllerConn.Send(strMgs); } } #endregion #region 发送运行命令 /// /// 发送运行命令 /// public bool SendCommand(RobotPoint RP) { try { // RP.SpeedGear = RP.SpeedGear * (RobotPer.SpeedS / 100); int SpeedBaiFenbi = Convert.ToInt32(RP.SpeedGear * RobotPer.SpeedS / 100); RcvShowInfo = ""; //string sendMsg = string.Format("@{0} {1} {2} {3} {4} {5} {6} {7},{8},{9}\r\n", RP.Command, RP.SpeedGear, RP.PointX, RP.PointY, RP.PointZ, RP.PointU, RP.PointV, RP.PointW, RP.HandRL, RP.ToolNum); string sendMsg = string.Format("@{0} {1} {2} {3} {4} {5} {6} {7},{8},{9}\r\n", RP.Command, SpeedBaiFenbi, RP.PointX, RP.PointY, RP.PointZ, RP.PointU, RP.PointV, RP.PointW, RP.HandRL, RP.ToolNum); CommandInteraction.Send(sendMsg); //记录移动日志 RecordLog("(PC→Robot)" + RP.PointName + "【" + sendMsg + "】"); return true; } catch { return false; } } #endregion #region 机器人点位编辑相关 #region 机器人PG移动方法 /// /// 机器人PG移动方法 /// public override void RobotMove(string direction) { CommandModel = new RobotPoint(); switch (direction) { case "+X": case "-X": CommandModel.Command = direction; CommandModel.PointX = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); break; case "+Y": case "-Y": CommandModel.Command = direction; CommandModel.PointY = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); break; case "+Z": case "-Z": CommandModel.Command = direction; CommandModel.PointZ = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); break; case "+U": case "-U": CommandModel.Command = direction; CommandModel.PointU = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); break; case "+V": case "-V": CommandModel.Command = direction; CommandModel.PointV = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); break; case "+W": case "-W": CommandModel.Command = direction; CommandModel.PointW = RobotTuningDis; CommandModel.SpeedGear = SelectedRobotPoint.SpeedGear; SendCommand(CommandModel); //CommandModel.Command = direction; //CommandModel.SpeedGear = RobotTuningDis; //SendCommand(CommandModel); break; } } #endregion /// /// 鼠标点击PG移动 /// /// public override void RobotPGMove(object obj) { try { Button btn = obj as Button; RobotTuningDis = Convert.ToDouble(btn.ToolTip); RobotMove(btn.Tag.ToString()); } catch (Exception) { } } #region 编辑点位 /// /// 编辑点位 /// /// public override void EditorRobotPoint(object obj) { if (SelectedRobotPoint != null && SelectedRobotPoint.ID > 0) { EditingEnabled = true; } else { MessageBox.Show("请选择要编辑的点位"); } } #endregion #region 保存机器人点位 /// /// 保存机器人点位 /// /// public override void SaveRobotPoint(object obj) { //RobotCurPos = null; if (MessageBox.Show("请确定要保存当前点位吗?", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { if (RobotCurPos != null) { try { SelectedRobotPoint.PointX = RobotCurPos.PointX; SelectedRobotPoint.PointY = RobotCurPos.PointY; SelectedRobotPoint.PointZ = RobotCurPos.PointZ; SelectedRobotPoint.PointU = RobotCurPos.PointU; SelectedRobotPoint.PointV = RobotCurPos.PointV; SelectedRobotPoint.PointW = RobotCurPos.PointW; ShuaxinPointing(SelectedRobotPoint.PointClass);//刷新矩阵点位 if (dal.UpdateRobotPoint(SelectedRobotPoint) > 0) { MessageBox.Show("保存成功"); } else { MessageBox.Show("保存失败"); } } catch (Exception ex) { MessageBox.Show("保存失败\r\n" + ex.Message); } } else { MessageBox.Show("机器人点位保存失败,未能获取机器人的当前点位信息,请重试"); } } } #endregion #region 运行到选中点位 /// /// 运行到选中点位 /// /// public override void RunSelectedRobotPointPoint(object obj) { if (SelectedRobotPoint != null && SelectedRobotPoint.ID > 0) { SendCommand(SelectedRobotPoint); } else { MessageBox.Show("请选择要运行的点位"); } } #endregion #endregion #region 手动回原点 /// /// 手动回原点 /// /// public override void GoHome(object obj) { RobotPoint rrp = RobotPointList.Where(w => w.PointType == 1 && w.PointClass == 0).FirstOrDefault(); RunRobotPoint(rrp); } #endregion #region 机器人回原点 /// /// 机器人回原点 /// public override void RobotOrgin() { switch (HomeStep) { case GengralProcessEnum.Start: if (ControllerPLCConn != null && ControllerPLCConn.ConnStatu.StatuInfo == "连接正常") { RobotConn = false; HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step1: if (HomeTime.AddMilliseconds(1000) < DateTime.Now) { //切换自动模式 RobotConn = true; HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step2: if (HomeTime.AddMilliseconds(1000) < DateTime.Now) { Reset(0); //重置 HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step3: if (HomeTime.AddMilliseconds(2000) < DateTime.Now) { //启动机器人程序 RobotStart = true; HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step4: if (HomeTime.AddMilliseconds(1000) < DateTime.Now) { ServoOn = true; //开启使能 HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step5: RobotCurPos = null; RobotPoint rp = new RobotPoint() { Command = "A", SpeedGear = 1 }; SendCommand(rp); HomeTime = DateTime.Now; HomeStep++; break; case GengralProcessEnum.Step6: if (HomeTime.AddMilliseconds(1000) < DateTime.Now) { RobotCurPos = null; RobotPoint rp1 = new RobotPoint() { Command = "A", SpeedGear = 1 }; SendCommand(rp1); HomeTime = DateTime.Now; HomeStep++; } break; case GengralProcessEnum.Step7: if (RobotCurPos != null) { //回待机点 RunRobotPoint(RobotPointList.Where(w => w.PointType == 1).FirstOrDefault()); HomeStep = GengralProcessEnum.End; } else if (HomeTime.AddMilliseconds(1000) < DateTime.Now) { //流程重置,重新发送指令启动 RobotConn = false; HomeTime = DateTime.Now; HomeStep = GengralProcessEnum.Start; } break; } } #endregion #region 更新工具坐标系 /// /// 更新工具坐标系 /// /// public override void UpToolCoordinate(object obj) { if (MessageBox.Show("错误的设置可能带来风险,你确定要更新工具坐标系吗?", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Exclamation) != MessageBoxResult.OK) { return; } RobotPoint p1 = RobotPointList.Where(r => r.PointType == 100).FirstOrDefault(); RobotPoint p2 = RobotPointList.Where(r => r.PointType == 101).FirstOrDefault(); double d = Math.Abs((Math.Abs(p1.PointU) - Math.Abs(p2.PointU))); if (d < 178) { MessageBox.Show("工具坐标点位的角度必须相差180度,请重新调整工具坐标点位"); return; } RobotPoint p = CalcTool(p1, p2); p.Command = "UpTool"; p.ToolNum = 1; SendCommand(p); } #endregion #region 工具坐标系的创建算法 /// /// 获取工具坐标系参数 /// /// 第一个坐标点 /// 旋转180度后的第二个坐标点 /// 工具坐标序号 /// public RobotPoint CalcTool(RobotPoint p1, RobotPoint p2) { double xTool = (p1.PointX - p2.PointX) / 2; double yTool = (p1.PointY - p2.PointY) / 2; double theta = Math.Atan2(yTool, xTool); //Math.Atan2(xTool, yTool); theta = theta - (p2.PointU * Math.PI / 180);//角度转弧度 double rTool = Math.Sqrt(xTool * xTool + yTool * yTool); xTool = Math.Cos(theta) * rTool; yTool = Math.Sin(theta) * rTool; RobotPoint toolPoint = new RobotPoint() { PointX = xTool, PointY = yTool }; Tool_X = xTool; Tool_Y = yTool; return toolPoint; } /// /// 世界坐标转工具坐标 /// /// /// /// /// private RobotPoint WorldToTool(RobotPoint wp, double xtool, double ytool) { RobotPoint rp = new RobotPoint(); rp.PointU = wp.PointU; rp.PointZ = wp.PointZ; rp.PointX = wp.PointX + (xtool * Math.Cos(wp.PointU) - ytool * Math.Sin(wp.PointU)); rp.PointY = wp.PointY + (xtool * Math.Sin(wp.PointU) + ytool * Math.Cos(wp.PointU)); return rp; } /// /// 工具坐标系 X系数 /// public double Tool_X { get; set; } /// /// 工具坐标系 Y系数 /// public double Tool_Y { get; set; } public RobotPoint wordPoint = new RobotPoint() { PointX = -145.011, PointY = 423.095, PointZ = -10, PointU = 179.972 }; public RobotPoint toolPoint = new RobotPoint() { PointX = -144.166, PointY = 510.445, PointZ = -10, PointU = 179.972 }; /// /// 工具坐标与世界坐标的转换 /// /// /// /// public RobotPoint Pointzhuanghuan(RobotPoint Rp, bool WordToTool) { Tool_X = -0.802; Tool_Y = -87.350; //Rp.PointU =Math.Round( Rp.PointU-180,3); Rp.PointU = (-1 * Math.PI / 180); RobotPoint rp = new RobotPoint(); rp.PointU = Rp.PointU; rp.PointZ = Rp.PointZ; if (WordToTool) //世界坐标转工具坐标 { double xcos = Math.Round(Rp.PointX * Math.Cos(Rp.PointU), 3); double xsin = Math.Round(Rp.PointX * Math.Sin(Rp.PointU), 3); double ysin = Math.Round(Rp.PointY * Math.Sin(Rp.PointU), 3); double ycos = Math.Round(Rp.PointY * Math.Cos(Rp.PointU), 3); rp.PointX = (Rp.PointX * Math.Cos(Rp.PointU) - Rp.PointY * Math.Sin(Rp.PointU)) - Tool_X; rp.PointY = (Rp.PointX * Math.Sin(Rp.PointU) + Rp.PointY * Math.Cos(Rp.PointU)) - Tool_Y; } else //否则 工具坐标转世界坐标 { rp.PointX = Rp.PointX - (Tool_X * Math.Cos(Rp.PointU) + Tool_Y * Math.Sin(Rp.PointU)); rp.PointY = Rp.PointY - (Tool_X * Math.Sin(Rp.PointU) - Tool_Y * Math.Cos(Rp.PointU)); } return rp; } #endregion #region 运行机械手点位 /// /// 运行机械手点位 /// /// /// public override bool RunRobotPoint(RobotPoint point, bool runType = false) { return SendCommand(point); } #endregion #region 机器人移动日志 byte[] data { get; set; } /// /// 文件夹路径 /// string path { get; set; } /// /// 文件路径 /// string paths { get; set; } /// /// 打开的文件流对象 /// FileStream FS { get; set; } /// /// 记录日志信息到文件 /// /// private void RecordLog(string showMag) { try { lock (this) { path = @"D:\\LAGLog\RobotLog"; //文件夹路径 paths = @"D:\\LAGLog\RobotLog\" + DateTime.Now.ToString("D") + ".txt"; //文件路径 以年月日为名称 //创建文件夹 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //打开或创建文件 FS = File.Open(paths, FileMode.Append); //获得字节数组 data = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + showMag + "\r\n"); //开始写入 FS.Write(data, 0, data.Length); //清空缓冲区、关闭流 FS.Flush(); FS.Close(); } } catch { } } #endregion /// /// 比较坐标是否到位 /// /// /// public override bool Bijiao(RobotPoint point) { double x = Math.Abs(point.PointX - RobotCurPos.PointX); double y = Math.Abs(point.PointY - RobotCurPos.PointY); double z = Math.Abs(point.PointZ - RobotCurPos.PointZ); double u = Math.Abs(point.PointU - RobotCurPos.PointU); double v = Math.Abs(point.PointV - RobotCurPos.PointV); double w = Math.Abs(Math.Abs(point.PointW) - Math.Abs(RobotCurPos.PointW)); if (x <= 0.1 && y <= 0.1 && z <= 0.1 && u <= 0.1 && v <= 0.1 && w <= 0.1) { return true; } else { return false; } } } }