| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using FluentResults;
- using GSG.NET.Concurrent;
- using GSG.NET.Extensions;
- using GSG.NET.LINQ;
- using GSG.NET.Logging;
- using GSG.NET.Quartz;
- using GSG.NET.Utils;
- using OHV.Common.Events;
- using OHV.Common.Model;
- using OHV.Common.Shareds;
- using OHV.SqliteDAL;
- using Prism.Events;
- using VehicleControlSystem.ControlLayer.Actuator.Cylinder;
- using VehicleControlSystem.ControlLayer.Drive;
- using VehicleControlSystem.ControlLayer.IO;
- using VehicleControlSystem.ControlLayer.MQ;
- using VehicleControlSystem.ControlLayer.Serial.BatteryTabos;
- using VehicleControlSystem.ControlLayer.Serial.DataModel;
- using VehicleControlSystem.Managers;
- using static VehicleControlSystem.ControlLayer.Drive.GSIDrive;
- namespace VehicleControlSystem.ControlLayer
- {
- public class VehicleRefObjects
- {
- public GSIDrive Drive { get; set; }
- public Clamp Clamp { get; set; }
- public Conveyor Conveyor { get; set; }
- public EzIO IO { get; set; }
- public Steering Steering { get; set; }
- public BMUManager BMUManager { get; set; }
- public ZmqManager ZmqManager { get; set; }
- public List<Alarm> Alarms { get; set; }
- public HostManager HostManager { get; set; }
- public SqliteManager Sqlite { get; set; }
- public AutoManager AutoManager { get; set; }
- }
- /// <summary>
- /// Control Layer 의 자원을 여기서 사용하자.
- /// </summary>
- public class Vehicle : ControlObjectBase, IDisposable
- {
- /// <summary>
- /// OCS Report Code
- /// 목적지에 도착해서 Load, Unload 시 발생하는 Alarm
- /// </summary>
- public enum eFailCode
- {
- Load_PortHasNotCarrier = 1,
- Load_VehicleHasCarrier,
- Unload_PortHasCarrier,
- Unload_VehicleHasNotCarrier,
- LoadPIOInterlockTimeout,
- UnlaodPIOInterlockTimeout,
- }
- static Logger logger = Logger.GetLogger();
- static Logger loggerPIO = Logger.GetLogger( "PIO" );
- #region Properties
- /// <summary>
- /// Tag 위치
- /// </summary>
- private int currentTag = 0;
- public int CurrentTag
- {
- get { return currentTag; }
- set
- {
- if ( SetField( ref this.currentTag, value ) )
- {
- var info = this.refObjects.Sqlite.VehicleInfoDAL.GetAll().FirstOrDefault();
- info.CurrentTag = value.ToString();
- this.refObjects.Sqlite.VehicleInfoDAL.Update( info );
- this.OnCurrentTagChanged?.Invoke( value );
- }
- }
- }
- /// <summary>
- /// Scale Value
- /// </summary>
- private double currentPosition;
- public double CurrentPosition
- {
- get { return currentPosition; }
- set
- {
- if ( SetField( ref this.currentPosition, value ) )
- {
- }
- }
- }
- private double currentSpeed;
- public double CurrentSpeed
- {
- get { return currentSpeed; }
- set { SetField( ref this.currentSpeed, value ); }
- }
- private double currentTorque;
- public double CurrentTorque
- {
- get { return currentTorque; }
- set { SetField( ref this.currentTorque, value ); }
- }
- private bool isContain;
- public bool IsContain
- {
- get { return isContain; }
- set { SetField( ref this.isContain, value ); }
- }
- eClampState _clampState;
- public eClampState ClampState
- {
- get { return this._clampState; }
- set { this.SetField( ref this._clampState, value ); }
- }
- private eSteeringState steeringState;
- public eSteeringState SteeringState
- {
- get { return steeringState; }
- set
- {
- if ( SetField( ref this.steeringState, value ) )
- {
- this.refObjects.ZmqManager.SetCurrentSteeringState( value );
- }
- }
- }
- private int _obstacleDrive;
- public int ObstacleDrive { get { return this._obstacleDrive; } set { SetField( ref this._obstacleDrive, value ); } }
- private int _obstacleCurve;
- public int ObstacleCurve { get { return this._obstacleCurve; } set { SetField( ref this._obstacleCurve, value ); } }
- private int obstacleCurrent;
- public int ObstacleCurrent { get { return this.ObstacleCurrent; } set { SetField( ref this.obstacleCurrent, value ); } }
- private eObstacleState obstacleState = eObstacleState.Normal;
- public eObstacleState ObstacleStateProperty
- {
- get { return obstacleState; }
- set
- {
- if ( SetField( ref this.obstacleState, value ) )
- {
- if ( value == eObstacleState.Blocked )
- this.VehicleStateProperty = eVehicleState.Blocked;
- }
- }
- }
- private eVehicleState vehicleState = eVehicleState.None;
- public eVehicleState VehicleStateProperty
- {
- get { return vehicleState; }
- set
- {
- if ( SetField( ref this.vehicleState, value ) )
- {
- var info = this.refObjects.Sqlite.VehicleInfoDAL.GetAll().FirstOrDefault();
- info.VehicleState = value;
- this.refObjects.Sqlite.VehicleInfoDAL.Update( info );
- }
- }
- }
- private eMachineMode machineMode = eMachineMode.LocalMode;
- public eMachineMode MachineMode
- {
- get { return machineMode; }
- set
- {
- if ( SetField( ref this.machineMode, value ) )
- {
- var info = this.refObjects.Sqlite.VehicleInfoDAL.GetAll().FirstOrDefault();
- info.MachineMode = value;
- this.refObjects.Sqlite.VehicleInfoDAL.Update( info );
- }
- }
- }
- private int obstaclePattern;
- public int ObstaclePattern
- {
- get { return obstaclePattern; }
- set { SetField( ref this.obstaclePattern, value ); }
- }
- private DriveState frontDriveState;
- public DriveState FrontDriveState
- {
- get { return frontDriveState; }
- set { SetField( ref this.frontDriveState, value ); }
- }
- private DriveState rearDriveState;
- public DriveState RearDriveState
- {
- get { return rearDriveState; }
- set { SetField( ref this.rearDriveState, value ); }
- }
- private eVehicleAutoReadyState autoReadyState;
- public eVehicleAutoReadyState AutoReadyState
- {
- get { return autoReadyState; }
- set { SetField(ref this.autoReadyState, value);}
- }
- //이동
- public bool Busy
- {
- get
- {
- return this.CurrentSubCommand == null ? false : true;
- }
- set { }
- }
- public bool IsMoving { get => this.refObjects.Drive.IsDriveMoving(); }
- private bool batteryChargeState;
- public bool BatteryChargeState
- {
- get { return batteryChargeState; }
- set
- {
- if ( SetField( ref batteryChargeState, value ) )
- {
- if ( value )
- {
- this.OnChargingStart?.Invoke();
- LockUtils.Wait( 200 );
- this.OnCharging?.Invoke();
- QuartzUtils.Invoke( "BatterLogger", QuartzUtils.GetExpnMinute( 1 ), () => { batteryLogger.I( $"SOC - {this.BatteryStateOfCharge} / Current - {this.BatteryCurrent} / Voltage - {this.BatteryVoltage} / Capacity - {this.BatteryCapacity} / Energy - {this.BatteryEnergy}" ); } );
- }
- else
- QuartzUtils.StopSchedule( "BatterLogger" );
- }
- }
- }
- #region Battery Property
- double batteryVoltage;
- public double BatteryVoltage
- {
- get { return this.batteryVoltage; }
- set
- {
- //var d = Math.Truncate( value * 10 ) / 10;
- //this.SetField( ref this.batteryVoltage, d );
- this.SetField( ref this.batteryVoltage, value );
- }
- }
- double batteryCurrent;
- public double BatteryCurrent
- {
- get { return this.batteryCurrent; }
- set { this.SetField( ref this.batteryCurrent, value ); }
- }
- double batteryState;
- public double BatteryState
- {
- get { return this.batteryState; }
- set { this.SetField( ref this.batteryState, value ); }
- }
- double batteryChargeTime;
- public double BatteryChargeTime
- {
- get { return this.batteryChargeTime; }
- set { this.SetField( ref this.batteryChargeTime, value ); }
- }
- double batteryDisChargeTime;
- public double BatteryDisChargeTime
- {
- get { return this.batteryDisChargeTime; }
- set { this.SetField( ref this.batteryDisChargeTime, value ); }
- }
- double batteryStateOfCharge;
- public double BatteryStateOfCharge
- {
- get { return this.batteryStateOfCharge; }
- set { if ( this.SetField( ref this.batteryStateOfCharge, value ) ) { this.BatteryChargeStateLED( value ); } }
- }
- double batteryStateOfHealth;
- public double BatteryStateOfHealth
- {
- get { return this.batteryStateOfHealth; }
- set
- {
- if ( this.SetField( ref this.batteryStateOfHealth, value ) ) { }
- }
- }
- double batteryCapacity;
- public double BatteryCapacity
- {
- get { return this.batteryCapacity; }
- set { this.SetField( ref this.batteryCapacity, value ); }
- }
- double batteryEnergy;
- public double BatteryEnergy
- {
- get { return this.batteryEnergy; }
- set
- {
- var d = Math.Truncate( value * 10 ) / 10;
- this.SetField( ref this.batteryEnergy, d );
- }
- }
- double batteryTemperature;
- public double BatteryTemperature
- {
- get { return this.batteryTemperature; }
- set { this.SetField( ref this.batteryTemperature, value ); }
- }
- bool batteryIsConnect;
- public bool BatteryIsConnect
- {
- get
- {
- return batteryIsConnect;
- }
- set { this.SetField( ref this.batteryIsConnect, value ); }
- }
- #endregion
- public bool IsError { get; set; }
- public SubCmd CurrentSubCommand { get; private set; }
- double frontLoadFactor = 0;
- public double FrontLoadFactor
- {
- get { return this.frontLoadFactor; }
- set { SetField( ref this.frontLoadFactor, value ); }
- }
- double frontRpm = 0;
- public double FrontRpm
- {
- get { return this.frontRpm; }
- set { SetField( ref this.frontRpm, value ); }
- }
- double frontSpeed = 0;
- public double FrontSpeed
- {
- get { return this.frontSpeed; }
- set { SetField( ref this.frontSpeed, value ); }
- }
- double frontTorque = 0;
- public double FrontTorque
- {
- get { return this.frontTorque; }
- set { SetField( ref this.frontTorque, value ); }
- }
- double rearLoadFactor = 0;
- public double RearLoadFactor
- {
- get { return this.rearLoadFactor; }
- set { SetField( ref this.rearLoadFactor, value ); }
- }
- double rearRpm = 0;
- public double RearRpm
- {
- get { return this.rearRpm; }
- set { SetField( ref this.rearRpm, value ); }
- }
- double rearSpeed = 0;
- public double RearSpeed
- {
- get { return this.rearSpeed; }
- set { SetField( ref this.rearSpeed, value ); }
- }
- double rearTorque = 0;
- public double RearTorque
- {
- get { return this.rearTorque; }
- set { SetField( ref this.rearTorque, value ); }
- }
- private double linearSpeed;
- public double LinearSpeed
- {
- get { return linearSpeed; }
- set { SetField(ref this.linearSpeed, value); }
- }
- private double curveSpeed;
- public double CurveSpeed
- {
- get { return curveSpeed; }
- set { SetField(ref this.curveSpeed, value); }
- }
- private double accelSpeed;
- public double AccelSpeed
- {
- get { return accelSpeed; }
- set { SetField(ref this.accelSpeed , value); }
- }
- private double decelSpeed;
- public double DecelSpeed
- {
- get { return decelSpeed; }
- set { SetField(ref this.decelSpeed, value); }
- }
- private double creepSpeed;
- public double CreepSpeed
- {
- get { return creepSpeed; }
- set { SetField(ref this.creepSpeed, value); }
- }
- private double creepDistance;
- public double CreepDistance
- {
- get { return creepDistance; }
- set { SetField(ref this.creepDistance , value); }
- }
- private double jogSpeed;
- public double JogSPeed
- {
- get { return jogSpeed; }
- set { SetField(ref this.jogSpeed , value); }
- }
- #endregion
- #region Event
- public event Action OnMoveReady;
- public event Action OnMoving;
- public event Action OnMoveFinish;
- public event Action OnChargingStart;
- public event Action OnCharging;
- public event Action OnChargingFull;
- public event Action<double> OnBatteryVelueChanged;
- public event Action<bool> OnPIOStart;
- public event Action<bool> OnConveyorStart;
- public event Action<bool> OnConveyorStop;
- public event Action<bool> OnCarrierDetected;
- public event Action OnLoadComplete;
- public event Action OnUnloadComplete;
- public event Action<int> OnCurrentTagChanged;
- public event Action OnManualMove;
- public event Action OnManualLoad;
- public event Action OnManualUnload;
- public event Action OnManualCharging;
- public event Action<eFailCode> OnFailReport;
- #endregion
- #region List.
- List<ICylinder> cylinders = new List<ICylinder>();
- List<string> obstacleBitList = new List<string>();
- #endregion
- VehicleRefObjects refObjects = null;
- //SqliteManager sql = null;
- //AutoManager autoManager = null;
- ThreadCancel cancel = new ThreadCancel();
- TaskCancel taskCancel = new TaskCancel();
- TaskCancel taskMoveCancel = new TaskCancel();
- IEventAggregator eventAggregator;
- public Vehicle( IEventAggregator ea )
- {
- this.obstacleBitList.AddRange( new string[]
- {
- "OUT_OBSTRUCTION_PATTERN_00",
- "OUT_OBSTRUCTION_PATTERN_01",
- "OUT_OBSTRUCTION_PATTERN_02",
- "OUT_OBSTRUCTION_PATTERN_03",
- "OUT_OBSTRUCTION_PATTERN_04",
- } );
- this.eventAggregator = ea;
- this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Unsubscribe( ReceiveDriveControlEvent );
- this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Subscribe( ReceiveDriveControlEvent );
- this.eventAggregator.GetEvent<ObstacleControlPubSubEvent>().Unsubscribe( ObstacleReceiveEvent );
- this.eventAggregator.GetEvent<ObstacleControlPubSubEvent>().Subscribe( ObstacleReceiveEvent );
- }
- public void DependencyInjection( VehicleRefObjects vehicleRefObjects )
- {
- this.refObjects = vehicleRefObjects;
- this.refObjects.IO.OnChangedIO += IO_OnChangedIO;
- this.refObjects.BMUManager.OnConnect += BMUManager_OnConnect;
- this.refObjects.BMUManager.OnDisconnect += BMUManager_OnDisconnect;
- this.refObjects.BMUManager.OnChangedReceivedData += BMUManager_OnChangedReceivedData;
- this.refObjects.BMUManager.OnFirstColtd += BMUManager_OnFirstColtd;
- this.refObjects.Drive.PropertyChanged += Motion_PropertyChanged;
- this.refObjects.Clamp.PropertyChanged += Clamp_PropertyChanged;
- this.refObjects.Steering.OnSteeringError += Steering_OnSteeringError;
- this.refObjects.Steering.PropertyChanged += Steering_PropertyChanged;
- this.refObjects.ZmqManager.PropertyChanged += ZmqManager_PropertyChanged;
- this.refObjects.AutoManager.OnOperationModeChanged += AutoManager_OnOperationModeChanged;
- }
- private void ObstacleReceiveEvent( ObstacleControlEventArgs obj )
- {
- if ( this.refObjects.AutoManager.OperationModeProperty != eOperatationMode.ManualMode )
- return;
- if ( obj.EventDir == ObstacleControlEventArgs.eEventDir.ToBack )
- {
- switch ( obj.ControlKind )
- {
- case ObstacleControlEventArgs.eControlKind.NONE:
- break;
- case ObstacleControlEventArgs.eControlKind.DRIVE:
- //this.ChgObstacleDetectPattern( new Random().Next( 0 , 40 ) );
- break;
- case ObstacleControlEventArgs.eControlKind.CURVE:
- //this.ChgObstacleDetectPattern( new Random().Next( 0 , 40 ) );
- break;
- case ObstacleControlEventArgs.eControlKind.STATE:
- //var value = this.GetObstacleDetectPattern();
- break;
- case ObstacleControlEventArgs.eControlKind.INFO:
- {
- var msg = new ObstacleControlEventArgs
- {
- ControlKind = ObstacleControlEventArgs.eControlKind.INFO,
- Drive = this.ObstacleDrive,
- Curve = this.ObstacleCurve,
- Current = this.GetObstacleDetectPattern(),
- ObstacleState = this.ObstacleStateProperty.ToString()
- };
- this.ObstacleControlEventPublish( msg );
- }
- break;
- case ObstacleControlEventArgs.eControlKind.SAVE:
- {
- this.ObstacleCurve = obj.Curve;
- this.ObstacleDrive = obj.Drive;
- var reply = new ObstacleControlEventArgs
- {
- ControlKind = ObstacleControlEventArgs.eControlKind.SAVE
- };
- reply.Result = Results.Ok( ObstacleControlEventArgs.eControlKind.SAVE );
- this.ObstacleControlEventPublish( reply );
- }
- break;
- }
- }
- }
- private void ObstacleControlEventPublish( ObstacleControlEventArgs args )
- {
- args.EventDir = ObstacleControlEventArgs.eEventDir.ToFront;
- this.eventAggregator.GetEvent<ObstacleControlPubSubEvent>().Publish( args );
- }
- private void ReceiveDriveControlEvent( DriveControlEventArgs _args )
- {
- var msg = _args;
- if ( msg.EventDir == DriveControlEventArgs.eEventDir.ToBack )
- {
- switch ( msg.ControlKind )
- {
- case DriveControlEventArgs.eControlKind.MOVE:
- this.ReqMoveToPos( _args );
- break;
- case DriveControlEventArgs.eControlKind.STOP:
- break;
- case DriveControlEventArgs.eControlKind.Steering:
- if ( msg.MoveDir == DriveControlEventArgs.eMoveDir.LEFT )
- this.refObjects.Steering.ControlSteering( true );
- else
- this.refObjects.Steering.ControlSteering();
- break;
- case DriveControlEventArgs.eControlKind.SteeringState:
- {
- var reply = new DriveControlEventArgs();
- reply.ControlKind = DriveControlEventArgs.eControlKind.SteeringState;
- if ( this.refObjects.Steering.IsLeft() )
- {
- reply.Args = eSteeringState.Left;
- reply.Result = FluentResults.Results.Ok();
- }
- else if ( this.refObjects.Steering.IsRight() )
- {
- reply.Args = eSteeringState.Right;
- reply.Result = FluentResults.Results.Ok();
- }
- else
- reply.Result = FluentResults.Results.Fail( new Error() );
- this.DriveControlEventPublish( reply );
- }
- break;
- case DriveControlEventArgs.eControlKind.ReqCurrentPos:
- //this.ReqCurrentPos();
- break;
- case DriveControlEventArgs.eControlKind.ReqStopCurrentPos:
- //this.taskCancel.Cancel();
- //this.taskCancel.WaitAll();
- break;
- case DriveControlEventArgs.eControlKind.FaultReset:
- this.ReqFaultReset( _args );
- break;
- case DriveControlEventArgs.eControlKind.DriveON:
- this.ReqDriveOn( _args );
- break;
- case DriveControlEventArgs.eControlKind.DriveOFF:
- this.ReqDriveOff( _args );
- break;
- case DriveControlEventArgs.eControlKind.JOG:
- this.ReqJog( _args );
- break;
- case DriveControlEventArgs.eControlKind.VehicleState:
- ReqVehicleState( _args );
- break;
- default:
- break;
- }
- }
- }
- public void ReqConveyorMove( string dir )
- {
- if ( dir.Equals( "CW" ) )
- this.refObjects.Conveyor.OnOffConveyor( true, false );
- else if ( dir.Equals( "CCW" ) )
- this.refObjects.Conveyor.OnOffConveyor( true, true );
- else if ( dir.Equals( "STOP" ) )
- this.refObjects.Conveyor.OnOffConveyor( false, false );
- }
- private void DriveControlEventPublish( DriveControlEventArgs args )
- {
- args.EventDir = DriveControlEventArgs.eEventDir.ToFront;
- this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Publish( args );
- }
- public void Init()
- {
- ThreadStart();
- //TimerUtils.Once(5000, () => { this.CurrentPosition = 1000; });
- var v = refObjects.Sqlite.VehicleInfoDAL.GetAll().FirstOrDefault();
- v.CurrentTag = "0000";
- v.VehicleState = eVehicleState.None;
- v.MachineMode = eMachineMode.LocalMode;
- refObjects.Sqlite.VehicleInfoDAL.Update( v );
- }
- public int InitializationVehicle()
- {
- #if SIMULATION
- this.VehicleStateProperty = eVehicleState.Idle;
- return 0;
- #else
- int result = 0;
- //PIOClear();
- //PIOSensorOff();
- result = this.refObjects.Clamp.IsAllAxisOriginReturn();
- if ( result != ConstInt.EXECUTE_SUCCESS )
- {
- this.refObjects.Clamp.AllOriginReturn();
- LockUtils.Wait( 2000 );
- }
- if ( this.refObjects.Conveyor.IsDetectedCenter() ) //자제가 있으면 Lock
- result = this.refObjects.Clamp.Lock_Sync();
- else
- result = this.refObjects.Clamp.Unlock_Sync();
- result = 0;
- if ( result != 0 )
- {
- this.VehicleStateProperty = eVehicleState.Abnormal;
- return result;
- }
- if ( this.refObjects.Drive.IsErrorOn )
- return 22;
- this.VehicleStateProperty = eVehicleState.Idle;
- return result;
- #endif
- }
- public void Dispose()
- {
- this.taskCancel.Cancel();
- this.cancel.Cancel();
- this.cancel.StopWaitAll();
- //this.bMUManager.Disconnect();
- //this.drive.Dispose();
- }
- #region Request Method
- private void ReqVehicleState( DriveControlEventArgs args )
- {
- VehicleInfo state = new VehicleInfo();
- state.CurrentPosition = this.CurrentPosition;
- state.CurrentSpeed = this.CurrentSpeed;
- state.CurrentTag = this.CurrentTag.ToString();
- state.CurrentTorque = this.CurrentTorque;
- var msg = new DriveControlEventArgs();
- msg.ControlKind = args.ControlKind;
- msg.Args = state;
- DriveControlEventPublish( msg );
- }
- private void ReqMoveToPos( DriveControlEventArgs args )
- {
- //var result = drive.Move( args.PositionTag );
- //this.MoveTo( "1111" );
- var reply = new DriveControlEventArgs();
- int targetTag = args.TargetRouteID;
- var route = this.refObjects.Sqlite.RouteDal.Get( x => x.Name.Equals( targetTag ) ).FirstOrDefault();
- if ( route == null )
- {
- reply.Result = Results.Fail( "Not Found Route" );
- this.DriveControlEventPublish( reply );
- return;
- }
- var subCommand = new SubCmd();
- subCommand.TargetID = route.Name;
- this.MoveTo( subCommand );
- reply.Result = Results.Ok( "Position Move" );
- this.DriveControlEventPublish( reply );
- }
- void ReqFaultReset( DriveControlEventArgs _args )
- {
- var drive = 0;
- //var result = drive.ResetAmpFault();
- var msg = new DriveControlEventArgs
- {
- ControlKind = DriveControlEventArgs.eControlKind.FaultReset
- };
- msg.Result = Results.Ok( "Drive On" );
- this.DriveControlEventPublish( msg );
- }
- void ReqJog( DriveControlEventArgs _args )
- {
- if ( _args.JogDir == DriveControlEventArgs.eJogMoveDir.Positive )
- this.refObjects.Drive.JogForword();
- else
- this.refObjects.Drive.JogBackword();
- }
- Logger batteryLogger = Logger.GetLogger( "BatteryLogger" );
- void ReqCurrentPos()
- {
- var task = Task.Factory.StartNew( () =>
- {
- while ( !this.taskCancel.Canceled )
- {
- LockUtils.Wait( 1000 );
- batteryLogger.I( $"SOC - {this.BatteryStateOfCharge} / Current - {this.BatteryCurrent} / Voltage - {this.BatteryVoltage} / Capacity - {this.BatteryCapacity} / Energy - {this.BatteryEnergy}" );
- //var msg = new DriveControlEventArgs
- //{
- // EventDir = DriveControlEventArgs.eEventDir.ToFront,
- // ControlKind = DriveControlEventArgs.eControlKind.ReqCurrentPos,
- // CurrentPosition = new Random().Next( 0, 1000 ),
- //};
- //this.DriveControlEventPublish( msg );
- }
- } );
- this.taskCancel.Add( task );
- }
- void ReqDriveOn( DriveControlEventArgs _args )
- {
- var ll = this.refObjects.ZmqManager.SetDriveControl( eDriveControl.ServoOn );
- if(ll == 38)
- {
- logger.E( $"Servo On Error" );
- }
- var msg = new DriveControlEventArgs
- {
- ControlKind = DriveControlEventArgs.eControlKind.DriveON
- };
- msg.Result = Results.Ok( "Drive On" );
- this.DriveControlEventPublish( msg );
- }
- void ReqDriveOff( DriveControlEventArgs _args )
- {
- var ll = this.refObjects.ZmqManager.SetDriveControl( eDriveControl.ServoOff );
- if ( ll == 38 )
- {
- logger.E( $"Servo Off Error" );
- }
- var msg = new DriveControlEventArgs
- {
- ControlKind = DriveControlEventArgs.eControlKind.DriveOFF
- };
- msg.Result = Results.Ok( "Drive On" );
- this.DriveControlEventPublish( msg );
- }
- #endregion
- #region Thread
- void ThreadStart()
- {
- this.cancel.AddGo( new Action( this._ThSubCmdWorker ) );
- this.cancel.AddGo( new Action( this._ThVehicleStateCheck ) );
- }
- //장애물 감지 Thread
- //장애물 감지 패턴 변경도 여기 하자.
- private void _ThVehicleStateCheck()
- {
- while ( !this.cancel.Canceled )
- {
- try
- {
- //if ( this.autoManager.OperationModeProperty == eOperatationMode.AutoMode )
- //this.CheckObstacle();
- //this.CheckIOState();
- }
- catch ( ThreadInterruptedException threadInterruptedException )
- {
- }
- catch ( Exception exception )
- {
- logger.E( exception );
- }
- finally
- {
- LockUtils.Wait( 5 );
- }
- }
- logger.D( "Vehicle - _ThObstacleChecker Dispose" );
- }
- /// <summary>
- /// Scheduler 가 주는 Sub Command 를 이용하여 동작하자.
- /// </summary>
- public void _ThSubCmdWorker()
- {
- while ( !this.cancel.Canceled )
- {
- try
- {
- if ( this.ObstacleStateProperty != eObstacleState.Normal ) //장애물 감지 상태 시 조그 동작만 가능하게.
- continue;
- if ( this.refObjects.AutoManager.AutoModeStateProperty != eAutoModeState.Run ) //
- continue;
- var subCmd = this.refObjects.Sqlite.SubCmdDAL.GetAll().FirstOrDefault();
- if ( subCmd == null ) continue;
- if ( !this.refObjects.Sqlite.CommandDAL.GetAll().Any( x => x.CommandID.Equals( subCmd.CmdID ) ) )
- {
- if ( subCmd.CmdType == SubCmd.eCmdType.Auto ) //자동 명령중 Main Command 가 없으면 삭제.
- {
- this.refObjects.Sqlite.SubCmdDAL.Delete( subCmd.ID );
- logger.I( $"SubCmd Deleted - ID={subCmd.ID}, CommandID={subCmd.CmdID}" );
- }
- }
- switch ( subCmd.Type )
- {
- case eSubCommandType.Move:
- this.CurrentSubCommand = subCmd;
- this.Move( subCmd );
- break;
- case eSubCommandType.Load:
- this.CurrentSubCommand = subCmd;
- this.LoadCarrier( subCmd );
- break;
- case eSubCommandType.Unload:
- this.CurrentSubCommand = subCmd;
- this.UnloadCarrier( subCmd );
- break;
- case eSubCommandType.Charge:
- this.CurrentSubCommand = subCmd;
- this.BatteryCharge( subCmd );
- break;
- case eSubCommandType.Cancel:
- this.CurrentSubCommand = subCmd;
- CancelCommand( subCmd );
- break;
- default:
- break;
- }
- }
- catch ( Exception exception )
- {
- logger.E( exception );
- }
- finally
- {
- LockUtils.Wait( 500 );
- }
- }
- logger.D( "Vehicle - _ThSubCmdWorker Dispose" );
- }
- private void CancelCommand( SubCmd subCmd )
- {
- this.refObjects.Drive.CancelCommand( subCmd );
- var cmd = this.refObjects.Sqlite.CommandDAL.GetById( subCmd.CmdID );
- cmd.State = eCommandState.Complete;
- this.refObjects.Sqlite.CommandDAL.Update( cmd );
- this.refObjects.Sqlite.SubCmdDAL.Clean();
- logger.D( $"[Cancel Command] {cmd.TargetID} / {cmd.Type}" );
- }
- #endregion
- #region Control Action Method
- public void EStop()
- {
- this.refObjects.Conveyor.OnOffConveyor( false );
- //Clamp EStop
- this.refObjects.Clamp.ClampEStop();
- //this.drive.EStop();
- this.OccurVehicleAlarm( 23 );
- }
- #region For Moving
- void Move( SubCmd sub )
- {
- logger.I( $"[SubCommand Start] - Target : {sub.TargetID} / Type : {sub.Type}" );
- //Move 시작 시 충전 중이면 충전 중지 실행.
- int result = 0;
- if ( this.CheckBatteryCharge() || this.VehicleStateProperty == eVehicleState.Charge || this.BatteryChargeState )
- {
- result = this.StopBatteryCharge();
- if ( result != 0 )
- {
- OccurVehicleAlarm( result );
- return;
- }
- }
- var iTarget = Convert.ToInt32( sub.TargetID );
- if ( iTarget != CurrentTag ) //하나의 목표 위치로 왔을때 현재 위치와 동일 하면 이동안함.
- {
- result = this.MoveTo( sub );
- if ( result != ConstInt.EXECUTE_SUCCESS )
- {
- OccurVehicleAlarm( result );
- }
- }
- this.refObjects.Sqlite.SubCmdDAL.Clean();
- this.taskMoveCancel.Cancel();
- this.taskMoveCancel.WaitAll();
- this.CheckOCSConnectionState();
- logger.I( $"[SubCommand Complete] - Target : {sub.TargetID} / Type : {sub.Type}" );
- }
- int MoveTo( SubCmd sub )
- {
- if ( this.VehicleStateProperty == eVehicleState.Idle )
- {
- this.OnMoveReady?.Invoke();
- var moveReadyBuzzerTime = Convert.ToInt32( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.BuzzerStartReadyTime ).Value );
- Thread.Sleep( moveReadyBuzzerTime );
- this.VehicleStateProperty = eVehicleState.Move;
- }
- this.OnMoving?.Invoke();
- //이전에 있던 작업들 종료 및 삭제
- this.taskMoveCancel.Cancel();
- this.taskMoveCancel.WaitAll();
- this.taskMoveCancel.Add( CheckCrossPoint() );
- this.VehicleStateProperty = eVehicleState.Move;
- int result = this.refObjects.Drive.MoveToPoint( sub, 100 );
- if ( result != ConstInt.EXECUTE_SUCCESS )
- return result;
- result = this.Wait4MoveDone();
- if ( result != ConstInt.EXECUTE_SUCCESS )
- return result;
- //Drive 에서 정지 확인 후 상태 변경
- if ( this.refObjects.Drive.IsDriveStop() )
- {
- this.OnMoveFinish?.Invoke();
- this.VehicleStateProperty = eVehicleState.Idle;
- logger.D( "Move Finish" );
- }
- return result;
- }
- int Wait4MoveDone()
- {
- int waitTime = ConstUtils.ONE_HOUR; //설정 할 수있게.
- long st = SwUtils.CurrentTimeMillis;
- //Todo: 이동시 확인 사항들.
- while ( true )
- {
- Thread.Sleep( 5 );
- if ( SwUtils.Gt( st, waitTime ) )
- {
- logger.D( "Wait4MoveDone Time Over" );
- return 39;
- }
- //Todo: 이동중 명령이 삭제 되면 처리 할일들.
- //이동중 메인 명력이 없어진다면 정지 후
- if ( null == this.refObjects.Sqlite.CommandDAL.GetById( this.CurrentSubCommand.CmdID ) )
- {
- logger.D( "[Wait Move Done] - 메인 명령 사라짐" );
- var cmd = this.refObjects.Sqlite.CommandDAL.GetAll();
- if ( cmd == null )
- {
- logger.D( "[Wait Move Done] - Main Command not Exist Motion Stop" );
- this.refObjects.Drive.Stop();
- return 40;
- }
- else
- {
- logger.D( "[Wait Move Done] - Main Command not Exist Motion command, New Command Exist" );
- break;
- }
- }
- if ( this.refObjects.Drive.IsDriveStop() ) //Move Stop
- break;
- }
- return ConstInt.EXECUTE_SUCCESS;
- }
- Task CheckCrossPoint()
- {
- var task = Task.Run( () =>
- {
- long sTime = SwUtils.CurrentTimeMillis;
- while ( !this.taskMoveCancel.Canceled )
- {
- Thread.Sleep( 10 );
- //ToDo: approach Cross Point Check
- //ToDo: Obstacle Laser Sensor Pattern Change Method 구현 필요.
- }
- } );
- return task;
- }
- #endregion
- public bool LoadCarrier( SubCmd sub )
- {
- logger.I( $"[SubCommand Start] - Target : {sub.TargetID} / Type : {sub.Type}" );
- this.VehicleStateProperty = eVehicleState.Load;
- //var route = sql.RouteDal.GetRoute( sub.TargetID );
- //if ( !CorrectPosition( route, this.CurrentPosition ) )
- //{
- // this.OccurVehicleAlarm( 20 );
- // return false; //Alarm
- //}
- int result = 0;
- result = this.PIOAndLoad( sub.TargetID );
- if ( result != 0 )
- {
- this.PIOSensorOff();
- this.OccurVehicleAlarm( result );
- return false;
- }
- this.PIOSensorOff();
- //Load, Unload 가 끝나면 메인 Command 를 완료 했다고 판단.
- logger.I( $"[SubCommand Complete] - Target : {sub.TargetID} / Type : {sub.Type}" );
- this.refObjects.Sqlite.SubCmdDAL.Clean();
- var cmd = this.refObjects.Sqlite.CommandDAL.GetById( sub.CmdID );
- if ( cmd != null )
- {
- cmd.State = eCommandState.Complete;
- this.refObjects.Sqlite.CommandDAL.Update( cmd );
- }
- TimerUtils.Once( 1000, this.OnLoadComplete );
- //LockUtils.Wait( 1000 );
- //this.OnLoadComplete?.Invoke(); //일찍 주면 다음 명령을 500ms 안에 주는 현상 있음. 그러니까 천천히 주자
- this.VehicleStateProperty = eVehicleState.Idle;
- return true;
- }
- public bool UnloadCarrier( SubCmd sub )
- {
- logger.I( $"[SubCommand Start] - Target : {sub.TargetID} / Type : {sub.Type}" );
- this.VehicleStateProperty = eVehicleState.Unload;
- var targetNo = Convert.ToInt32( sub.TargetID );
- if ( this.CurrentTag != targetNo )
- {
- this.OccurVehicleAlarm( 21 );
- return false; //Alarm
- }
- //var route = sql.RouteDal.GetRoute( sub.TargetID );
- //if ( !CorrectPosition( route, this.CurrentPosition ) )
- //{
- // this.OccurVehicleAlarm( 21 );
- // return false; //Alarm
- //}
- //PIO 내부로 이동.
- //int result = this.clamp.Unlock_Sync();
- //if ( result != 0 )
- //{
- // this.OccurVehicleAlarm( result );
- // return false;
- //}
- int result = 0;
- result = this.PIOAndUnload( sub.TargetID );
- if ( result != 0 )
- {
- this.refObjects.IO.OutputOn( "OUT_PIO_SENSOR_ONOFF" );
- this.OccurVehicleAlarm( result );
- return false;
- }
- this.PIOSensorOff();
- logger.I( $"[SubCommand Complete] - Target : {sub.TargetID} / Type : {sub.Type}" );
- this.refObjects.Sqlite.SubCmdDAL.Clean();
- var cmd = this.refObjects.Sqlite.CommandDAL.GetById( sub.CmdID );
- if ( cmd != null )
- {
- cmd.State = eCommandState.Complete;
- this.refObjects.Sqlite.CommandDAL.Update( cmd );
- }
- TimerUtils.Once( 1000, this.OnUnloadComplete );
- //LockUtils.Wait( 1000 );
- //this.OnUnloadComplete?.Invoke(); //일찍 주면 다음 명령을 500ms 안에 주는 현상 있음. 그러니까 천천히 주자
- this.VehicleStateProperty = eVehicleState.Idle;
- return true;
- }
- public void BatteryCharge( SubCmd subCmd )
- {
- int result = 0;
- result = this.StartBatteryCharge();
- if ( result != ConstInt.EXECUTE_SUCCESS )
- this.OccurVehicleAlarm( result );
- this.refObjects.Sqlite.SubCmdDAL.Clean();
- var cmd = this.refObjects.Sqlite.CommandDAL.GetById( subCmd.CmdID );
- if ( cmd == null )
- return;
- cmd.State = eCommandState.Complete;
- this.refObjects.Sqlite.CommandDAL.Update( cmd );
- }
- /// <summary>
- /// Battery Charge
- /// 충전 시 PIO 를 해야 함.
- /// </summary>
- /// <param name="sub"></param>
- /// <returns></returns>
- int PIOBatteryCharge( SubCmd sub )
- {
- var route = this.refObjects.Sqlite.RouteDal.GetById( sub.TargetID );
- if ( !CorrectPosition( route, this.CurrentPosition ) )
- {
- this.OccurVehicleAlarm( 21 );
- return 0; //Alarm
- }
- var pioTimeout = CastTo<int>.From<string>( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- PIOClear();
- loggerPIO.I( $"Start Charge PIO - [{sub.TargetID}]" );
- if ( !this.refObjects.IO.IsOn( "IN_PIO_READY" ) )
- {
- loggerPIO.E( "[Port] - 1 Ready not On" );
- this.OccurVehicleAlarm( 25 );
- return 0;
- }
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_READY", true );
- loggerPIO.I( "[Vehicle] - 1 Ready On" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_RECEIVE_RUN" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 2 Receive CV Run Timeout" );
- this.OccurVehicleAlarm( 26 );
- return 0;
- }
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SENDING_RUN", true );
- loggerPIO.I( "[Vehicle] - 2 Send Run On" );
- var sTime = SwUtils.CurrentTimeMillis;
- while ( true )
- {
- Thread.Sleep( 5 );
- if ( !this.refObjects.IO.IsOn( "IN_PIO_READY" ) || this.refObjects.IO.IsOn( "IN_PIO_RECEIVE_RUN" ) )
- break;
- if ( null == this.refObjects.Sqlite.CommandDAL.GetById( this.CurrentSubCommand.CmdID ) )
- {
- PIOClear();
- logger.D( "[Wait Charging] - 메인 명령 사라짐" );
- break;
- }
- }
- if ( !this.refObjects.IO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_RECEIVE_COMPLITE" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 3 Receive Complete Timeout" );
- this.OccurVehicleAlarm( 26 );
- return 0;
- }
- PIOClear();
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", true );
- Thread.Sleep( 1000 );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", false );
- return 0;
- }
- public int StartBatteryCharge()
- {
- #if SIMULATION
- this.PIOSensorOn();
- var pioTimeout = CastTo<int>.From<string>( sql.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- PIOClear();
- loggerPIO.I( $"Start Battery Charge PIO" );
- //if ( !this.iO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SENDABLE" ) )
- //{
- // PIOClear();
- // loggerPIO.E( "[Port] - 4 Ready Time Out" );
- // return 34;
- //}
- Thread.Sleep( 1000 );
- loggerPIO.E( "[Port] - 4 Ready On" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVABLE", true );
- loggerPIO.I( "[Vehicle] - 4 Receivable" );
- //if ( !this.iO.WaitChangeInputIO( true, 20000, "IN_PIO_SEND_RUN" ) )
- //{
- // PIOClear();
- // loggerPIO.E( "[Port] - 5 Sending Run Time Out" );
- // return 35;
- //}
- Thread.Sleep( 1000 );
- loggerPIO.I( "[Port] - 5 Sending Run On" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true );
- loggerPIO.I( "[Vehicle] - 5 Receive Run On" );
- this.VehicleStateProperty = eVehicleState.Charge;
- this.OnChargingStart?.Invoke();
- Thread.Sleep( 1000 );
- this.OnCharging?.Invoke();
- return 0;
- #else
- this.PIOSensorOn();
- LockUtils.Wait( 500 );
- var pioTimeout = Convert.ToInt32( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- PIOClear();
- loggerPIO.I( $"Start Battery Charge PIO" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SENDABLE" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 4 Ready Time Out" );
- return 34;
- }
- loggerPIO.E( "[Port] - 4 Ready On" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVABLE", true );
- loggerPIO.I( "[Vehicle] - 4 Receivable" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 5000, "IN_PIO_SEND_RUN" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 5 Sending Run Time Out" );
- return 35;
- }
- loggerPIO.I( "[Port] - 5 Sending Run On" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true );
- loggerPIO.I( "[Vehicle] - 5 Receive Run On" );
- this.VehicleStateProperty = eVehicleState.Charge;
- return 0;
- #endif
- }
- public int StopBatteryCharge()
- {
- #if SIMULATION
- loggerPIO.I( $"Stop Battery Charge PIO" );
- var pioTimeout = CastTo<int>.From<string>( sql.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- this.PIOClear();
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", true );
- loggerPIO.I( "[Vehicle] Receive Complete On" );
- //if ( !this.iO.WaitChangeInputIO( true, 20000, "IN_PIO_SEND_COMPLITE" ) )
- //{
- // this.iO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false );
- // loggerPIO.E( "[Port] IN_PIO_SEND_COMPLITE On Time Out" );
- // return 36;
- //}
- Thread.Sleep( 1000 );
- loggerPIO.I( "[Port] Send Complete On" );
- Thread.Sleep( 1000 );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false );
- this.OnChargingFull?.Invoke();
- this.PIOSensorOff();
- this.VehicleStateProperty = eVehicleState.Idle;
- return 0;
- #else
- loggerPIO.I( $"Stop Battery Charge PIO" );
- var pioTimeout = Convert.ToInt32( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- this.PIOClear();
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", true );
- loggerPIO.I( "[Vehicle] Receive Complete On" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 5000, "IN_PIO_SEND_COMPLITE" ) )
- {
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false );
- loggerPIO.E( "[Port] IN_PIO_SEND_COMPLITE On Time Out" );
- return 36;
- }
- loggerPIO.I( "[Port] Send Complete On" );
- Thread.Sleep( 1000 );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false );
- this.PIOSensorOff();
- this.OnChargingFull?.Invoke();
- this.VehicleStateProperty = eVehicleState.Idle;
- return 0;
- #endif
- }
- #endregion
- #region Check Method
- bool CheckObstacle()
- {
- if ( this.refObjects.IO.IsOff( "IN_OBSTRUCTION_DETECT_SAFETY" ) || this.refObjects.IO.IsOff( "IN_OBSTRUCTION_DETECT_ERROR" ) )
- {
- this.ObstacleStateProperty = eObstacleState.Abnormal;
- //this.OccurVehicleAlarm( 42 );
- }
- else if ( this.refObjects.IO.IsOff( "IN_OBSTRUCTION_DETECT_STOP" ) )
- {
- this.ObstacleStateProperty = eObstacleState.Blocked;
- }
- else if ( this.refObjects.IO.IsOff( "IN_OBSTRUCTION_DETECT_SLOW" ) )
- {
- this.ObstacleStateProperty = eObstacleState.Decelerate;
- }
- else
- {
- this.ObstacleStateProperty = eObstacleState.Normal;
- }
- this.refObjects.Drive.SetObstacleState( this.ObstacleStateProperty );
- return false;
- }
- void CheckIOState()
- {
- //이미 알람이면 체크 안함.
- if ( this.VehicleStateProperty == eVehicleState.Abnormal ) return;
- if ( this.refObjects.IO.IsConnectError ) return;
- //if ( this.iO.IsOn( "IN_EMS_SW" ) ) this.OccurVehicleAlarm( 28 );
- //if ( !this.iO.IsOn( "IN_CP_ON_SAFETY" ) ) this.OccurVehicleAlarm( 31 );
- //if ( !this.iO.IsOn( "IN_CP_ON_24V" ) ) this.OccurVehicleAlarm( 30 );
- //if ( !this.iO.IsOn( "IN_MC_ON" ) ) this.OccurVehicleAlarm( 29 );
- }
- #endregion
- #region Mechanical Method
- #region IO
- /// <summary>
- /// Out Put 을 On 이면 Sensor Off
- /// </summary>
- public void PIOSensorOn() => this.refObjects.IO.OutputOff( "OUT_PIO_SENSOR_ONOFF" );
- /// <summary>
- /// Out Put 을 Off 이면 Sensor On
- /// </summary>
- public void PIOSensorOff() => this.refObjects.IO.OutputOn( "OUT_PIO_SENSOR_ONOFF" );
- /// <summary>
- /// 충전 중일때 MTL PIO Bit 가 살아 있다
- /// 이걸 보고 판단 하자. 충전 단자 전진 상태임.
- /// </summary>
- /// <returns></returns>
- public bool CheckBatteryCharge()
- {
- this.PIOSensorOn();
- LockUtils.Wait( 500 );
- if ( this.BatteryChargeState || this.VehicleStateProperty == eVehicleState.Charge )
- {
- }
- //var ret = this.refObjects.IO.IsOn( "OUT_PIO_RECEIVABLE", false )
- // && this.refObjects.IO.IsOn( "OUT_PIO_RECEIVE_RUN", false )
- // && this.refObjects.IO.IsOn( "IN_PIO_SEND_RUN" );
- var ret = this.refObjects.IO.IsOn( "IN_PIO_SEND_RUN" );
- //this.PIOSensorOff();
- return ret;
- }
- #endregion
- #region Drive
- //public void DriveServoOff() => this.drive.ServoOff();
- //public void DriveServoOn() => this.drive.ServoOn();
- #endregion
- #region Conveyor
- public void ConveyorOff() => this.refObjects.Conveyor.OnOffConveyor( false );
- public int ConveyorLoad() => this.refObjects.Conveyor.ConveyorLoad();
- public int ConveyorUnload() => this.refObjects.Conveyor.ConveyorUnload();
- public int PIOAndLoad( string targetName )
- {
- #if SIMULATION
- PIOClear();
- loggerPIO.I( $"Start Load PIO - [{targetName}]" );
- this.OnPIOStart?.Invoke( true );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true );
- loggerPIO.I( "[Vehicle] - 4 Receive Run On" );
- Thread.Sleep( 1000 );//상대 IO 기다린다 생각.
- loggerPIO.E( "[Port] - 4 Ready On" );
- //Conveyor Start
- loggerPIO.I( "[Vehicle] - Conveyor Run" );
- this.OnConveyorStart?.Invoke( true );
- Thread.Sleep( 10000 );//Conveyor 구동
- this.OnCarrierDetected?.Invoke( true );
- PIOClear();
- Thread.Sleep( 1000 );
- this.OnConveyorStop?.Invoke( true );
- Thread.Sleep( 1000 );
- this.OnLoadComplete?.Invoke();
- #else
- loggerPIO.I( $"Start Load PIO - [{targetName}]" );
- this.PIOSensorOn();
- LockUtils.Wait( 500 );
- int result = 0;
- var pioTimeout = Convert.ToInt32( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- result = this.refObjects.Clamp.Unlock_Sync();
- if ( result != 0 )
- {
- this.OccurVehicleAlarm( result );
- return result;
- }
- if ( this.refObjects.Conveyor.IsInverterError() )
- return 16;
- if ( this.refObjects.Conveyor.IsDetectedCenter() )
- {
- this.OnFailReport?.Invoke( eFailCode.Load_VehicleHasCarrier );
- return 0;
- }
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 40 * ConstUtils.ONE_SECOND, "IN_LIFTER_POSITION_DETECT" ) )
- {
- loggerPIO.E( "[Port] - Lift Position Check Error" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.LoadPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
- return 0; //14
- }
- //if ( !this.refObjects.Conveyor.IsLifterPositinCheck() )
- //{
- // loggerPIO.E( "[Port] - Lift Position Check Error" );
- // this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
- // return 0; //14
- //}
- //Todo: Sensor Setting 이 후 주석 풀기.
- //if ( !this.IsLifterDuplication() )
- //{
- // this.OnFailReport?.Invoke( eFailCode.Load_PortHasNotCarrier );
- // return 0;
- //}
- PIOClear();
- this.OnPIOStart?.Invoke( true );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVABLE", true );
- loggerPIO.I( "[Vehicle] - 4 Receivable" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 20 * ConstUtils.ONE_SECOND, "IN_PIO_SENDABLE" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 4 Ready Time Out" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.LoadPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
- return 0;
- }
- loggerPIO.E( "[Port] - 4 Ready On" );
- //this.conveyor.SetConveyorSpeed( true );
- this.refObjects.Conveyor.OnOffConveyor( true, true );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECEIVE_RUN", true, 1000 ); //1Sec 이후 On
- loggerPIO.I( "[Vehicle] - Conveyor Run" );
- this.OnConveyorStart?.Invoke( true );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SEND_RUN" ) )
- {
- this.refObjects.Conveyor.OnOffConveyor( false, true );
- PIOClear();
- loggerPIO.E( "[Port] - 5 Sending Run Time Out" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.LoadPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
- return 0;
- }
- loggerPIO.I( "[Port] - 5 Sending Run On" );
- bool isStartDetected = false;
- var sTime = SwUtils.CurrentTimeMillis;
- while ( true )
- {
- LockUtils.Wait( 10 );
- if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) )
- {
- PIOClear();
- this.refObjects.Conveyor.OnOffConveyor( false, true );
- loggerPIO.E( "[Vehicle] Conveyor Wait Time Out" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.LoadPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.LoadPIOInterlockTimeout );
- if ( this.refObjects.Conveyor.IsDetectedLoadStart() ) // 감지가 시작 되었으면 이동중 Error 로 판단 설비를 정지 상태로
- return 10; //Conveyor Moving Timeout
- else
- return 0;
- }
- if ( this.refObjects.Conveyor.IsDetectedLoadStart() && !isStartDetected )
- isStartDetected = true;
- if ( !this.refObjects.Conveyor.IsDetectedLoadStart() && isStartDetected ) { }
- //this.conveyor.SetConveyorSpeed( false );
- if ( this.refObjects.Conveyor.IsDetectedLoadStop() ) break;
- if ( this.refObjects.Conveyor.IsPIOInterLockOn() )
- {
- PIOClear();
- this.refObjects.Conveyor.OnOffConveyor( false ); //Stop
- loggerPIO.E( "[Port] PIO InterLock On " );
- return 19; //
- }
- }
- if ( this.refObjects.Conveyor.IsDetectedCenter() )
- this.OnCarrierDetected?.Invoke( true );
- this.refObjects.Conveyor.OnOffConveyor( false ); //Stop
- PIOClear();
- this.OnConveyorStop?.Invoke( true );
- loggerPIO.I( "[Vehicle] Conveyor Stop" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", true );
- loggerPIO.I( "[Vehicle] Receive Complete On" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, pioTimeout, "IN_PIO_SEND_COMPLITE" ) )
- {
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false );
- loggerPIO.E( "[Port] IN_PIO_SEND_COMPLITE On Time Out" );
- }
- loggerPIO.I( "[Port] Send Complete On" );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_RECIVE_COMPLITE", false, 1000 );
- loggerPIO.I( $"End Load PIO - [{targetName}]" );
- result = this.refObjects.Clamp.Lock_Sync();
- if ( result != 0 )
- {
- this.OccurVehicleAlarm( result );
- return result;
- }
- #endif
- return 0;
- }
- public int PIOAndUnload( string targetName )
- {
- #if SIMULATION
- PIOClear();
- loggerPIO.I( $"Start Unload PIO - [{targetName}]" );
- this.OnPIOStart?.Invoke( false );
- Thread.Sleep( 1000 );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_READY", true );
- loggerPIO.I( "[Vehicle] - 1 Ready On" );
- Thread.Sleep( 1000 );
- this.OnConveyorStart?.Invoke( false );
- Thread.Sleep( 10000 );
- this.refObjects.Conveyor.OnOffConveyor( false ); //Stop
- this.OnConveyorStop?.Invoke( false );
- PIOClear();
- Thread.Sleep( 1000 );
- this.OnUnloadComplete?.Invoke();
- #else
- loggerPIO.E( $"Start Unload PIO -[{targetName}]" );
- this.PIOSensorOn();
- LockUtils.Wait( 500 );
- int result = 0;
- var pioTimeout = Convert.ToInt32( this.refObjects.Sqlite.ConfigDal.GetById( ConstString.PIOTimeOut ).Value );
- if ( this.refObjects.Conveyor.IsInverterError() )
- return 16;
- //if ( this.refObjects.Conveyor.IsLifterDuplication() )
- //{
- // this.OnFailReport?.Invoke( eFailCode.Unload_PortHasCarrier );
- // return 0;
- //}
- if ( !this.refObjects.Conveyor.IsDetectedCenter() )
- {
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.Unload_VehicleHasNotCarrier );
- //this.OnFailReport?.Invoke( eFailCode.Unload_VehicleHasNotCarrier );
- return 0;
- }
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 40 * ConstUtils.ONE_SECOND, "IN_LIFTER_POSITION_DETECT" ) )
- {
- loggerPIO.E( "[Port] - Lift Position Check Error" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.UnlaodPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
- return 0;
- }
- //if ( !this.refObjects.Conveyor.IsLifterPositinCheck() )
- //{
- // loggerPIO.E( "[Port] - Lift Position Check Error" );
- // this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout ); //Unloading Fail Code 를 Time Out 으로 하자. 정의 된 코드 없음.
- // return 0; //13 -> Alarm Code 보고 없음. 경알람 상태 이므로 한번 보고 후 정상 동작
- //}
- PIOClear();
- this.OnPIOStart?.Invoke( false );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 20 * ConstUtils.ONE_SECOND, "IN_PIO_READY" ) )
- {
- loggerPIO.E( "[Port] - 1 Ready not On" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.UnlaodPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
- return 0;
- }
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_READY", true );
- loggerPIO.I( "[Vehicle] - 1 Ready On" );
- if ( !this.refObjects.IO.WaitChangeInputIO( true, 10 * ConstUtils.ONE_SECOND, "IN_PIO_RECEIVE_RUN" ) )
- {
- PIOClear();
- loggerPIO.E( "[Port] - 2 Receive CV Run Timeout" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.UnlaodPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
- return 0;
- }
- loggerPIO.E( "[Port] - 2 Receive CV Run On" );
- result = this.refObjects.Clamp.Unlock_Sync();
- if ( result != 0 )
- {
- this.OccurVehicleAlarm( result );
- return result;
- }
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SENDING_RUN", true );
- loggerPIO.I( "[Vehicle] - 2 Send Run On" );
- //this.conveyor.SetConveyorSpeed( true );
- this.refObjects.Conveyor.OnOffConveyor( true );
- this.OnConveyorStart?.Invoke( false );
- var sTime = SwUtils.CurrentTimeMillis;
- while ( true )
- {
- if ( SwUtils.Gt( sTime, 20 * ConstUtils.ONE_SECOND ) )
- {
- PIOClear();
- this.refObjects.Conveyor.OnOffConveyor( false, true );
- loggerPIO.E( "[Port] Conveyor Wait Time Out" );
- TimerUtils.Once( 1000, this.OnFailReport, eFailCode.UnlaodPIOInterlockTimeout );
- //this.OnFailReport?.Invoke( eFailCode.UnlaodPIOInterlockTimeout );
- if ( this.refObjects.Conveyor.IsDetectedLoadStart() || this.refObjects.Conveyor.IsDetectedCenter() ) //중간에 걸려 있다고 생각해서 알람 처리.
- return 12; //Conveyor Moving Timeout
- else
- {
- if ( this.refObjects.Conveyor.IsDetectedCenter() ) //Time Out 후 아직 Tray 가 있으면 다시 Clamp Lock.
- {
- result = this.refObjects.Clamp.Unlock_Sync();
- if ( result != 0 )
- {
- this.OccurVehicleAlarm( result );
- return result;
- }
- }
- else
- return 0;
- }
- }
- if ( !this.refObjects.Conveyor.IsDetectedLoadStart() && !this.refObjects.Conveyor.IsDetectedCenter() )
- {
- if ( this.refObjects.IO.IsOn( "IN_PIO_RECEIVE_COMPLITE" ) )
- {
- loggerPIO.I( "[Port] - 3 Receive Complete On" );
- break;
- }
- }
- }
- if ( !this.refObjects.Conveyor.IsDetectedCenter() )
- this.OnCarrierDetected?.Invoke( false );
- this.refObjects.Conveyor.OnOffConveyor( false ); //Stop
- this.OnConveyorStop?.Invoke( false );
- PIOClear();
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", true );
- Thread.Sleep( 1000 );
- this.refObjects.IO.WriteOutputIO( "OUT_PIO_SEND_COMPLITE", false );
- loggerPIO.I( "[Vehicle] - 3 Send Complete OnOff" );
- #endif
- loggerPIO.I( $"End Unload PIO - [{targetName}]" );
- return 0;
- }
- void PIOClear()
- {
- 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" };
- pio.FwEach( x => { this.refObjects.IO.OutputOff( x ); } );
- }
- #endregion
- #endregion
- #region Help Method
- Task taskHostConnection = null;
- /// <summary>
- /// Move 이후 OCS 연결을 확인 후 Disconnected 상태이면 5분 상태 확인 후 Alarm 발생.
- /// </summary>
- void CheckOCSConnectionState()
- {
- if ( this.taskHostConnection != null )
- return;
- if ( refObjects.HostManager.IsConnected )
- return;
- this.taskHostConnection = new Task( () =>
- {
- long sTime = SwUtils.CurrentTimeMillis;
- while ( !refObjects.HostManager.IsConnected )
- {
- LockUtils.Wait( 100 );
- if ( SwUtils.Gt( sTime, 30 * ConstUtils.ONE_SECOND ) )
- {
- OccurVehicleAlarm( 43 );
- break;
- }
- }
- } );
- this.taskHostConnection = null;
- }
- void BatteryChargeStateLED( double percent )
- {
- if ( percent > 60 )
- {
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_00", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_01", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_02", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_03", true );
- }
- else if ( percent > 45 )
- {
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_00", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_01", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_02", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_03", false );
- }
- else if ( percent > 30 )
- {
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_00", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_01", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_02", false );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_03", false );
- }
- else
- {
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_00", true );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_01", false );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_02", false );
- this.refObjects.IO.WriteOutputIO( "OUT_BATTERY_LED_03", false );
- }
- }
- /// <summary>
- /// 현재 Point 가 변경될때 장애물 감지 센서의 패턴을 변경한다.
- /// </summary>
- /// <param name="v"></param>
- private void ObstaclePatternChange( int v )
- {
- if ( !RouteManager.Instance.Segments.Any( s => s.ID == v ) )
- {
- logger.E( "Current Tag Not Exist RouteManager Point List" );
- return;
- }
- //Todo: 현재 Segment ID 를 가져 와서 변경하는 방식으로 변경 필요.
- var obstacle = RouteManager.Instance.Obstacles.Where( o => o.segmentID == v ).Single();
- this.ChgObstacleDetectPattern( obstacle.fieldset );
- logger.D( $"[Obstacle Pattern Chg] - {obstacle.fieldset}" );
- }
- /// <summary>
- /// 현재 좌표 값이 등록된 Route 에 맞는 위치인지 확인한다.
- /// 판단 기준은 Route 에 Tolerance 범위를 사용.
- /// </summary>
- /// <param name="route"></param>
- /// <param name="currentPosition"></param>
- /// <returns></returns>
- bool CorrectPosition( Route route, double currentPosition )
- {
- var rScale = route.ScaleValue;
- var rTolerance = route.ScaleTolerance;
- var result = currentPosition - rScale;
- if ( rTolerance < Math.Abs( result ) )
- return false;
- return true;
- }
- /// <summary>
- /// if no is zero, Laser Off
- /// bit Off, On, On, On,On Area1
- /// </summary>
- /// <param name="no"> 0 == Off Laser</param>
- /// <returns></returns>
- public bool ChgObstacleDetectPattern( int no )
- {
- var bitArray = BitUtils.ChgBitArray( no );
- int bitIndex = 0;
- this.obstacleBitList.ForEach( b =>
- {
- if ( bitArray[bitIndex] )
- this.refObjects.IO.OutputOff( b );
- else
- this.refObjects.IO.OutputOn( b );
- bitIndex++;
- } );
- ObstaclePattern = no;
- return true;
- }
- public int GetObstacleDetectPattern()
- {
- int bitIndex = 0;
- BitArray bitArray = new BitArray( this.obstacleBitList.Count );
- this.obstacleBitList.ForEach( b =>
- {
- if ( this.refObjects.IO.IsOn( b, false ) )
- bitArray.Set( bitIndex, false );
- else
- bitArray.Set( bitIndex, true );
- bitIndex++;
- } );
- return BitUtils.ChgInt32( bitArray );
- }
- /// <summary>
- /// Vehicle 이동 및 동작 중 Alarm 발생 시 처리
- /// </summary>
- /// <param name="alarmID"></param>
- public void OccurVehicleAlarm( int alarmID )
- {
- var alarm = refObjects.Alarms.Where( x => x.AlarmId == alarmID ).FirstOrDefault();
- if ( alarm != null )
- {
- if ( alarm.Level == eAlarmLevel.Warn )
- {
- HisAlarm hisAlarm = new HisAlarm();
- hisAlarm.AlarmId = alarmID;
- hisAlarm.Text = alarm.Name + " - " + alarm.Text;
- hisAlarm.Solution = alarm.Solution;
- var clone = ObjectCopyUtils.DeepClone<Alarm>( alarm );
- this.refObjects.Sqlite.HisAlarmDAL.Insert( hisAlarm );
- return;
- }
- }
- this.MachineMode = eMachineMode.LocalMode;
- this.VehicleStateProperty = eVehicleState.Abnormal;
- this.ConveyorOff();
- this.refObjects.AutoManager.ProcessAlarm( alarmID );
- }
- public void SetObstaclePattern( ObstacleControlEventArgs.eControlKind state, int value )
- {
- if ( state == ObstacleControlEventArgs.eControlKind.DRIVE )
- {
- this.ObstacleDrive = value;
- ChgObstacleDetectPattern( this.ObstacleDrive );
- }
- else if ( state == ObstacleControlEventArgs.eControlKind.CURVE )
- {
- this.ObstacleCurve = value;
- ChgObstacleDetectPattern( this.ObstacleCurve );
- }
- else
- return;
- }
- public eSteeringState GetESteeringState() => this.refObjects.Steering.GetSteeringState();
- #endregion
- #region Event Subscribe
- private void BMUManager_OnDisconnect( string obj )
- {
- this.BatteryIsConnect = false;
- this.OccurVehicleAlarm( 32 );
- }
- private void BMUManager_OnConnect( string obj )
- {
- this.BatteryIsConnect = true;
- //ReqCurrentPos();
- }
- private void BMUManager_OnFirstColtd( List<ReceivedData> obj )
- {
- }
- private void BMUManager_OnChangedReceivedData( Serial.DataModel.ReceivedData obj )
- {
- var kind = CastTo<eDataKind>.From<Enum>( obj.DataKind );
- switch ( kind )
- {
- case eDataKind.Voltage:
- this.BatteryVoltage = (double)obj.Value;
- break;
- case eDataKind.Current:
- this.BatteryCurrent = (double)obj.Value;
- if ( BatteryCurrent > 3 )
- this.BatteryChargeState = true;
- else
- this.BatteryChargeState = false;
- break;
- case eDataKind.BatteryState:
- this.BatteryState = (double)obj.Value;
- break;
- case eDataKind.ChargeCompleteTime:
- this.BatteryChargeTime = (double)obj.Value;
- break;
- case eDataKind.DisChargeCompleteTime:
- this.BatteryDisChargeTime = (double)obj.Value;
- break;
- case eDataKind.SOC:
- this.BatteryStateOfCharge = (double)obj.Value;
- break;
- case eDataKind.SOH:
- this.BatteryStateOfHealth = (double)obj.Value;
- break;
- case eDataKind.ResidualCapacity:
- this.BatteryCapacity = (double)obj.Value;
- break;
- case eDataKind.ResidualEnergy:
- this.BatteryEnergy = (double)obj.Value;
- break;
- case eDataKind.Temperature:
- this.BatteryTemperature = (double)obj.Value;
- break;
- default:
- break;
- }
- }
- private void AutoManager_OnOperationModeChanged( eOperatationMode obj )
- {
- this.refObjects.Drive.SetDriveOperationMode( obj );
- }
- private void ZmqManager_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e )
- {
- var property = sender.GetType().GetProperty( e.PropertyName );
- var newValue = property.GetValue( sender, null );
- switch ( e.PropertyName )
- {
- case "SegmentID":
- {
- var v = CastTo<int>.From<object>( newValue );
- this.ObstaclePatternChange( v );
- }
- break;
- case "RequestSteering":
- {
- var v = CastTo<eSteeringState>.From<object>( newValue );
- switch ( v )
- {
- case eSteeringState.None:
- break;
- case eSteeringState.Left:
- this.refObjects.Steering.ControlSteering( true );
- break;
- case eSteeringState.Right:
- this.refObjects.Steering.ControlSteering();
- break;
- default:
- break;
- }
- logger.D( $"[Request Steering] - {v}" );
- }
- break;
- case "CurrentPointNo":
- {
- var v = CastTo<int>.From<object>( newValue );
- logger.D( $"{this.CurrentTag} -> {v}" );
- this.CurrentTag = v;
- }
- break;
- case "RearDriveState":
- {
- var v = CastTo<DriveState>.From<object>( newValue );
- this.RearDriveState = v;
- }
- break;
- case "FrontLoadFactor":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.FrontLoadFactor = v;
- this.FrontTorque = Math.Truncate( ( ( v * 1.9 ) / 1000 ) * 100 ) / 100;
- }
- break;
- case "FrontRPM":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.FrontRpm = v;
- var ll = ( ( ( ( v / 60 ) * ( 2 * Math.PI ) ) * 0.06 ) / 10 );
- this.FrontSpeed = Math.Truncate( ll * 100 ) / 100;
- }
- break;
- case "RearLoadFactor":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.RearLoadFactor = v;
- this.RearTorque = Math.Truncate( ( ( v * 1.9 ) / 1000 ) * 100 ) / 100;
- }
- break;
- case "RearRPM":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.RearRpm = v;
- var ll = ( ( ( ( v / 60 ) * ( 2 * Math.PI ) ) * 0.06 ) / 10 );
- this.RearSpeed = Math.Truncate( ll * 100 ) / 100;
- }
- break;
- case "AutoReadyState":
- {
- var v = CastTo<eVehicleAutoReadyState>.From<object>(newValue);
- this.AutoReadyState = v;
- }
- break;
- case "LinearSpeed":
- {
- this.LinearSpeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "CurveSpeed":
- {
- this.CurveSpeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "JogSPeed":
- {
- this.JogSPeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "AccelSpeed":
- {
- this.AccelSpeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "DecelSpeed":
- {
- this.DecelSpeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "CreepSpeed":
- {
- this.CreepSpeed = CastTo<double>.From<object>(newValue);
- }
- break;
- case "CreepDistance":
- {
- this.CreepDistance = CastTo<double>.From<object>(newValue);
- }
- break;
- default:
- break;
- }
- }
- private void Motion_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e )
- {
- var property = sender.GetType().GetProperty( e.PropertyName );
- var newValue = property.GetValue( sender, null );
- switch ( e.PropertyName )
- {
- case "CurrentPos":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.CurrentPosition = v;
- }
- break;
- //case "CurrentTag":
- // {
- // var v = CastTo<int>.From<object>( newValue );
- // logger.D( $"{this.CurrentTag} -> {v}" );
- // this.CurrentTag = v;
- // }
- // break;
- case "CurrentSpeed":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.CurrentSpeed = v;
- }
- break;
- case "CurrentTorque":
- {
- var v = CastTo<double>.From<object>( newValue );
- this.CurrentTorque = v;
- }
- break;
- case "ReqSteeringState":
- //{
- // var v = CastTo<eSteeringState>.From<object>( newValue );
- // switch ( v )
- // {
- // case eSteeringState.None:
- // break;
- // case eSteeringState.Left:
- // this.refObjects.Steering.ControlSteering( true );
- // break;
- // case eSteeringState.Right:
- // this.refObjects.Steering.ControlSteering();
- // break;
- // default:
- // break;
- // }
- //}
- break;
- case "DriveServoState":
- {
- var v = CastTo<eDriveServoState>.From<object>( newValue );
- if ( v == eDriveServoState.ServoOn )
- this.refObjects.IO.OutputOn( "OUT_DRIVE_BRAKE_OFF" );
- else
- this.refObjects.IO.OutputOff( "OUT_DRIVE_BRAKE_OFF" );
- }
- break;
- case "FrontDriveState":
- {
- var v = CastTo<DriveState>.From<object>( newValue );
- this.FrontDriveState = v;
- }
- break;
- case "RearDriveState":
- {
- var v = CastTo<DriveState>.From<object>( newValue );
- this.RearDriveState = v;
- }
- break;
-
- default:
- break;
- }
- }
- private void Steering_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e )
- {
- var property = sender.GetType().GetProperty( e.PropertyName );
- var newValue = property.GetValue( sender, null );
- //Todo: 나중에 Test 하자
- //var ownPropperty = this.GetType().GetProperty(e.PropertyName);
- if ( e.PropertyName.Equals( "SteeringState" ) )
- {
- var v = CastTo<eSteeringState>.From<object>( newValue );
- this.SteeringState = v;
- logger.D( $"steering - {v}" );
- }
- }
- private void Clamp_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e )
- {
- var property = sender.GetType().GetProperty( e.PropertyName );
- var newValue = property.GetValue( sender, null );
- if ( e.PropertyName.Equals( "ClampState" ) )
- {
- var v = CastTo<eClampState>.From<object>( newValue );
- this.ClampState = v;
- }
- }
- private void IO_OnChangedIO( BitBlock bit )
- {
- switch ( bit.Tag )
- {
- case "IN_CV_DETECT_01":
- this.IsContain = bit.IsBitOn;
- this.refObjects.ZmqManager.Publish( "Contain", this.IsContain.ToString() );
- break;
- case "IN_MC_ON":
- if ( bit.IsBitOn )
- {
- if ( !this.refObjects.IO.IsOn( "IN_EMS_SW" ) && this.refObjects.IO.IsOn( "IN_CP_ON_SAFETY" ) && this.refObjects.IO.IsOn( "IN_CP_ON_24V" ) )
- this.VehicleStateProperty = eVehicleState.Idle;
- }
- else
- {
- if ( this.ObstacleStateProperty == eObstacleState.Abnormal )
- this.OccurVehicleAlarm( 42 );
- else
- this.OccurVehicleAlarm( 29 );
- }
- break;
- case "IN_EMS_SW":
- if ( bit.IsBitOn )
- this.OccurVehicleAlarm( 28 );
- break;
- case "IN_CP_ON_SAFETY":
- if ( !bit.IsBitOn )
- this.OccurVehicleAlarm( 31 );
- break;
- case "IN_CP_ON_24V":
- if ( !bit.IsBitOn )
- this.OccurVehicleAlarm( 30 );
- break;
- case "IN_OBSTRUCTION_DETECT_ERROR":
- case "IN_OBSTRUCTION_DETECT_SAFETY":
- case "IN_OBSTRUCTION_DETECT_STOP":
- case "IN_OBSTRUCTION_DETECT_SLOW":
- CheckObstacle();
- break;
- case "IN_BUMPER_DETECT":
- if ( bit.IsBitOn )
- this.refObjects.ZmqManager.SetSafetyBumper();
- break;
- default:
- break;
- }
- }
- private void Steering_OnSteeringError( object sender, int e )
- {
- if ( e != 0 )
- {
- logger.E( $"[Steering] - Control Error {e}" );
- this.OccurVehicleAlarm( e );
- }
- else
- {
- var msg = new DriveControlEventArgs()
- {
- EventDir = DriveControlEventArgs.eEventDir.ToFront,
- ControlKind = DriveControlEventArgs.eControlKind.Steering,
- Result = FluentResults.Results.Ok<DriveControlEventArgs.eMoveDir>( DriveControlEventArgs.eMoveDir.LEFT ),
- };
- this.eventAggregator.GetEvent<DriveControlPubSubEvent>().Publish( msg );
- }
- }
- #endregion
- }
- }
|