Vehicle.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using FluentResults;
  8. using GSG.NET.Concurrent;
  9. using GSG.NET.LINQ;
  10. using GSG.NET.Logging;
  11. using GSG.NET.Quartz;
  12. using GSG.NET.Utils;
  13. using OHV.Common.Events;
  14. using OHV.Common.Model;
  15. using OHV.Common.Shareds;
  16. using OHV.SqliteDAL;
  17. using Prism.Events;
  18. using VehicleControlSystem.ControlLayer.Actuator.Cylinder;
  19. using VehicleControlSystem.ControlLayer.IO;
  20. using VehicleControlSystem.ControlLayer.Motion;
  21. using VehicleControlSystem.Managers;
  22. namespace VehicleControlSystem.ControlLayer
  23. {
  24. /// <summary>
  25. /// Control Layer 의 자원을 여기서 사용하자.
  26. /// </summary>
  27. public class Vehicle : ControlObjectBase, IDisposable
  28. {
  29. /// <summary>
  30. /// OCS Report Code
  31. /// 목적지에 도착해서 Load, Unload 시 발생하는 Alarm
  32. /// </summary>
  33. public enum eFailCode
  34. {
  35. Load_PortHasNotCarrier = 1,
  36. Load_VehicleHasCarrier,
  37. Unload_PortHasCarrier,
  38. Unload_VehicleHasNotCarrier,
  39. LoadPIOInterlockTimeout,
  40. UnlaodPIOInterlockTimeout,
  41. }
  42. static Logger logger = Logger.GetLogger();
  43. static Logger loggerPIO = Logger.GetLogger( "PIO" );
  44. #region Properties
  45. private double currentPosition;
  46. /// <summary>
  47. /// Tag 위치
  48. /// </summary>
  49. public double CurrentPosition
  50. {
  51. get { return currentPosition; }
  52. set
  53. {
  54. if ( this.currentPosition == value ) return;
  55. this.currentPosition = value;
  56. this.OnCurrentPotisionChanged?.Invoke( (int)value );
  57. }
  58. }
  59. //이동
  60. public bool Busy
  61. {
  62. get
  63. {
  64. return this.CurrentSubCommand == null ? false : true;
  65. }
  66. private set { }
  67. }
  68. public bool IsMoving { get; set; }
  69. public double BatteryVolt { get; set; }
  70. public bool IsError { get; set; }
  71. public bool IsContain { get { return this.IsDetectedCenter(); } }
  72. public SubCmd CurrentSubCommand { get; private set; }
  73. #endregion
  74. #region Event
  75. public event Action OnMoveReady;
  76. public event Action OnMoving;
  77. public event Action OnMoveFinish;
  78. public event Action OnChargingStart;
  79. public event Action OnCharging;
  80. public event Action OnChargingFull;
  81. public event Action<double> OnBatteryVelueChanged;
  82. public event Action<bool> OnPIOStart;
  83. public event Action<bool> OnConveyorStart;
  84. public event Action<bool> OnConveyorStop;
  85. public event Action<bool> OnCarrierDetected;
  86. public event Action OnLoadComplete;
  87. public event Action OnUnloadComplete;
  88. public event Action<int> OnCurrentPotisionChanged;
  89. public event Action OnManualMove;
  90. public event Action OnManualLoad;
  91. public event Action OnManualUnload;
  92. public event Action OnManualCharging;
  93. public event Action<eFailCode> OnFailReport;
  94. #endregion
  95. IIO iO = null;
  96. GSIMotion motion = null;
  97. SqliteManager sql = null;
  98. Clamp clamp = null;
  99. Steering steering = null;
  100. AutoManager autoManager = null;
  101. #region List.
  102. List<ICylinder> cylinders = new List<ICylinder>();
  103. List<string> obstacleBitList = new List<string>();
  104. #endregion
  105. ThreadCancel cancel = new ThreadCancel();
  106. TaskCancel taskCancel = new TaskCancel();
  107. private eObstacleState obstacleState = eObstacleState.Normal;
  108. public eObstacleState ObstacleStateProperty
  109. {
  110. get { return obstacleState; }
  111. set { SetField( ref this.obstacleState, value ); }
  112. }
  113. private eVehicleState vehicleState;
  114. public eVehicleState VehicleStateProperty
  115. {
  116. get { return vehicleState; }
  117. set { SetField( ref this.vehicleState, value ); }
  118. }
  119. IEventAggregator eventAggregator;
  120. public Vehicle( IIO io, SqliteManager sqliteManager, IEventAggregator ea, AutoManager auto )
  121. {
  122. this.iO = io;
  123. this.motion = new GSIMotion();
  124. this.sql = sqliteManager;
  125. this.autoManager = auto;
  126. this.obstacleBitList.AddRange( new string[]
  127. {
  128. "OUT_OBSTRUCTION_PATTERN_00",
  129. "OUT_OBSTRUCTION_PATTERN_01",
  130. "OUT_OBSTRUCTION_PATTERN_02",
  131. "OUT_OBSTRUCTION_PATTERN_03",
  132. "OUT_OBSTRUCTION_PATTERN_04",
  133. } );
  134. this.eventAggregator = ea;
  135. this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Unsubscribe( ReceiveDriveControlEvent );
  136. this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Subscribe( ReceiveDriveControlEvent );
  137. }
  138. private void ReceiveDriveControlEvent( DriveControlEventArgs _args )
  139. {
  140. if ( this.autoManager.OperationModeProperty != eOperatationMode.ManualMode )
  141. return;
  142. var msg = _args;
  143. if ( msg.EventDir == DriveControlEventArgs.eEventDir.ToBack )
  144. {
  145. switch ( msg.ControlKind )
  146. {
  147. case DriveControlEventArgs.eControlKind.MOVE:
  148. break;
  149. case DriveControlEventArgs.eControlKind.STOP:
  150. break;
  151. case DriveControlEventArgs.eControlKind.Steering:
  152. if ( msg.MoveDir == DriveControlEventArgs.eMoveDir.LEFT )
  153. this.steering.ControlSteering( true );
  154. else
  155. this.steering.ControlSteering();
  156. break;
  157. case DriveControlEventArgs.eControlKind.SteeringState:
  158. {
  159. DriveControlEventArgs reply = new DriveControlEventArgs();
  160. reply.ControlKind = DriveControlEventArgs.eControlKind.SteeringState;
  161. if ( this.steering.IsLeft() )
  162. reply.Result = FluentResults.Results.Ok<DriveControlEventArgs.eMoveDir>( DriveControlEventArgs.eMoveDir.LEFT );
  163. else
  164. reply.Result = FluentResults.Results.Ok<DriveControlEventArgs.eMoveDir>( DriveControlEventArgs.eMoveDir.RIGHT );
  165. this.DriveControlEventPublish( reply );
  166. }
  167. break;
  168. case DriveControlEventArgs.eControlKind.ReqCurrentPos:
  169. this.ReqCurrentPos();
  170. break;
  171. case DriveControlEventArgs.eControlKind.ReqStopCurrentPos:
  172. this.taskCancel.Cancel();
  173. this.taskCancel.WaitAll();
  174. break;
  175. case DriveControlEventArgs.eControlKind.FaultReset:
  176. this.ReqFaultReset( _args );
  177. break;
  178. case DriveControlEventArgs.eControlKind.DriveON:
  179. this.ReqDriveOn( _args );
  180. break;
  181. case DriveControlEventArgs.eControlKind.DriveOFF:
  182. this.ReqDriveOff( _args );
  183. break;
  184. case DriveControlEventArgs.eControlKind.JOG:
  185. this.ReqJog( _args );
  186. break;
  187. default:
  188. break;
  189. }
  190. }
  191. }
  192. private void DriveControlEventPublish( DriveControlEventArgs args )
  193. {
  194. args.EventDir = DriveControlEventArgs.eEventDir.ToFront;
  195. this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Publish( args );
  196. }
  197. public void Init()
  198. {
  199. this.CreateClamp();
  200. this.CreateSteering();
  201. ThreadStart();
  202. }
  203. public int InitializationVehicle()
  204. {
  205. int result = 0;
  206. if ( this.IsDetectedCenter() ) //자제가 있으면 Lock
  207. result = this.clamp.Lock_Sync();
  208. else
  209. result = this.clamp.Unlock_Sync();
  210. if ( this.motion.IsErrorOn )
  211. return 22;
  212. return result;
  213. }
  214. public void Dispose()
  215. {
  216. this.cancel.Cancel();
  217. this.cancel.StopWaitAll();
  218. }
  219. #region Request Method
  220. void ReqFaultReset(DriveControlEventArgs _args)
  221. {
  222. //TODO:[20/03/18 ys-hwang] Drive Assign
  223. var drive = 0;
  224. //var result = drive.ResetAmpFault();
  225. var msg = new DriveControlEventArgs
  226. {
  227. };
  228. msg.Result = Results.Ok( "Drive On" );
  229. this.DriveControlEventPublish( msg );
  230. }
  231. void ReqJog(DriveControlEventArgs _args)
  232. {
  233. //TODO:[20/03/18 ys-hwang] Drive Jog Request
  234. var drive = string.Empty;
  235. if ( _args.JogDir == DriveControlEventArgs.eJogMoveDir.Positive )
  236. drive = "POSITIVE";
  237. else
  238. drive = "NEGATIVE";
  239. }
  240. void ReqCurrentPos()
  241. {
  242. //TODO:[20/03/18 ys-hwang] Drive Current Position Publish
  243. var task = Task.Factory.StartNew( ( ) =>
  244. {
  245. while(!this.taskCancel.Canceled)
  246. {
  247. LockUtils.Wait( 500 );
  248. var msg = new DriveControlEventArgs
  249. {
  250. EventDir = DriveControlEventArgs.eEventDir.ToFront ,
  251. ControlKind = DriveControlEventArgs.eControlKind.ReqCurrentPos ,
  252. //CurrentPosition = drive.CurrentPosition,
  253. };
  254. //this.DriveControlEventPublish( msg );
  255. }
  256. } );
  257. this.taskCancel.Add( task );
  258. }
  259. void ReqDriveOn( DriveControlEventArgs _args)
  260. {
  261. //TODO:[20/03/18 ys-hwang] Drive On
  262. var drive = "Drive Name";
  263. //drive.On();
  264. var msg = new DriveControlEventArgs
  265. {
  266. };
  267. msg.Result = Results.Ok( "Drive On" );
  268. this.DriveControlEventPublish( msg );
  269. }
  270. void ReqDriveOff( DriveControlEventArgs _args)
  271. {
  272. var drive = "Drive Name";
  273. //drive.Off();
  274. var msg = new DriveControlEventArgs
  275. {
  276. };
  277. msg.Result = Results.Ok( "Drive On" );
  278. this.DriveControlEventPublish( msg );
  279. }
  280. #endregion
  281. #region Thread
  282. void ThreadStart()
  283. {
  284. this.cancel.AddGo( new Action( this._ThSubCmdWorker ) );
  285. this.cancel.AddGo( new Action( this._ThObstacleChecker ) );
  286. }
  287. //장애물 감지 Thread
  288. //장애물 감지 패턴 변경도 여기 하자.
  289. private void _ThObstacleChecker()
  290. {
  291. while ( !this.cancel.Canceled )
  292. {
  293. try
  294. {
  295. if ( this.autoManager.OperationModeProperty == eOperatationMode.AutoMode )
  296. this.CheckObstacle();
  297. }
  298. catch ( ThreadInterruptedException threadInterruptedException )
  299. {
  300. }
  301. catch ( Exception exception )
  302. {
  303. logger.E( exception );
  304. }
  305. finally
  306. {
  307. LockUtils.Wait( 5 );
  308. }
  309. }
  310. logger.D( "Vehicle - _ThObstacleChecker Dispose" );
  311. }
  312. /// <summary>
  313. /// Scheduler 가 주는 Sub Command 를 이용하여 동작하자.
  314. /// </summary>
  315. public void _ThSubCmdWorker()
  316. {
  317. while ( !this.cancel.Canceled )
  318. {
  319. try
  320. {
  321. if ( this.ObstacleStateProperty != eObstacleState.Normal ) //장애물 감지 상태 시 조그 동작만 가능하게.
  322. continue;
  323. if ( this.autoManager.AutoModeStateProperty != eAutoModeState.Run ) //
  324. continue;
  325. var subCmd = sql.SubCmdDAL.GetSubCmd();
  326. if ( subCmd == null ) continue;
  327. if ( !sql.CommandDAL.All.Any( x => x.CommandID.Equals( subCmd.CmdID ) ) )
  328. {
  329. if ( subCmd.CmdType == SubCmd.eCmdType.Auto ) //자동 명령중 Main Command 가 없으면 삭제.
  330. {
  331. sql.SubCmdDAL.Delete( subCmd );
  332. logger.I( $"SubCmd Deleted - ID={subCmd.ID}, CommandID={subCmd.CmdID}" );
  333. }
  334. }
  335. switch ( subCmd.Type )
  336. {
  337. case SubCmd.eType.Move:
  338. this.CurrentSubCommand = subCmd;
  339. this.Move( subCmd );
  340. break;
  341. case SubCmd.eType.Load:
  342. this.CurrentSubCommand = subCmd;
  343. this.LoadCarrier( subCmd );
  344. break;
  345. case SubCmd.eType.Unload:
  346. this.CurrentSubCommand = subCmd;
  347. this.UnloadCarrier( subCmd );
  348. break;
  349. case SubCmd.eType.Charge:
  350. this.CurrentSubCommand = subCmd;
  351. this.BatteryCharge( subCmd );
  352. break;
  353. default:
  354. break;
  355. }
  356. }
  357. catch ( ThreadInterruptedException threadInterruptedException )
  358. {
  359. }
  360. catch ( Exception exception )
  361. {
  362. logger.E( exception );
  363. }
  364. finally
  365. {
  366. LockUtils.Wait( 500 );
  367. }
  368. }
  369. logger.D( "Vehicle - _ThSubCmdWorker Dispose" );
  370. }
  371. #endregion
  372. #region Control Action Method
  373. public void EStop()
  374. {
  375. //Clamp EStop
  376. this.clamp.ClampEStop();
  377. this.motion.EStop();
  378. this.autoManager.ProcessAlarm(23);
  379. }
  380. void Move( SubCmd sub )
  381. {
  382. if ( this.MoveTo( sub.TargetID ) )
  383. {
  384. sql.SubCmdDAL.Delete( sub );
  385. }
  386. else
  387. {
  388. if ( this.ObstacleStateProperty == eObstacleState.Blocked )
  389. {
  390. }
  391. }
  392. }
  393. bool MoveTo( string pointID )
  394. {
  395. //this.BuzzerOnOff(true, eBuzzerKind.StartWarn);
  396. ////TimerUtils.Once(3000, BuzzerOnOff, false, eBuzzerKind.StartWarn );
  397. //Thread.Sleep(3000);
  398. //this.BuzzerOnOff(false);
  399. this.OnMoveReady?.Invoke();
  400. var moveReadyBuzzerTime = sql.ConfigDal.GetValueToInt( ConstString.BuzzerStartReadyTime );
  401. Thread.Sleep( moveReadyBuzzerTime );
  402. this.OnMoving?.Invoke();
  403. this.IsMoving = true;
  404. //this.BuzzerOnOff(true, eBuzzerKind.Moving);
  405. this.motion.MoveToPoint( pointID, 100 );
  406. bool result = Wait4MoveDone();
  407. this.IsMoving = false;
  408. //this.BuzzerOnOff(false);
  409. this.OnMoveFinish?.Invoke();
  410. return result;
  411. }
  412. bool Wait4MoveDone()
  413. {
  414. int waitTime = 6000; //설정 할 수있게.
  415. long st = SwUtils.CurrentTimeMillis;
  416. //Todo: 이동시 확인 사항들.
  417. while ( true )
  418. {
  419. Thread.Sleep( 5 );
  420. if ( SwUtils.Gt( st, waitTime ) )
  421. {
  422. //Todo: 이동시간 초과 시 동작들.
  423. break;
  424. }
  425. if ( this.ObstacleStateProperty == eObstacleState.Blocked )
  426. return false;
  427. //Todo: 이동중 명령이 삭제 되면 처리 할일들.
  428. if (!sql.SubCmdDAL.HasK(this.CurrentSubCommand.ID))
  429. {
  430. }
  431. }
  432. return true;
  433. }
  434. public bool LoadCarrier( SubCmd sub )
  435. {
  436. var route = sql.RouteDal.GetRoute( sub.TargetID );
  437. if ( !CorrectPosition( route, this.CurrentPosition ) )
  438. {
  439. this.autoManager.ProcessAlarm( 20 );
  440. return false; //Alarm
  441. }
  442. int result = this.clamp.Unlock_Sync();
  443. if ( result != 0 )
  444. {
  445. this.autoManager.ProcessAlarm( result );
  446. return false;
  447. }
  448. result = this.PIOAndLoad( sub.TargetID );
  449. if ( result != 0 )
  450. {
  451. this.autoManager.ProcessAlarm( result );
  452. return false;
  453. }
  454. result = this.clamp.Lock_Sync();
  455. if ( result != 0 )
  456. {
  457. this.autoManager.ProcessAlarm( result );
  458. return false;
  459. }
  460. //Load, Unload 가 끝나면 메인 Command 를 완료 했다고 판다.
  461. sql.CommandDAL.UpdateState( sub.CmdID, eCommandState.Complete );
  462. sql.SubCmdDAL.Delete( sub );
  463. return true;
  464. }
  465. public bool UnloadCarrier( SubCmd sub )
  466. {
  467. var route = sql.RouteDal.GetRoute( sub.TargetID );
  468. if ( !CorrectPosition( route, this.CurrentPosition ) )
  469. {
  470. this.autoManager.ProcessAlarm( 21 );
  471. return false; //Alarm
  472. }
  473. int result = this.clamp.Unlock_Sync();
  474. if ( result != 0 )
  475. {
  476. this.autoManager.ProcessAlarm( result );
  477. return false;
  478. }
  479. result = this.PIOAndUnload( sub.TargetID );
  480. if ( result != 0 )
  481. {
  482. this.autoManager.ProcessAlarm( result );
  483. return false;
  484. }
  485. sql.CommandDAL.UpdateState( sub.CmdID, eCommandState.Complete );
  486. sql.SubCmdDAL.Delete( sub );
  487. return true;
  488. }
  489. /// <summary>
  490. /// Battery Charge
  491. /// 충전 시 PIO 를 해야 함.
  492. /// </summary>
  493. /// <param name="sub"></param>
  494. /// <returns></returns>
  495. public bool BatteryCharge( SubCmd sub )
  496. {
  497. var route = sql.RouteDal.GetRoute(sub.TargetID);
  498. if (!CorrectPosition(route, this.CurrentPosition))
  499. {
  500. this.autoManager.ProcessAlarm(21);
  501. return false; //Alarm
  502. }
  503. var pioTimeout = sql.ConfigDal.GetValueToInt(ConstString.PIOTimeOut);
  504. PIOClear();
  505. loggerPIO.I($"Start Unload PIO - [{sub.TargetID}]");
  506. this.OnPIOStart?.Invoke(false);
  507. if (!this.iO.IsOn("IN_PIO_READY"))
  508. {
  509. loggerPIO.E("[Port] - 1 Ready not On");
  510. this.OnFailReport?.Invoke(eFailCode.UnlaodPIOInterlockTimeout);
  511. //return 0;
  512. }
  513. this.iO.WriteOutputIO("OUT_PIO_READY", true);
  514. loggerPIO.I("[Vehicle] - 1 Ready On");
  515. if (!this.iO.WaitChangeInputIO(true, pioTimeout, "IN_PIO_RECEIVE_RUN"))
  516. {
  517. PIOClear();
  518. loggerPIO.E("[Port] - 2 Receive CV Run Timeout");
  519. this.OnFailReport?.Invoke(eFailCode.UnlaodPIOInterlockTimeout);
  520. //return 0;
  521. }
  522. this.iO.WriteOutputIO("OUT_PIO_SENDING_RUN", true);
  523. loggerPIO.I("[Vehicle] - 2 Send Run On");
  524. this.SetConveyorSpeed(true);
  525. this.OnOffConveyor(true);
  526. this.OnConveyorStart?.Invoke(false);
  527. var sTime = SwUtils.CurrentTimeMillis;
  528. while (true)
  529. {
  530. if (SwUtils.Gt(sTime, 20 * ConstUtils.ONE_SECOND))
  531. {
  532. PIOClear();
  533. this.OnOffConveyor(false, true);
  534. loggerPIO.E("[Port] Conveyor Wait Time Out");
  535. this.OnFailReport?.Invoke(eFailCode.UnlaodPIOInterlockTimeout);
  536. //if (IsDetectedLoadStart() || IsDetectedCenter()) //중간에 걸려 있다고 생각해서 알람 처리.
  537. // return 12; //Conveyor Moving Timeout
  538. //else
  539. // return 0;
  540. }
  541. if (this.iO.IsOn("IN_PIO_RECEIVE_COMPLITE"))
  542. break;
  543. }
  544. if (!IsDetectedCenter())
  545. this.OnCarrierDetected?.Invoke(false);
  546. this.OnOffConveyor(false); //Stop
  547. this.OnConveyorStop?.Invoke(false);
  548. PIOClear();
  549. this.iO.WriteOutputIO("OUT_PIO_SEND_COMPLITE", true);
  550. this.iO.WriteOutputIO("OUT_PIO_SEND_COMPLITE", false, 1000);
  551. this.OnUnloadComplete?.Invoke();
  552. return true;
  553. }
  554. #endregion
  555. #region Check Method
  556. bool CheckObstacle()
  557. {
  558. if ( this.iO.IsOn( "IN_OBSTRUCTION_DETECT_SAFETY" ) || this.iO.IsOn( "IN_OBSTRUCTION_DETECT_ERROR" ) )
  559. {
  560. this.motion.Stop();
  561. this.ObstacleStateProperty = eObstacleState.Abnormal;
  562. return true;
  563. }
  564. if ( this.iO.IsOn( "IN_OBSTRUCTION_DETECT_STOP" ) )
  565. {
  566. this.motion.Stop();
  567. this.ObstacleStateProperty = eObstacleState.Blocked;
  568. return true;
  569. }
  570. if ( this.iO.IsOn( "IN_OBSTRUCTION_DETECT_SLOW" ) )
  571. {
  572. this.motion.SlowStop();
  573. this.ObstacleStateProperty = eObstacleState.Decelerate;
  574. return true;
  575. }
  576. this.ObstacleStateProperty = eObstacleState.Normal;
  577. return false;
  578. }
  579. #endregion
  580. #region Machanical Method
  581. #region Conveyor
  582. int OnOffConveyor( bool isOn, bool isCW = false )
  583. {
  584. if ( IsInverterError() )
  585. return 16;
  586. if ( isCW )
  587. this.iO.OutputOn( "OUT_CV_CWCCW" );
  588. else
  589. this.iO.OutputOff( "OUT_CV_CWCCW" );
  590. if ( isOn )
  591. this.iO.OutputOn( "OUT_CV_RUN" );
  592. else
  593. this.iO.OutputOff( "OUT_CV_RUN" );
  594. return 0;
  595. }
  596. void SetConveyorSpeed( bool IsHight )
  597. {
  598. if ( IsHight )
  599. this.iO.WriteOutputIO( "OUT_CV_DA", true );
  600. else
  601. this.iO.WriteOutputIO( "OUT_CV_DA", false );
  602. }
  603. /// <summary>
  604. /// 입구 감지 로딩시 감속 사용
  605. /// </summary>
  606. /// <returns></returns>
  607. bool IsDetectedLoadStart() => this.iO.IsOn( "IN_CV_DETECT_00" );
  608. /// <summary>
  609. /// 실물 감지
  610. /// </summary>
  611. /// <returns></returns>
  612. public bool IsDetectedCenter() => this.iO.IsOn( "IN_CV_DETECT_01" );
  613. bool IsDetectedLoadStop() => this.iO.IsOn( "IN_CV_DETECT_02" );
  614. bool IsInverterError() => this.iO.IsOn( "IN_CV_ERROR" );
  615. bool IsLifterPositinCheck() => this.iO.IsOn( "IN_LIFTER_POSITION_DETECT" );
  616. bool IsLifterDuplication() => this.iO.IsOn( "IN_LIFTER_DUPLICATION_DETECT" );
  617. bool IsPIOInterLockOn() => this.iO.IsOn( "OUT_PIO_INTERLOCK" );
  618. int Load_Carrier()
  619. {
  620. if ( IsDetectedCenter() )
  621. return 9;
  622. OnOffConveyor( true, true );
  623. long sTime = SwUtils.CurrentTimeMillis;
  624. while ( true )
  625. {
  626. if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) ) //Wait 20Sec
  627. {
  628. OnOffConveyor( false, true );
  629. return 10;
  630. }
  631. if ( IsDetectedLoadStart() )
  632. break;
  633. }
  634. return 0;
  635. }
  636. int UnloadCarrier()
  637. {
  638. if ( !IsDetectedLoadStart() )
  639. return 11;
  640. OnOffConveyor( true, true );
  641. long sTime = SwUtils.CurrentTimeMillis;
  642. while ( true )
  643. {
  644. if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) ) //Wait 20Sec
  645. {
  646. OnOffConveyor( false, true );
  647. return 12;
  648. }
  649. if ( !IsDetectedLoadStart() )
  650. break;
  651. }
  652. return 0;
  653. }
  654. public int PIOAndLoad( string targetName )
  655. {
  656. #if SIMULATION
  657. PIOClear();
  658. loggerPIO.I($"Start Load PIO - [{targetName}]");
  659. this.OnPIOStart?.Invoke(true);
  660. this.iO.WriteOutputIO("OUT_PIO_RECEIVE_RUN", true);
  661. loggerPIO.I("[Vehicle] - 4 Receive Run On");
  662. Thread.Sleep(1000);//상대 IO 기다린다 생각.
  663. loggerPIO.E("[Port] - 4 Ready On");
  664. //Conveyor Start
  665. loggerPIO.I("[Vehicle] - Conveyor Run");
  666. this.OnConveyorStart?.Invoke(true);
  667. Thread.Sleep(10000);//Conveyor 구동
  668. this.OnCarrierDetected?.Invoke(true);
  669. PIOClear();
  670. Thread.Sleep(1000);
  671. this.OnConveyorStop?.Invoke(true);
  672. #else
  673. var pioTimeout = sql.ConfigDal.GetValueToInt( ConstString.PIOTimeOut );
  674. if ( this.IsInverterError() )
  675. return 16;
  676. if ( this.IsLifterPositinCheck() )
  677. return 14;
  678. if ( !this.IsLifterDuplication() )
  679. {
  680. this.OnFailReport?.Invoke( eFailCode.Load_PortHasNotCarrier );
  681. return 0;
  682. }
  683. if ( this.IsDetectedCenter() )
  684. {
  685. this.OnFailReport?.Invoke( eFailCode.Load_VehicleHasCarrier );
  686. return 0;
  687. }
  688. PIOClear();
  689. loggerPIO.I( $"Start Load PIO - [{targetName}]" );
  690. this.OnPIOStart?.Invoke( true );
  691. this.iO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true );
  692. loggerPIO.I( "[Vehicle] - 4 Receive Run On" );
  693. if ( !this.iO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SENDABLE" ) )
  694. {
  695. PIOClear();
  696. loggerPIO.E( "[Port] - 4 Ready Time Out" );
  697. this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
  698. return 0;
  699. }
  700. loggerPIO.E( "[Port] - 4 Ready On" );
  701. this.SetConveyorSpeed( true );
  702. this.OnOffConveyor( true, true );
  703. this.iO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true );
  704. loggerPIO.I( "[Vehicle] - Conveyor Run" );
  705. this.OnConveyorStart?.Invoke( true );
  706. if ( !this.iO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SEND_RUN" ) )
  707. {
  708. this.OnOffConveyor( false, true );
  709. PIOClear();
  710. loggerPIO.E( "[Port] - 5 Sending Run Time Out" );
  711. this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
  712. return 0;
  713. }
  714. bool isStartDetected = false;
  715. var sTime = SwUtils.CurrentTimeMillis;
  716. while ( true )
  717. {
  718. if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) )
  719. {
  720. PIOClear();
  721. this.OnOffConveyor( false, true );
  722. loggerPIO.E( "[Vehicle] Conveyor Wait Time Out" );
  723. this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
  724. if ( this.IsDetectedLoadStart() ) // 감지가 시작 되었으면 이동중 Error 로 판단 설비를 정지 상태로
  725. return 10; //Conveyor Moving Timeout
  726. else
  727. return 0;
  728. }
  729. if ( this.IsDetectedLoadStart() && !isStartDetected )
  730. isStartDetected = true;
  731. if ( !this.IsDetectedLoadStart() && isStartDetected )
  732. this.SetConveyorSpeed( false );
  733. if ( this.IsDetectedLoadStop() ) break;
  734. if ( this.IsPIOInterLockOn() )
  735. {
  736. PIOClear();
  737. this.OnOffConveyor( false ); //Stop
  738. loggerPIO.E( "[Port] PIO InterLock On " );
  739. return 19; //
  740. }
  741. }
  742. if ( this.IsDetectedCenter() )
  743. this.OnCarrierDetected?.Invoke( true );
  744. this.OnOffConveyor( false ); //Stop
  745. PIOClear();
  746. this.OnConveyorStop?.Invoke( true );
  747. this.iO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", true );
  748. this.iO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false, 1000 );
  749. this.OnLoadComplete?.Invoke();
  750. #endif
  751. return 0;
  752. }
  753. public int PIOAndUnload( string targetName )
  754. {
  755. #if SIMULATION
  756. PIOClear();
  757. loggerPIO.I($"Start Unload PIO - [{targetName}]");
  758. this.OnPIOStart?.Invoke(false);
  759. Thread.Sleep(1000);
  760. this.iO.WriteOutputIO("OUT_PIO_READY", true);
  761. loggerPIO.I("[Vehicle] - 1 Ready On");
  762. Thread.Sleep(1000);
  763. this.OnConveyorStart?.Invoke(false);
  764. Thread.Sleep(10000);
  765. this.OnOffConveyor(false); //Stop
  766. this.OnConveyorStop?.Invoke(false);
  767. PIOClear();
  768. this.OnUnloadComplete?.Invoke();
  769. #else
  770. var pioTimeout = sql.ConfigDal.GetValueToInt( ConstString.PIOTimeOut );
  771. if ( this.IsInverterError() )
  772. return 16;
  773. if ( this.IsLifterDuplication() )
  774. {
  775. this.OnFailReport?.Invoke( eFailCode.Unload_PortHasCarrier );
  776. return 0;
  777. }
  778. if ( !this.IsDetectedCenter() )
  779. {
  780. this.OnFailReport?.Invoke( eFailCode.Unload_VehicleHasNotCarrier );
  781. return 0;
  782. }
  783. if ( this.IsLifterPositinCheck() )
  784. return 13;
  785. PIOClear();
  786. loggerPIO.I( $"Start Unload PIO - [{targetName}]" );
  787. this.OnPIOStart?.Invoke( false );
  788. if ( !this.iO.IsOn( "IN_PIO_READY" ) )
  789. {
  790. loggerPIO.E( "[Port] - 1 Ready not On" );
  791. this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
  792. return 0;
  793. }
  794. this.iO.WriteOutputIO( "OUT_PIO_READY", true );
  795. loggerPIO.I( "[Vehicle] - 1 Ready On" );
  796. if ( !this.iO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_RECEIVE_RUN" ) )
  797. {
  798. PIOClear();
  799. loggerPIO.E( "[Port] - 2 Receive CV Run Timeout" );
  800. this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
  801. return 0;
  802. }
  803. this.iO.WriteOutputIO( "OUT_PIO_SENDING_RUN", true );
  804. loggerPIO.I( "[Vehicle] - 2 Send Run On" );
  805. this.SetConveyorSpeed( true );
  806. this.OnOffConveyor( true );
  807. this.OnConveyorStart?.Invoke( false );
  808. var sTime = SwUtils.CurrentTimeMillis;
  809. while ( true )
  810. {
  811. if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) )
  812. {
  813. PIOClear();
  814. this.OnOffConveyor( false, true );
  815. loggerPIO.E( "[Port] Conveyor Wait Time Out" );
  816. this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
  817. if ( IsDetectedLoadStart() || IsDetectedCenter() ) //중간에 걸려 있다고 생각해서 알람 처리.
  818. return 12; //Conveyor Moving Timeout
  819. else
  820. return 0;
  821. }
  822. if ( this.iO.IsOn( "IN_PIO_RECEIVE_COMPLITE" ) )
  823. break;
  824. }
  825. if ( !IsDetectedCenter() )
  826. this.OnCarrierDetected?.Invoke( false );
  827. this.OnOffConveyor( false ); //Stop
  828. this.OnConveyorStop?.Invoke( false );
  829. PIOClear();
  830. this.iO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", true );
  831. this.iO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", false, 1000 );
  832. this.OnUnloadComplete?.Invoke();
  833. #endif
  834. return 0;
  835. }
  836. void PIOClear()
  837. {
  838. string[] pio = { "OUT_PIO_READY", "OUT_PIO_SENDING_RUN", "OUT_PIO_SEND_COMPLITE", "OUT_PIO_RECEIVABLE", "OUT_PIO_RECEIVE_RUN", "OUT_PIO_RECIVE_COMPLITE", "OUT_PIO_INTERLOCK" };
  839. pio.FwEach( x => { this.iO.OutputOff( x ); } );
  840. }
  841. #endregion
  842. #endregion
  843. #region Hardware Create Method
  844. void CreateSteering()
  845. {
  846. this.steering = new Steering( this.iO, this.sql, this.eventAggregator );
  847. this.steering.OnSteeringError += Steering_OnSteeringError;
  848. }
  849. void CreateClamp()
  850. {
  851. this.clamp = new Clamp( this.sql, this.eventAggregator );
  852. this.clamp.Init();
  853. }
  854. #endregion
  855. #region Help Method
  856. /// <summary>
  857. /// 현재 좌표 값이 등록된 Route 에 맞는 위치인지 확인한다.
  858. /// 판단 기준은 Route 에 Tolerance 범위를 사용.
  859. /// </summary>
  860. /// <param name="route"></param>
  861. /// <param name="currentPosition"></param>
  862. /// <returns></returns>
  863. bool CorrectPosition( Route route, double currentPosition )
  864. {
  865. var rScale = route.ScaleValue;
  866. var rTolerance = route.ScaleTolerance;
  867. var result = currentPosition - rScale;
  868. if ( rTolerance < Math.Abs( result ) )
  869. return false;
  870. return true;
  871. }
  872. /// <summary>
  873. /// if no is zero, Laser Off
  874. /// bit Off, On, On, On,On Area1
  875. /// </summary>
  876. /// <param name="no"> 0 == Off Laser</param>
  877. /// <returns></returns>
  878. bool ChgObstacleDetectPattern( int no )
  879. {
  880. var bitArray = BitUtils.ChgBitArray( no );
  881. int bitIndex = 0;
  882. this.obstacleBitList.ForEach( b =>
  883. {
  884. if ( bitArray[bitIndex] )
  885. this.iO.OutputOff( b );
  886. else
  887. this.iO.OutputOn( b );
  888. bitIndex++;
  889. } );
  890. return true;
  891. }
  892. int GetObstacleDetectPattern()
  893. {
  894. int bitIndex = 0;
  895. BitArray bitArray = new BitArray( this.obstacleBitList.Count );
  896. this.obstacleBitList.ForEach( b =>
  897. {
  898. if ( this.iO.IsOn( b ) )
  899. bitArray.Set( bitIndex, false );
  900. else
  901. bitArray.Set( bitIndex, true );
  902. bitIndex++;
  903. } );
  904. return BitUtils.ChgInt32( bitArray );
  905. }
  906. #endregion
  907. #region Event Subscribe
  908. private void Steering_OnSteeringError( object sender, int e )
  909. {
  910. if ( e != 0 )
  911. {
  912. logger.E( $"[Steering] - Control Error {e}" );
  913. this.autoManager.ProcessAlarm( e );
  914. }
  915. else
  916. {
  917. var msg = new DriveControlEventArgs()
  918. {
  919. EventDir = DriveControlEventArgs.eEventDir.ToFront,
  920. ControlKind = DriveControlEventArgs.eControlKind.Steering,
  921. Result = FluentResults.Results.Ok<DriveControlEventArgs.eMoveDir>( DriveControlEventArgs.eMoveDir.LEFT ),
  922. };
  923. this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Publish( msg );
  924. }
  925. }
  926. #endregion
  927. }
  928. }