URRobotControl.cs 15.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
using log4net;
using URSoldering.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using URToolKit;

namespace URSoldering.DeviceLibrary
{

    public class URRobotControl
    {
        private static string spiltStr = ",";
        public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public static TcpClient controlTcp = new TcpClient();
        public static URPointValue LastPoint = new URPointValue();

        public static string RobotIp = "";
        public static int ControlPort = 29999;

        public static double Robot_LIM_Z = (double)ConfigAppSettings.GetNumValue(Setting_Init.Soldering_LIM_Z);

        private static string CMD_powerOn = "power on";
        private static string CMD_powerOff = "power off";
        private static string CMD_robotMode = "robotmode";
        private static string CMD_brakeRelease = "brake release";
        private static string CMD_Safetymode = "Safetymode";

        private static string REV_PowerOn = "powering on";
        private static string REV_BrakeRelease = "brake releasing";
        private static string REV_RobotMode = "robotmode";
        private static string REV_SafetyMode = "safetymode";
        /// <summary>
        /// 记录最后一次收到OK的时间
        /// </summary>
        private static Dictionary<string, DateTime> LastOkMap = new Dictionary<string, DateTime>();

        /// <summary>
        /// 是否锁住轴
        /// </summary>
        public static bool IsLock = true;
        /// <summary>
        /// 是否运行中
        /// </summary>
        public static bool IsRun = false;

        public static bool IsStartConnect = false;
        private static int startCount = 0;
        /// <summary>
        /// 上一次启动的时间,UR机械臂启动需要时间,默认需要3分钟,若三分钟后还没有链接,需要重新启动
        /// </summary>
        private static DateTime PreStartTime = DateTime.Now;
        private static int StartTimeOutSeconds = 10000;

        public static string WarnMsg = "";
        private static System.Timers.Timer reconnectTimer = null;

        public static void InitConfig(string ip)
        {
            RobotIp = ip;
        }
        public static string LogName
        {
            get { return "【" + RobotIp + " ," + ControlPort + "】"; }
        }
        public static void Test()
        {
            URWithOutTP a = new URWithOutTP();          //创建对象
            a.restartURControl(RobotIp);         //重置UR控制器,然后可以利用dashboard,poweron,brake release  
        }
        /// <summary>
        /// 开始启动连接机器人
        /// </summary>
        /// <returns></returns>
        public static bool StartRobot()
        {
            if (reconnectTimer == null)
            {
                reconnectTimer = new System.Timers.Timer();
                reconnectTimer.AutoReset = true;
                reconnectTimer.Interval = 1000;
                reconnectTimer.Elapsed += reconnectTimer_Elapsed;
                reconnectTimer.Enabled = false;
            }
            IsStartConnect = true;
            if (IsRun)
            {
                return true;
            }
            return StartConnect();
        }

        private static bool StartConnect()
        {
            try
            {
                if (RobotIp.Equals(""))
                {
                    LogUtil.info("未初始化UR机械臂的IP地址");
                    return false;
                }
                if (startCount > 0)
                {
                    TimeSpan span = DateTime.Now - PreStartTime;
                    if (span.TotalMilliseconds < StartTimeOutSeconds)
                    {
                        LogUtil.info("" + LogName + "正在连接中,不需要重连");
                        return true;
                    }
                    else
                    {
                        LogUtil.info("" + LogName + "距离上次启动已经超过10秒,重新开始连接");
                        StopRobot();
                    }
                }
                WarnMsg = "";
                PreStartTime = DateTime.Now;
                startCount++;


                controlTcp = new TcpClient();
                bool result = controlTcp.connect(RobotIp, ControlPort, new TcpClient.HandleMessage(OnControlRevice));
                if (!result)
                {
                    LogUtil.error(LOGGER, "连接" + LogName + "失败");
                    return false;
                }
                else
                {
                    LogUtil.info(LOGGER, "连接" + LogName + "成功");
                }
                //发送
                controlTcp.sendLine(CMD_Safetymode);
                //controlTcp.sendLine(CMD_robotMode);
                preCheckTime = DateTime.Now;
                return true;
            }
            catch (Exception ex)
            {
                LogUtil.error("" + LogName + "starttcp error:" + ex.ToString());
                return false;
            }
        }
        private static DateTime preCheckTime = DateTime.Now;
        private static bool IsInPorcess = false;
        private static void reconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (IsInPorcess)
            {
                return;
            }
            IsInPorcess = true;
            try
            {
                if (IsStartConnect)
                {
                    TimeSpan span = DateTime.Now - preCheckTime;
                    if (span.TotalSeconds > 30)
                    {
                        preCheckTime = DateTime.Now;
                        //判断500在连接上,则获取状态
                        if (controlTcp.IsConnected())
                        {
                            controlTcp.sendLine(CMD_robotMode);
                        }
                        else
                        {
                            LogUtil.error("" + LogName + "reconnectTimer_Elapsed检测到 机械臂已经断开,需要重连!");
                            stopTcp();
                            StartConnect();
                        }
                    }
                }
                if (IsRun)
                {
                    //如果监听的断开,直接重新连接
                    if (!URRobotClient.IsConnected())
                    {
                        URRobotClient.StartListen(RobotIp);
                    }
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error("" + LogName + "  定时器出错:" + ex.ToString());
            }
            IsInPorcess = false;
        }
        public static bool SendCMD(string cmd, int msendons)
        {
            try
            {
                LogUtil.URSInfo(LogName + "将于【" + msendons + "】后发送数据:" + cmd);
                if (msendons > 0)
                {
                    Task.Factory.StartNew(delegate ()
                    {
                        Thread.Sleep(msendons);
                        controlTcp.sendLine(cmd);
                    });
                }
                else
                {
                    controlTcp.sendLine(cmd);
                }
            }
            catch (Exception ex)
            {
                LogUtil.URSError("" + LogName + "SendCMD出错啦cmd[" + cmd + "]msendons[" + msendons + "]" + ex.ToString());
            }
            return true;
        }
        public static bool GetRobotMode()
        {
            return SendCMD(CMD_robotMode, 0);
        }

       
        private static void OnControlRevice(string message)
        {
            if (message == null || message.Equals(""))
            {
                return;
            }
            try
            {
                //Connected: Universal Robots Dashboard Server
                message = message.Replace("\n", "");
                LogUtil.URSInfo(LogName + "收到数据:" + message);
                if (message.ToLower().IndexOf(REV_PowerOn) >= 0)
                {
                    SendCMD(CMD_brakeRelease, 1000);
                }
                else if (message.ToLower().IndexOf(REV_BrakeRelease) >= 0)
                {
                    SendCMD(CMD_robotMode, 2000);
                }
                else if (message.ToLower().IndexOf(REV_RobotMode) >= 0)
                {
                    SafetymodeProcess(message);
                }
                else if (message.ToLower().IndexOf(REV_SafetyMode) >= 0)
                {
                    StatusProcess(message);
                }
                else
                {
                    //急停模式
                }
            }
            catch (Exception ex)
            {
                LogUtil.URSError(LogName + " OnControlRevice出错啦" + ex.ToString());
            }
        }
        private static void SafetymodeProcess(string message)
        {
            string msg = message.ToLower().Replace(REV_RobotMode + ": ", "").ToUpper().Trim();
           
            if (msg.Equals(URStatus.POWER_ON))
            {
                SendCMD(CMD_brakeRelease, 1000);
            }
            else if (msg.Equals(URStatus.RUNNING) || msg.Equals(URStatus.IDLE))
            {
                WarnMsg = "";
                LogUtil.URSInfo(LogName + " 当前状态:" + msg + ",机器人连接成功!");
                LogUtil.info(LogName + " 当前状态:" + msg + ",机器人连接成功!");
                IsRun = true;
                reconnectTimer.Enabled = true;
            }
            else
            {
                if (!IsTimeOut(message))
                {
                    LogUtil.URSInfo(LogName + "当前状态:" + msg + ",发送打开命令" + CMD_powerOn);
                    SendCMD(CMD_powerOn, 1000);
                }
            }
        }
        private static void StatusProcess(string message)
        {
            string msg = message.ToLower().Replace(REV_SafetyMode + ": ", "").ToUpper().Trim();
            if (msg.Equals(URStatus.SFETY_POWER_OFF) || msg.Equals(URStatus.ROBOT_EMERGENCY_STOP))
            {
                if (!IsTimeOut(message))
                {
                    WarnMsg = "机器人急停中[" + msg + "],请先打开急停";
                    SendCMD(CMD_Safetymode, 1000);
                }
                else
                {
                    WarnMsg = "机器人急停中[" + msg + "],启动超时";
                    IsRun = false;
                }
            }
            else
            {
                SendCMD(CMD_Safetymode, 500);
            }
        }
        private static bool IsTimeOut(string status)
        {
            TimeSpan span = DateTime.Now - PreStartTime;
            if (span.TotalMilliseconds > StartTimeOutSeconds)
            {
                string logMsg = LogName + "【" + status + "】 已持续" + Math.Round(span.TotalMilliseconds) + ",启动超时!";
                LogUtil.info(logMsg);
                LogUtil.URSInfo(logMsg);
                return true ;
            }
            return false ;
        }
     

        private static void stopTcp()
        {
            try
            {
                IsRun = false;
                startCount--;
                controlTcp.sendLine(CMD_powerOff);
                controlTcp.close();
            }
            catch (Exception ex)
            {
                LogUtil.error(LogName + "stopTcp出错啦" + ex.ToString());
            }
        }
        /// <summary>
        /// 停止机器人,断开连接
        /// </summary>
        public static void StopRobot()
        {
            try
            {
                IsStartConnect = false;
                reconnectTimer.Enabled = false;
                stopTcp();
            }
            catch (Exception ex)
            {
                LogUtil.error(LogName + "StopEpson出错啦" + ex.ToString());
            }
        }
        /// <summary>
        /// 释放所有轴,切换为手移方式
        /// </summary>
        public static void FreeAxis()
        {
        }

        /// <summary>
        /// 锁定轴,改为程序模式
        /// </summary>
        public static void LockAxis()
        {
        }
        /// <summary>
        /// 移动到指定的坐标
        /// </summary>
        /// <param name="point"></param>
        public static bool MoveTo(URPointValue point)
        {
            //movej([0, 1.57, -1.57, 3.14, -1.57, 1.57],a = 1.4, v = 1.05, t = 0, r = 0)
            string moveCmd = "movej([" + point.X + spiltStr + point.X + spiltStr + point.X + spiltStr + point.X + spiltStr + point.X + spiltStr + point.X + "],a=1.4, v=1.05, t=0, r=0)";
            URRobotClient.LastMoveCMD = moveCmd;
            return true;
        }
        /// <summary>
        /// 获取机器人最后一次获取的坐标
        /// </summary>
        /// <returns></returns>
        public static URPointValue GetLastPosition()
        {
            return LastPoint;
        }
    }
    public class URPointValue
    {
        public URPointValue()
        {
            this.X = 0;
            this.Y = 0;
            this.Z = 0;
            this.RX = 0;
            this.RY = 0;
            this.RZ = 0;
            this.UpdateTime = DateTime.Now;
        }
        public URPointValue(double x, double y, double z, double rx, double ry, double rz)
        {
            // TODO: Complete member initialization
            this.X = Math.Round(x, 2);
            this.Y = Math.Round(y, 2);
            this.Z = Math.Round(z, 2);
            this.RX = Math.Round(rx, 4);
            this.RY = Math.Round(ry, 4);
            this.RZ = Math.Round(rz, 4);
            this.UpdateTime = DateTime.Now;
        }
        /// <summary>
        /// 更新的时间
        /// </summary>
        public DateTime UpdateTime { get; set; }
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }
        public double RX { get; set; }
        public double RY { get; set; }
        public double RZ { get; set; }

        public string ToShowStr()
        {
            return "[X: " + X + ",Y: " + Y + ",Z: " + Z + ",RX: " + RX + ",RY:" + RY + ",RZ:" + RZ + "]";
        }

        public string ToJosonStr()
        {
            string jsonStr = JsonHelper.SerializeObject(this);
            return jsonStr;
        }

        public static URPointValue ToObject(string json)
        {
            return JsonHelper.DeserializeJsonToObject<URPointValue>(json);
        }
    }
    public struct URStatus
    {
        public static string NO_CONTROLLER = "NO_CONTROLLER";
        public static string DISCONNECTED = "DISCONNECTED";
        public static string CONFIRM_SAFETY = "CONFIRM_SAFETY";
        public static string BOOTING = "BOOTING";
        public static string POWER_OFF = "POWER_OFF";
        public static string POWER_ON = "POWER_ON";
        public static string IDLE = "IDLE";
        public static string BACKDRIVE = "BACKDRIVE";
        public static string RUNNING = "RUNNING";
        /// <summary>
        /// ROBOT_EMERGENCY_STOP 急停
        /// </summary>
        public static string ROBOT_EMERGENCY_STOP = "ROBOT_EMERGENCY_STOP";
        /// <summary>
        /// FAULT 急停
        /// </summary>
        public static string FAULT = "FAULT";
        /// <summary>
        /// POWER_OFF 外部急停
        /// </summary>
        public static string SFETY_POWER_OFF = "POWER_OFF";
    }
}