Class LocalProjectService
- Namespace
- Hi.MachiningProcs
- Assembly
- HiNc.dll
Root(Local) project service. Apply absolute file path.
public class LocalProjectService : IProjectService, IMachiningProjectGetter, IMachiningService, IGetMachiningEquipment, IStepPropertyAccessHost, IDisposable
- Inheritance
-
LocalProjectService
- Implements
- Inherited Members
- Extension Methods
Remarks
LocalProjectService handles the runtime data and cache generally not requires configuration IO. Compare to MachiningProject, LocalProjectService also handles events that does not reset on the MachiningProject been reloaded.
Constructors
LocalProjectService(ILogger<LocalProjectService>)
Ctor.
public LocalProjectService(ILogger<LocalProjectService> logger = null)
Parameters
loggerILogger<LocalProjectService>Optional logger instance.
Properties
ActiveNcRunner
Gets the active NC runner based on EnableSoftNcRunner.
public IControlRunner ActiveNcRunner { get; }
Property Value
BaseDirectory
Gets the project base directory (relative-path root).
public string BaseDirectory { get; }
Property Value
BoundSelectorHost
Gets the bound selector host for managing selection boundaries.
public BoundSelectorHost BoundSelectorHost { get; }
Property Value
ClRunner
Gets the NX-CL (CLSF) control runner of the project
(NxClRunner); null when there is no project.
public IControlRunner ClRunner { get; }
Property Value
ClStrip
Gets the cutter location strip containing the machining steps.
public ClStrip ClStrip { get; }
Property Value
CsvRunner
Gets the CSV control runner — the CSV suit's pipeline
(GeneralCsvRunner); null when there is no project.
public IControlRunner CsvRunner { get; }
Property Value
DictionaryColorGuide
Gets the color guide for dictionary-based coloring.
public DictionaryColorGuide DictionaryColorGuide { get; }
Property Value
EnablePauseOnFailure
Gets or sets whether to pause execution on failure.
public bool EnablePauseOnFailure { get; set; }
Property Value
EnableSoftNcRunner
Switches between SoftNcRunner and the legacy
HardNcRunner. Default true (2026-07-17):
SoftNcRunner is the flagship NC pipeline; set
false to fall back to HardNcRunner for the
features that still depend on it (e.g. NcOptProc
optimization reads NcLines).
Will be removed when HardNcRunner is fully replaced.
public bool EnableSoftNcRunner { get; set; }
Property Value
EnableStrokeLimitCheck
Gets or sets whether stroke limit checking is enabled.
public bool EnableStrokeLimitCheck { get; set; }
Property Value
Fixture
Gets or sets the fixture.
public Fixture Fixture { get; set; }
Property Value
Global
global variable for SessionShell. Not save on XML.
public Dictionary<object, object> Global { get; set; }
Property Value
InspectingKey
Gets or sets the current inspecting key for visualization. When set, updates the inspecting quantity function.
public string InspectingKey { get; set; }
Property Value
InspectingQuantityFunc
Gets the function that retrieves the quantity value for the current inspecting key.
public Func<MachiningStep, double?> InspectingQuantityFunc { get; }
Property Value
IsCollisionDetectionEnabled
Gets whether collision detection is currently enabled.
public bool IsCollisionDetectionEnabled { get; }
Property Value
LastMillingParaTrainResult
Snapshot of the most recent TrainMillingPara(SampleFlag, bool, double, string, CancellationToken, ICuttingPara, IProgress<IMessage>) /
ReTrainMillingPara(SampleFlag, double, string, CancellationToken, IProgress<IMessage>) outcome — sampleFlags, correlation R,
filtered sample count, output file and the built parameter's XML — so a
caller (e.g. the webservice) can read the training result without
re-opening the output .mp file. Service lifetime, last-wins;
null until the first training call completes. Deliberately not cleared
by ResetRuntime(IProgress<IMessage>) so the result stays readable after a
post-run reset.
public MillingParaTrainResult LastMillingParaTrainResult { get; }
Property Value
Logger
Gets the logger instance for this service.
public ILogger<LocalProjectService> Logger { get; }
Property Value
MachiningActRunner
Gets the machining act runner responsible for executing machining operations.
public MachiningActRunner MachiningActRunner { get; }
Property Value
MachiningChain
Gets or sets the machining chain.
public IMachiningChain MachiningChain { get; set; }
Property Value
MachiningChainFile
Gets or sets the file path of the solid machining chain. This is used for XML serialization and file management.
public string MachiningChainFile { get; set; }
Property Value
MachiningEquipment
Gets or sets the machining equipment used for milling. Updates related components when changed.
public MachiningEquipment MachiningEquipment { get; set; }
Property Value
MachiningMotionResolution
Gets or sets the machining motion resolution strategy (project-level; backed by MachiningActRunner).
public IMachiningMotionResolution MachiningMotionResolution { get; set; }
Property Value
MachiningProject
Gets or sets the machining project instance.
public MachiningProject MachiningProject { get; set; }
Property Value
MachiningProjectPath
public string MachiningProjectPath { get; set; }
Property Value
MachiningResolution_mm
Gets the machining resolution (mm) — the act-runner value, or the workpiece bottom resolution when unset. Set via SetMachiningResolution_mm(double, IProgress<IMessage>) (have-both: the caller injects the message host).
public double MachiningResolution_mm { get; }
Property Value
MachiningSession
Gets the current machining session.
public MachiningSession MachiningSession { get; set; }
Property Value
MachiningTool
Gets or sets the machining tool.
public IMachiningTool MachiningTool { get; set; }
Property Value
MachiningToolHouse
Gets or sets the machining tool house containing tool configurations.
public MachiningToolHouse MachiningToolHouse { get; set; }
Property Value
MachiningToolHouseFile
Gets or sets the file path to the milling tool house configuration.
public string MachiningToolHouseFile { get; set; }
Property Value
MillingStepLuggageReader
Gets the reader for accessing milling step luggage data.
public ParallelBulkReader<MillingStepLuggage> MillingStepLuggageReader { get; }
Property Value
NcDiagnosticProgress
NC-pipeline diagnostic sink on the IMessage channel — sibling of
StepDiagnosticProgress. Stable for the service lifetime (created in the ctor,
only Cleared on reset, never swapped per session).
public NcDiagnosticProgress NcDiagnosticProgress { get; }
Property Value
NcManipulationDiagnosticProgress
Gets the NC-manipulation diagnostic sink — the second diagnostic home, for operations that rework an already-played NC/CL program (writeback conversion, NC optimization) as opposed to the play-time pipeline diagnostics in NcDiagnosticProgress. Keeping the two scenarios in separate homes lets a play reset clear run diagnostics without discarding manipulation results, and vice versa; each manipulation run clears this home at its start so it always holds the latest run.
public NcDiagnosticProgress NcManipulationDiagnosticProgress { get; }
Property Value
NcOptProc
Gets the NC optimization processor for optimizing NC programs.
public NcOptProc NcOptProc { get; }
Property Value
NcRunner
Gets the legacy NC runner.
public HardNcRunner NcRunner { get; }
Property Value
PacePlayer
Gets the pace player for controlling execution pace of milling operations.
public PacePlayer PacePlayer { get; }
Property Value
ProjectDirectory
Gets the directory containing the machining project.
public string ProjectDirectory { get; }
Property Value
ScriptOptions
Project-level Roslyn script options for session script execution. Initialized from DefaultScriptOptions.
public ScriptOptions ScriptOptions { get; set; }
Property Value
SessionShell
Gets the shell API for the active session. Created at BeginSession(),
nulled at EndSession(); null outside a session — its lifetime is
unified with MachiningSession, so a non-null instance always implies an
active session.
public SessionShell SessionShell { get; }
Property Value
ShellProgress
Session-level routine / lifecycle message sink on the IMessage channel
(cache reset, file progress, …). Owned by MachiningSession (truly
session-scoped); null outside a session. Use null-safely.
public ShellProgress ShellProgress { get; }
Property Value
SoftNcRunner
Facade over the active suit's NC pipeline
(MachiningProject.NcRunnerSuit.SoftNcRunner). The getter is null-safe
(returns null when there is no project/suit). The setter is the single
rewiring entry point: it assigns the suit's runner and re-binds everything
that depends on it (proxy hosts, kinematics provider, session script
dictionaries, and the per-session NcRunnerSessionState).
public SoftNcRunner SoftNcRunner { get; set; }
Property Value
StepDiagnosticProgress
Step-anchored message sink on the IMessage channel, threaded through the runner / act-processing chain.
public StepDiagnosticProgress StepDiagnosticProgress { get; }
Property Value
StepPropertyAccessDictionary
Gets the dictionary mapping property keys to their access methods.
public ConcurrentDictionary<string, PropertyAccess<MachiningStep>> StepPropertyAccessDictionary { get; }
Property Value
TimeMapping
Gets or sets the time mapping for synchronizing different time-based data streams.
public TimeMapping TimeMapping { get; set; }
Property Value
Workpiece
Gets or sets the workpiece to be machined. Ensures proper initialization of workpiece properties.
public Workpiece Workpiece { get; set; }
Property Value
WorkpieceService
Gets the workpiece runtime service.
public WorkpieceService WorkpieceService { get; }
Property Value
Methods
Act(IAct, ISentenceCarrier, CancellationToken?)
Executes an act and collects all results.
public void Act(IAct act, ISentenceCarrier sourceCommand = null, CancellationToken? cancellationToken = null)
Parameters
actIActThe act to execute.
sourceCommandISentenceCarrierThe source command that triggered the act.
cancellationTokenCancellationToken?Cancellation token to cancel the operation.
BeginControlRunner()
Prepares the control runner for a play session by initializing the workpiece meshed geometry (when not already initialized), reporting progress through ShellProgress.
public void BeginControlRunner()
BeginSession()
Initiate a simulation session. Clear the state from previous session (if existed).
public void BeginSession()
CheckStrokeLimitOnStep()
Checks stroke limit at the current MC position. Uses IStrokeLimitConfig when EnableSoftNcRunner is active, otherwise falls back to CheckStrokeLimit(DVec3d, IProgress<IMessage>).
public bool CheckStrokeLimitOnStep()
Returns
- bool
True if within limits or no limits configured.
CloseProject()
Closes the current project.
public void CloseProject()
ConvertClToNcFiles(string, IProgress<IMessage>)
Converts the CLSF play of the current session into Fanuc NC files
(writeback synthesis — MSYS tilt becomes G68.2, RTCP becomes
G43.4). Play a CL file on an XYZABC machine chain first, then
convert; see ConvertClToNcFiles(string, string, IProgress<IMessage>).
public IReadOnlyList<string> ConvertClToNcFiles(string relNcFileTemplate = "Output/[NcName].nc", IProgress<IMessage> messageProgress = null)
Parameters
relNcFileTemplatestringOutput path template;
[NcName]is replaced by the source file name.messageProgressIProgress<IMessage>Optional message sink for lifecycle reporting.
Returns
- IReadOnlyList<string>
Written NC file paths, relative to the project base directory.
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
Dispose(bool)
protected virtual void Dispose(bool disposing)
Parameters
disposingbool
EnableCollisionDetection(bool, IProgress<IMessage>)
Enables or disables collision detection. When enabling, prepares the
collidable items; when disabling, resets collision flags. Progress is
reported to the injected messageProgress.
public void EnableCollisionDetection(bool value, IProgress<IMessage> messageProgress = null)
Parameters
valueboolWhether collision detection should be enabled.
messageProgressIProgress<IMessage>Sink-agnostic message host for progress reporting.
EndSession()
Ends the current machining session and releases associated resources.
public void EndSession()
FixedPace(double, double)
Creates a fixed machining motion resolution with the specified linear (mm) and rotary (deg) resolutions.
public FixedMachiningMotionResolution FixedPace(double linearResolution_mm, double rotaryResolution_deg)
Parameters
linearResolution_mmdoubleLinear resolution in millimeters.
rotaryResolution_degdoubleRotary resolution in degrees.
Returns
GetInspectingKeyPresentName(StringLocalizer)
Gets the localized presentation name for the current inspecting key.
public string GetInspectingKeyPresentName(StringLocalizer stringLocalizer)
Parameters
stringLocalizerStringLocalizerThe string localizer to use for localization
Returns
- string
The localized presentation name
GetLocalProjectService()
Get Local Project Service as base-service.
public LocalProjectService GetLocalProjectService()
Returns
- LocalProjectService
Local Project Service
GetMachiningProject()
Gets the MachiningProject instance.
public MachiningProject GetMachiningProject()
Returns
- MachiningProject
The MachiningProject instance.
GetMillingEquipment()
Get MachiningEquipment.
public MachiningEquipment GetMillingEquipment()
Returns
GetSessionShell()
Returns the session shell that exposes the runtime surface of the active machining session.
public ISessionShell GetSessionShell()
Returns
LoadProject(string)
Loads a project by file path relative to the admin directory.
public void LoadProject(string projectPath)
Parameters
projectPathstringThe absolute file path
NewProject(string)
Creates a new project by file path.
public void NewProject(string projectPath)
Parameters
projectPathstringThe absolute file path
PlayClFile(string, string)
Plays an NX-CL (CLSF) file from the specified path.
public void PlayClFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths.
relFilePathstringRelative path to the CLSF file.
PlayCsvFile(string, string)
Plays a CSV file from the specified path.
public void PlayCsvFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths.
relFilePathstringRelative path to the CSV file.
PlayNc(string, string)
Plays NC commands from raw text with pace control.
public void PlayNc(string ncText, string fileNameAlternative = "--")
Parameters
ncTextstringThe NC command text to execute
fileNameAlternativestringAlternative name to associate with the NC program
PlayNcFile(string, string)
Plays an NC file from the specified path with pace control.
public void PlayNcFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths
relFilePathstringRelative path to the NC file
PowerReset()
Performs a controller power reset, modelling a power-off / power-on cycle:
- Every IPowerResettable dependency clears its volatile
subset. Persistent dependency state (controller parameters,
Fanuc
#500-#999, etc.) is left intact. - The active MachiningSession's
NcRunnerSessionState is reset so the per-layer
SyntaxPiecedataflow — includingVars.Volatile, modal carries, and the init seed — is dropped. The next RunControlLines(string, IEnumerable<string>, MachiningSession, StepDiagnosticProgress, NcDiagnosticProgress, CancellationToken) call re-initialises everything from scratch.
PowerReset while a project is
loaded would leave volatile commons alive across the supposed power
cycle (they live in the SyntaxPiece JSON dataflow rather than in any
IPowerResettable dependency).
public void PowerReset()
ProcAct(IAct, ISentenceCarrier, CancellationToken?)
Processes an act and returns the results.
public IEnumerable<object> ProcAct(IAct act, ISentenceCarrier sourceCommand = null, CancellationToken? cancellationToken = null)
Parameters
actIActThe act to process.
sourceCommandISentenceCarrierThe source command that triggered the act.
cancellationTokenCancellationToken?Cancellation token to cancel the operation.
Returns
- IEnumerable<object>
Enumerable of results from processing the act.
ReTrainMillingPara(SampleFlag, double, string, CancellationToken, IProgress<IMessage>)
Train Milling Parameter.
public void ReTrainMillingPara(SampleFlag sampleFlags, double outlierRatio, string dstRelFile, CancellationToken cancellationToken, IProgress<IMessage> messageProgress = null)
Parameters
sampleFlagsSampleFlagoutlierRatiodoubledstRelFilestringcancellationTokenCancellationTokenmessageProgressIProgress<IMessage>
ReadNcRunnerSuit(string)
Reads an NcRunnerSuit from relFile (project
relative) and makes it the active suit — switching the active parser (NC or
CSV) — then re-binds every host hookup (see Hi.MachiningProcs.LocalProjectService.RewireForActiveSuit()).
Refused while a control file is playing: the runner's per-session layers are
mid-enumeration and cannot be safely reset (an IProgress<T>
error is reported instead).
public void ReadNcRunnerSuit(string relFile)
Parameters
relFilestring
RefreshDrawing()
Refreshes the visual display of the milling course.
public void RefreshDrawing()
Reg(XFactory)
Bootstraps XML-factory registration for the simulation pipeline.
Entry points must call this once at startup before any project XML
is deserialized. Pass a custom XFactory for test
isolation, or null to populate Default.
Idempotent.
public static void Reg(XFactory factory = null)
Parameters
factoryXFactory
RegisterStepVariable(string, string, string, string, Func<MachiningStep, object>)
Registers a step variable so downstream components (strip charts,
CSV exports, scripting) can read it from MachiningStep.
Idempotent on key.
public void RegisterStepVariable(string key, string name, string unit, string formatString, Func<MachiningStep, object> variableFunc = null)
Parameters
keystringUnique key.
namestringHuman-readable name; may equal
key.unitstringPhysical unit name (
PhysicsUnit); nullable.formatStringstringDisplay format string; nullable.
variableFuncFunc<MachiningStep, object>Optional value extractor; nullable when the value comes from the step's flex dictionary.
ReloadProject()
Reloads the current project.
public void ReloadProject()
ResetRuntime(IProgress<IMessage>)
Reset the runtime states including: meshed geometry, collision flags, machine tool position, CL strips, message buffer and etc..
public void ResetRuntime(IProgress<IMessage> messageProgress = null)
Parameters
RunClFile(string, string)
Runs an NX-CL (CLSF) file from the specified path.
public IEnumerable<Action> RunClFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths.
relFilePathstringRelative path to the CLSF file.
Returns
- IEnumerable<Action>
An enumerable of actions to be executed.
RunCsvFile(string, string)
Runs a CSV file from the specified path.
public IEnumerable<Action> RunCsvFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths.
relFilePathstringRelative path to the CSV file.
Returns
- IEnumerable<Action>
An enumerable of actions to be executed.
RunNc(string, string)
Runs NC commands from raw text.
public IEnumerable<Action> RunNc(string ncText, string fileNameAlternative = "--")
Parameters
ncTextstringThe NC command text to execute
fileNameAlternativestringAlternative name to associate with the NC program
Returns
- IEnumerable<Action>
An enumerable of actions to be executed
RunNcFile(string, string)
Runs an NC file from the specified path.
public IEnumerable<Action> RunNcFile(string baseDirectory, string relFilePath)
Parameters
baseDirectorystringBase directory for resolving relative paths. If the value is null, BaseDirectory substitutes the value.
relFilePathstringRelative path to the NC file.
Returns
- IEnumerable<Action>
An enumerable of actions to be executed.
RunToLineEnd()
Advances the player by one NC/CSV line and pauses.
public void RunToLineEnd()
SaveAsProject(string)
Saves the current project to a specified relative file path.
public void SaveAsProject(string projectPath)
Parameters
projectPathstringThe absolute file path
SaveProject()
Save project by project path.
public void SaveProject()
SetMachiningResolution_mm(double, IProgress<IMessage>)
Sets the machining resolution (mm). Progress is reported to the injected
messageProgress.
public void SetMachiningResolution_mm(double value, IProgress<IMessage> messageProgress = null)
Parameters
valuedoubleThe machining resolution in millimeters.
messageProgressIProgress<IMessage>Sink-agnostic message host for progress reporting.
TrainMillingPara(SampleFlag, bool, double, string, CancellationToken, ICuttingPara, IProgress<IMessage>)
Train Milling Parameter.
public void TrainMillingPara(SampleFlag sampleFlags, bool enableFzOnlyDuringDrilling, double outlierRatio, string dstRelFile, CancellationToken cancellationToken, ICuttingPara paraTemplate, IProgress<IMessage> messageProgress = null)
Parameters
sampleFlagsSampleFlagenableFzOnlyDuringDrillingbooloutlierRatiodoubledstRelFilestringcancellationTokenCancellationTokenparaTemplateICuttingParamessageProgressIProgress<IMessage>
UpdateByMachiningChain()
Updates components when the machining chain changes.
public void UpdateByMachiningChain()
UpdateByMachiningEquipment()
Call on MachiningEquipment Or MachiningChainChanged. i.e. Update By MachiningEquipment Or MachiningChain. The function is called on MachiningEquipment and its delegate property changed. If the changing is raised outer from THIS service, this updating function should be manual called.
public void UpdateByMachiningEquipment()
UpdateIdealMillingToolOffsetTableByToolHouse()
Updates the ideal milling tool offset table based on the current tool house configuration.
public void UpdateIdealMillingToolOffsetTableByToolHouse()
WriteNcRunnerSuit(string)
Writes the active NcRunnerSuit to relFile
(project relative). Pure file IO — does not update any in-memory pointer.
public void WriteNcRunnerSuit(string relFile)
Parameters
relFilestring
WriteShotFile(TimeSpan, string, IProgress<IMessage>)
Writes time-based shot data to a file with the specified sampling period.
public void WriteShotFile(TimeSpan samplingPeriod, string relFileTemplate = "Output/[NcName].shot.csv", IProgress<IMessage> messageProgress = null)
Parameters
samplingPeriodTimeSpanThe time period between samples
relFileTemplatestringTemplate for the output file path, can include [NcName] placeholder
messageProgressIProgress<IMessage>Optional caller-supplied progress sink for start/finish messages.
WriteStepFile(string, IProgress<IMessage>)
Writes step-based data to a file.
public void WriteStepFile(string relFileTemplate = "Output/[NcName].step.csv", IProgress<IMessage> messageProgress = null)
Parameters
relFileTemplatestringTemplate for the output file path, can include [NcName] placeholder
messageProgressIProgress<IMessage>Optional caller-supplied progress sink for start/finish messages.
Events
MachiningProjectChanged
Event raised when the machining project changes.
public event LocalProjectService.MachiningProjectChangedDelegate MachiningProjectChanged
Event Type
MachiningStepBuilt
event to configure steps. The first parameter is the previous step; the second parameter is the current step. The previous step is null if no previous step exists.
public event MachiningActRunner.MachiningStepBuiltDelegate MachiningStepBuilt
Event Type
OnNcFileRan
Event triggered after an NC file is executed.
public event Action OnNcFileRan
Event Type
OnShellMessageAdded
App-lifetime bridge for ShellProgress appends. Because ShellProgress is session-scoped (recreated at BeginSession(), null outside a session), a consumer that wants every session's shell messages subscribes here once instead of chasing the swapping instance — BeginSession() re-wires the bridge to the new sink each session, the same way OnSourcedActEntry is bridged. Carries the append index and the message.
public event Action<int, IMessage> OnShellMessageAdded
Event Type
OnShellMessageCleared
App-lifetime bridge for ShellProgress clears (see OnShellMessageAdded).
public event Action OnShellMessageCleared
Event Type
OnSourcedActEntry
App-lifetime event triggered for each SourcedActEntry produced during NC/CSV execution.
public event Action<SourcedActEntry> OnSourcedActEntry
Event Type
OnSyntaxPieceRan
Raised after each SyntaxPiece has been run during NC execution (app lifetime).
public event Action<SyntaxPiece> OnSyntaxPieceRan
Event Type
OnUpdatedInspectingQuantityFunc
Event triggered when the inspecting quantity function is updated.
public event Action OnUpdatedInspectingQuantityFunc
Event Type
WorkpieceChanged
Event that is raised when the workpiece is changed.
public event Action<SeqPair<Workpiece>> WorkpieceChanged
Event Type
Remarks
This event is triggered whenever the workpiece property is modified. Subscribers can use this event to respond to changes in the workpiece configuration, such as updating visualizations or recalculating machining parameters. The event provides both the previous and new workpiece values through a SeqPair.