VServerComm.cs 24.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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
using Newtonsoft.Json;
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using RtTower.WebService.ComTowerApp.Contract;
using RtTower.WebService.SharedService;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace DeviceLibrary
{
    public class VServerComm
    {
        volatile StoreStatus _storeStatus = StoreStatus.Debugging;
        /// <summary>
        /// 出库,reelid
        /// </summary>
        public event EventHandler<JobInfo> OutStoreEvent;
        public StoreStatus storeStatus {
            get => _storeStatus;
            set {
                if (_storeStatus!= value)
                    VLog.Info($"set storeStatus to {value}");
                _storeStatus = value;
            }
        }
        static string server = Setting_Init.Device_Server_Address;
        string CID;//= Setting_Init.Device_CID;
        int StoreID = 1;
        string StoreName="";
        
        string WarnMsg = "";
        System.Timers.Timer serverConnectTimer = new System.Timers.Timer();
        VLog VLog;

        object serverclock = new object();

        public VServerComm(string cid , VLog vLog) {
            VLog = vLog;
            CID = cid;
            serverConnectTimer.Interval = 1000;
            serverConnectTimer.AutoReset = true;
            serverConnectTimer.Enabled = true;
            serverConnectTimer.Elapsed += ServerConnectTimer_Elapsed;
            GC.KeepAlive(serverConnectTimer);
            VLog.Info($"server:{server},cid:{CID}");



            BasicHttpBinding binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = 1073741824;
            binding.MaxBufferSize = 1073741824;
            binding.MaxBufferPoolSize = 5242880;
            binding.AllowCookies = false;
            Uri baseAddress = new Uri(Setting_Init.Device_StoreServerURL);
            EndpointAddress endpointAddress = new EndpointAddress(baseAddress.ToString());
            towerAppWSClient = new MydataWcfServiceTest.ServiceReference2.TowerAppWSClient(binding, endpointAddress);

        }
        private void ServerConnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (RobotManage.isRunning && storeStatus >0)
                {
                    //ProcessMsg(VMsg.msg);
                    SendLineStatus();
                }
            }
            catch (Exception ex)
            {
                VLog.Error($"ServerConnectTimer_Elapsed:{ex}");
            }
            finally {
                //Monitor.Exit(serverConnectTimer);
            }
        }

        public void ProcessMsg(List<Msg> msg)
        {
            if (msg == null)
                return;
            WarnMsg = string.Join("\r\n", msg.Select(x =>
            {
                if (x.msgLevel == MsgLevel.warning || x.msgLevel == MsgLevel.alarm)
                {
                    return GetMsgPrefix(x.msgLevel) + x.msgtxt;
                }
                return null;
            }
            ).Where(x => !string.IsNullOrEmpty(x)));
        }

        string GetMsgPrefix(MsgLevel msgLevel)
        {
            switch (msgLevel)
            {
                case MsgLevel.info:
                    return "I=";
                case MsgLevel.warning:
                    return "W=";
                case MsgLevel.alarm:
                    return "A=";
            }
            return "";

        }


        public bool SendStoreState(string posid, string barcode, StoreStatus storeStatus)
        {
            lock (serverclock)
            {
                Operation operation = getLineBoxStatus();
                if (!string.IsNullOrEmpty(posid))
                    operation.boxStatus[StoreID].data.Add(ParamDefine.posId, posid);
                if (!string.IsNullOrEmpty(barcode))
                {
                    operation.boxStatus[StoreID].data.Add(ParamDefine.barcode, barcode);
                    operation.data = new Dictionary<string, string>();
                    operation.data.Add(ParamDefine.barcode, barcode);
                }
                operation.boxStatus[StoreID].status = (int)storeStatus;
                operation.status = (int)storeStatus;
                LogUtil.info(JsonHelper.SerializeObject(operation));
                if (RobotManage.InoutDebugMode)
                    return true;
                Operation resultOperation = HttpHelper.Post(GetPostApi(), operation, 5000,out string log);

                if (resultOperation == null)
                {
                    VLog.Error($"SendStoreState error,posid:{barcode}, storeStatus:{storeStatus}");
                    return false;
                }
                if (operation.seq != resultOperation.seq)
                {
                    VLog.Error($"SendStoreState seq error,posid:{barcode}, storeStatus:{storeStatus}");
                    return false;
                }
                VLog.Info(log);
                VLog.Info($"SendStoreState success,posid:{barcode}, storeStatus:{storeStatus}");
                ResultProcess(resultOperation);
            }
            return true;
        }
                
        /// <summary>
        /// 获取整个料仓的状态
        /// </summary>
        Operation getLineBoxStatus()
        {
            //构建发送给服务器的对象
            Operation lineOperation = new Operation();
            lineOperation.msg = "";
            lineOperation.alarmList = new List<AlarmInfo>();
            lineOperation.cid = CID;
            lineOperation.seq = ConfigAppSettings.nextSeq();
            lineOperation.status = 1;


            //lineOperation.data = GetBtnStatus();
            lineOperation.status = (int)storeStatus;

            //判断如果是等待料盘拿走超时,状态改为4Warning
            //if (alarmType.Equals(StoreAlarmType.IoSingleTimeOut) && StoreMove.MoveType.Equals(StoreMoveType.OutStore))
            //{
            //    if (StoreMove.MoveStep.Equals(StoreMoveStep.SO_15_WaitTake) || StoreMove.MoveStep.Equals(StoreMoveStep.SO_16_CheckIsTake))
            //    {
            //        lineOperation.status = (int)StoreStatus.Warning;
            //    }
            //}

            BoxStatus boxStatus = new BoxStatus();
            boxStatus.boxId = StoreID;
            boxStatus.humidity = Humidity.ToString();
            boxStatus.temperature = Temperature.ToString();
            //状态
            boxStatus.status = (int)storeStatus;
            boxStatus.data.Add("capacity", capacity);

            string sendmsg = "";

            if (commandResultMsg.Count() > 0)
            {
                if (commandResultMsg.TryDequeue(out string msg))
                {
                    sendmsg = msg.Trim().Trim(',');
                }
            }
            else if (!string.IsNullOrEmpty(WarnMsg))
            {
                sendmsg = string.Join(",", new string[] { WarnMsg });
            }
            else if (!RobotManage.isRunning){
                sendmsg = crc.GetString("Res0155","设备未启动");
            }

            lineOperation.msg = sendmsg;
            lineOperation.msg = lineOperation.msg.Trim().Trim(',');
            boxStatus.msg = lineOperation.msg;
            lineOperation.msgEn = lineOperation.msg;
            lineOperation.msgJp = lineOperation.msg;


            lineOperation.boxStatus.Add(StoreID, boxStatus);
            return lineOperation;
        }
        private static string api_communication = "service/store/communication";    //流水线状态通信接口
        public static string GetPostApi()
        {
            var host = server;
            if (!host.StartsWith("http://"))
            {
                host = "http://" + host;
            }
            if (!host.EndsWith("/"))
            {
                host = host + "/";
            }
            return host + api_communication;
        }
        int getthtime = 0;
        int laststatus = 0;
        public void SendLineStatus()
        {
            if (RobotManage.InoutDebugMode)
                return;

            lock (serverclock)
            {
                bool printlog = false;
                DateTime time = DateTime.Now;
                //构建发送给服务器的对象
                Operation lineOperation = getLineBoxStatus();
                //如果还没湿度范围,先获取
                if (getthtime < 3)
                {
                    if (Max_Humidity <= 0 || (Max_Temperature <= 0))
                    {
                        lineOperation.op = 5;
                        VLog.Info(StoreName + "没有湿度预警范围,需要从服务器获取,发送OP=" + lineOperation.op);
                        getthtime++;
                    }
                }

                if (lineOperation.status != laststatus) {

                    laststatus = lineOperation.status;
                    printlog = true;
                }

                Operation resultOperation = HttpHelper.Post(GetPostApi(), lineOperation,700, out string log);
                if (resultOperation != null)
                    getthtime = 0;
                //LogUtil.info(JsonHelper.SerializeObject(resultOperation.data));
                ResultProcess(resultOperation);
                TimeSpan span = DateTime.Now - time;
                if (span.TotalMilliseconds > 700)
                {
                    VLog.Info(StoreName + "TimerProcess[" + span.TotalMilliseconds + "]");
                }
            }
        }
        public int queueTaskCount=-1;
        ConcurrentQueue<string> commandResultMsg = new ConcurrentQueue<string>();
        void ResultProcess(Operation resultOperation)
        {
            //发送状态信息到服务器 
            if (resultOperation == null)
            {
                //判断服务端是否返回出库操作
                return;
            }

            if (resultOperation.op.Equals(1))
            {
                var barcode = "";
                if (resultOperation.data.ContainsKey("code"))
                    barcode = resultOperation.data["code"];
                ReviceInStoreProcess(barcode, resultOperation);
            }
            else if (resultOperation.op.Equals(2))
            {
                ReviceOutStoreProcess(resultOperation);
            }
            else if (resultOperation.op.Equals(5))
            {
                //ProcessHumidityCMD(resultOperation);
            }
            ProcessHumidityCMD(resultOperation);
            if (resultOperation.data != null)
            {
                string result = "";
                Dictionary<string, string> dataMap = resultOperation.data;

                if (dataMap.ContainsKey(ParamDefine.queueTaskCount))
                {
                    var s = dataMap[ParamDefine.queueTaskCount];
                    if (int.TryParse(s, out int c))
                    {
                        queueTaskCount = c;
                    }
                    else
                    {
                        queueTaskCount = -1;
                    }
                }
            }
        }

        /// <summary>
        /// 处理服务器入库库位消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="resultOperation"></param>
        private void ReviceInStoreProcess(string message, Operation resultOperation)
        {
            Dictionary<string, string> data = resultOperation.data;
            if (data != null && data.ContainsKey(ParamDefine.posId) && data.ContainsKey(ParamDefine.plateH) && data.ContainsKey(ParamDefine.plateW))
            {
                //服务器返回时有:posId库位编号,plateW:料盘宽度,plateH:料盘高度,
                //postId格式BoxId#位置
                string posId = data[ParamDefine.posId];
                int.TryParse(data[ParamDefine.plateW], out int plateW);
                int.TryParse(data[ParamDefine.plateH], out int plateH);

                //根据发送的posId获取位置列表
                ACStorePosition position = CSVPositionReader<ACStorePosition>.GetPositon(posId);
                if (position == null)
                {
                    //出入库没有找到服务器发送的库位,需要打印日志方便查询原因
                    //SetWarnMsg(ResourceControl.InStoreNoPosition, message, posId);
                    WarnMsg = crc.GetString("Res0049","入库未找到库位:") + posId;//0505
                    VLog.Info("收到服务器入库命令:入库未找到库位:二维码【" + message + "】库位【" + posId + "】");
                    return;
                }
                //TODO:判断BOX是否处于可以入库状态,如果调试或急停中,需要返回给服务器;
                //if (RobotManage.mainMachine.IsInStoreReady)
                //{
                //    WarnMsg = "";
                //    if (plateH > 56)
                //        plateH = 56;
                //    JobInfo inStoreJob = new JobInfo(message, posId, plateW, plateH);
                //    RobotManage.mainMachine.StartInStore(inStoreJob);
                //    //如果当前正在出入库中,需要记录下来,等待空闲时执行
                //    VLog.Info(StoreName + " 收到服务器入库命令:库位号【" + posId + "】二维码【" + message + "】 开始入库!");
                //}
                //else
                {
                    SendStoreState("","", StoreStatus.InStoreError);
                }
            }

        }

        public double Max_Humidity;
        public double Max_Temperature;
        public double Humidity;
        public double Temperature;
        /// <summary>
        /// 处理服务器温湿度消息
        /// </summary>
        /// <param name="resultOperation"></param>
        private void ProcessHumidityCMD(Operation resultOperation)
        {
            if (resultOperation.data == null)
                return;
            Dictionary<string, string> data = resultOperation.data;
            if (data.ContainsKey(ParamDefine.maxHumidity) && data.ContainsKey(ParamDefine.maxTemperature))
            {
                string maxHumidity = data[ParamDefine.maxHumidity];
                string maxTemp = data[ParamDefine.maxTemperature];
                VLog.Info( "收到服务器温湿度预警值:maxHumidity=" + maxHumidity + ",maxTemperature=" + maxTemp);

                try
                {
                    this.Max_Humidity = (float)Convert.ToDouble(maxHumidity);
                    this.Max_Temperature = (float)Convert.ToDouble(maxTemp);
                    VLog.Info( "保存温湿度预警值:Max_Humidity=" + Max_Humidity + ",Max_Temperature=" + Max_Temperature);
                }
                catch (Exception ex)
                {
                    VLog.Error("转换温湿度失败:" + ex.ToString());
                }
            }
        }
        /// <summary>
        /// 处理服务器出库任务消息
        /// </summary>
        /// <param name="resultOperation"></param>
        private void ReviceOutStoreProcess(Operation resultOperation)
        {
            DateTime time = DateTime.Now;
            Dictionary<string, string> data = resultOperation.data;
            if (data != null && data.ContainsKey(ParamDefine.posId)
                   && data.ContainsKey(ParamDefine.plateH) && data.ContainsKey(ParamDefine.plateW))
            {
                string posIdStr = data[ParamDefine.posId];
                //string cid = data[ParamDefine.cid];
                string plateWStr = data[ParamDefine.plateW];
                string plateHStr = data[ParamDefine.plateH];
                string singleOut = data[ParamDefine.singleOut];
                string code = "";
                if (!data.TryGetValue("code", out code))
                    data.TryGetValue(ParamDefine.barcode, out code);
                VLog.Info("收到服务器出库消息:poaIs=" + posIdStr + ",platew=" + plateWStr + ",plateh=" + plateHStr + ",code=" + code);

                int.TryParse(plateWStr, out int plateW);
                int.TryParse(plateHStr, out int plateH);

                //根据发送的posId获取位置列表
                
                if (string.IsNullOrEmpty(code))
                {
                    //WarnMsg = StoreName + "没有:【" + cid + "】";
                    VLog.Error("收到服务器出库命令:没有code");
                }
                else
                {
                    JobInfo jobInfo = new JobInfo(code, posIdStr, plateW, plateH);
                    OutStoreEvent?.Invoke(crc.GetString("Res0064","服务器"), jobInfo);
                }

                TimeSpan span = DateTime.Now - time;
                if (span.TotalMilliseconds > 100)
                {
                    VLog.Info(StoreName + "执行 ReviceOutStoreProcess 共处理了【" + span.TotalMilliseconds + "】毫秒");
                }
            }
        }

        private static string Addr_cancelPutInTask = "/service/store/cancelPutInTask";
        public string cancelPutInTask(string barcode)
        {
            string msg = "";
            try
            {
                if (barcode.Count(c => c == '#') == 3)
                {
                    barcode = barcode.Split('#')[1].Substring(1);
                }

                Dictionary<string, string> paramMap = new Dictionary<string, string>();
                paramMap.Add("barcode", barcode);

                string server = GetAddr(Addr_cancelPutInTask, paramMap);
                DateTime startTime = DateTime.Now;
                string resultStr = HttpHelper.Post(server, "");
                VLog.Info("cancelPutInTask    " + FormUtil.GetSpanStr(DateTime.Now - startTime) + "  【" + server + "】【" + resultStr + "】");

                ResultData data = JsonHelper.DeserializeJsonToObject<ResultData>(resultStr);

                if (data == null)
                {
                    return msg = " cancelPutInTask【 " + barcode + "】 没有收到服务器反馈";
                }
                else if (data.code.Equals(0).Equals(false))
                {
                    return msg = " cancelPutInTask【 " + barcode + "】   :" + data.msg;
                }

                return "";
            }
            catch (Exception ex)
            {
                VLog.Error(" " + ex.ToString());
            }
            return msg;
        }

        public string DisabledPos(string posId, string barcode)
        {
            string msg = "";
            try
            {
                Dictionary<string, string> paramMap = new Dictionary<string, string>();
                paramMap.Add("posId", posId);
                paramMap.Add("barcode", barcode);

                string server = GetAddr("/service/store/disabledPos", paramMap);
                DateTime startTime = DateTime.Now;
                string resultStr = HttpHelper.Post(server, "");
                VLog.Info("DisabledPos    " + FormUtil.GetSpanStr(DateTime.Now - startTime) + "  【" + server + "】【" + resultStr + "】");

                ResultData data = JsonHelper.DeserializeJsonToObject<ResultData>(resultStr);

                if (data == null)
                {
                    return msg = " DisabledPos【 " + posId + "】 没有收到服务器反馈";
                }
                else if (data.code.Equals(0).Equals(false))
                {
                    return msg = " DisabledPos【 " + posId + "】   :" + data.msg;
                }

                return "";
            }
            catch (Exception ex)
            {
                VLog.Error("DisabledPos: " + ex.ToString());
            }
            return msg;
        }
        private static string GetAddr(string addr, Dictionary<string, string> paramsMap)
        {
            if (server.EndsWith("/"))
            {
                server = server.Substring(0, server.Length - 1);
            }
            string path = server + addr.Trim() + "?";
            foreach (string paramName in paramsMap.Keys)
            {
                string par = System.Web.HttpUtility.UrlEncode(paramsMap[paramName], System.Text.Encoding.UTF8);
                path += paramName + "=" + par + "&";
            }
            path = path.Substring(0, path.Length - 1);
            return path;
        }






        public bool BeginOutStore(JobInfo jobInfo, VLog vLog)
        {
            if (!SendCommand(VCmd.GetCarrierInformation, true, out string data, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            var reelinfo = XmlCommandSerializer.DeserializeCarrierInformation(result.Data);
            lock (VStoreCollection.OutStoreReelInfo)
            {
                VStoreCollection.OutStoreReelInfo[jobInfo.WareNum] = new JobInfo(jobInfo.WareNum, "", reelinfo.Diameter, reelinfo.Height);
                Setting_Init.Runtime_OutStoreReelInfo = JsonConvert.SerializeObject(VStoreCollection.OutStoreReelInfo);
            }
            vLog.Info("出库时获取到料盘数据:" + VStoreCollection.OutStoreReelInfo[jobInfo.WareNum].ToStr());
            if (!SendCommand(VCmd.UnloadCarrier, true, out data, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
            result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            return true;
        }
        public bool BeginInStore(string towerid, JobInfo jobInfo, VLog vLog)
        {
            if (!SendCommand(VCmd.SimulateStartButton, true, out string data, towerid, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            return true;
        }
        MydataWcfServiceTest.ServiceReference2.TowerAppWSClient towerAppWSClient;
        internal string capacity;

        public bool SendCommand(string command, bool needlog, out string msg, params string[] arg)
        {
            string errmsg;
            try
            {
                XmlDocument xd = new XmlDocument();
                command = string.Format(command, arg);
                xd.LoadXml(command);
            }
            catch (Exception ex)
            {
                errmsg = "Command format error:\r\n" + ex.ToString();
                msg = errmsg;
                return false;
            }

            try
            {
                if (needlog)
                    VLog.Info("send: " + command);
                //string command = textBox_sendcommand.Text;
                try
                {
                    var re = towerAppWSClient.XmlAction(command);
                    msg = re.ToString();
                    return true;
                    //errmsg = "Request sent successfully.";

                }
                catch (Exception ex)
                {
                    errmsg = "Failed to send request." + ex;
                    msg = errmsg;
                    return false;
                }
            }
            catch (Exception ex)
            {
                errmsg = "Error: " + ex.ToString();
                msg = errmsg;
            }
            return false;
        }
        /*
10001 UnknownTower
10002 no Towers to list
10003 no ProductionSite to list
10010 no Articles to list
10011 Article not found
10012 Article aready exists
10013 Article not deleted
10020 no Carriers to list
10021 Carrier not found
10022 Carrier alredy exists
10023 Carrier already in Tower
10041 JobList not found
10042 JobList creation Error
10043 Joblist creation Warning
         */
        public TowerDetailInformation GetTowerDetailInformation(string CID)
        {
            if (!SendCommand(VCmd.GetTowerInformation, false, out string data, CID))
            {
                VLog.Error(data);
                return null;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                VLog.Error(data);
                return null;
            }
            return XmlCommandSerializer.DeserializeTowerDetailInformation(result.Data);
        }
    }    
}