aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Telemetry/Sources/TelemetryJobStatusSource.cs
blob: 9f748890987629f8ca74ec70a7c8567cdf071483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.Telemetry.Telemetries;
// NEW:
using System.Timers;

namespace Tango.Telemetry.Sources
{
    public class TelemetryJobStatusSource : ITelemetryStreamingSource
    {
        private IMachineOperator _machineOperator;
        private Job _job;
        private TelemetryJobStatus _lastStatus;
        private String _groupID;
        private DateTime _startTime;

        // NEW: throttle state
        private readonly object _lock = new object();
        private DateTime _lastStatusArrivedUtc;
        private DateTime _lastEmittedUtc;
        private Timer _emitTimer; // ticks every 1s

        public bool IsStarted { get; private set; }
        public string Name { get; } = "Job Status Streaming";
        public bool RequiresTelemetryDuplicationTracking { get; }

        public event EventHandler<TelemetryAvailableEventArgs> TelemetryAvailable;

        public TelemetryJobStatusSource(IMachineOperator machineOperator)
        {
            _machineOperator = machineOperator;
        }

        public void Start()
        {
            if (!IsStarted)
            {
                IsStarted = true;
                _machineOperator.PrintingStarted += MachineOperator_PrintingStarted;

                // NEW: start 1s emitter (idempotent)
                if (_emitTimer == null)
                {
                    _emitTimer = new Timer(1000);
                    _emitTimer.AutoReset = true;
                    _emitTimer.Elapsed += EmitTimer_Elapsed;
                    _emitTimer.Start();
                }
            }
        }

        public void Stop()
        {
            if (IsStarted)
            {
                IsStarted = false;
                _machineOperator.PrintingStarted -= MachineOperator_PrintingStarted;

                // NEW: stop timer
                if (_emitTimer != null)
                {
                    _emitTimer.Stop();
                    _emitTimer.Elapsed -= EmitTimer_Elapsed;
                    _emitTimer.Dispose();
                    _emitTimer = null;
                }
            }
        }

        private void MachineOperator_PrintingStarted(object sender, PrintingEventArgs e)
        {
            if (e.JobHandler != null)
            {
                _groupID = Guid.NewGuid().ToString();
                _job = e.Job;
                _startTime = DateTime.UtcNow;
                e.JobHandler.StatusChanged += JobHandler_StatusChanged;
                e.JobHandler.Failed += JobHandler_Failed;
            }
        }

        // NEW: timer tick — emit only the latest status observed within last 5 seconds, once per tick
        private void EmitTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!IsStarted) return;

            TelemetryJobStatus toEmit = null;
            DateTime now = DateTime.UtcNow;

            lock (_lock)
            {
                // Only emit if we have a newer status than last emitted,
                // and that status is fresh (arrived within the last 5 seconds).
                if (_lastStatus != null &&
                    _lastStatusArrivedUtc > _lastEmittedUtc &&
                    (now - _lastStatusArrivedUtc) <= TimeSpan.FromSeconds(5))
                {
                    toEmit = _lastStatus;
                    _lastEmittedUtc = now; // mark emission (1 per tick max)
                }
            }

            if (toEmit != null)
            {
                TelemetryAvailable?.Invoke(this, new TelemetryAvailableEventArgs
                {
                    TelemetryObject = toEmit,
                    DisableDeliveryRetries = true
                });
            }
        }

        private void JobHandler_StatusChanged(object sender, RunningJobStatus status)
        {
            if (!IsStarted) return;

            // CHANGED: just update the latest snapshot fast; do NOT emit here.
            var tStatus = new TelemetryJobStatus
            {
                JobName = _job?.Name,
                ID = _groupID,
                TotalTime = status.TotalTime,
                RemainingTime = status.RemainingTime,
                Progress = status.ProgressMinusSettingUp,
                TotalProgress = status.TotalProgressMinusSettingUp,
                CurrentUnit = status.CurrentUnit,
                RemainingUnits = status.RemainingUnits,
                CurrentUnitProgress = status.CurrentUnitProgress,
                CurrentUnitTotalProgress = status.CurrentUnitTotalProgress,
                Message = status.Message
            };

            if (status.ProgressMinusSettingUp > 0) tStatus.Status = TelemetryJobStatus.JobStatus.InProgress;
            if (status.IsCompleted) tStatus.Status = TelemetryJobStatus.JobStatus.Completed;
            if (status.IsFailed) tStatus.Status = TelemetryJobStatus.JobStatus.Failed;
            if (status.IsCanceled) tStatus.Status = TelemetryJobStatus.JobStatus.Aborted;

            lock (_lock)
            {
                _lastStatus = tStatus;
                _lastStatusArrivedUtc = DateTime.UtcNow;
            }
        }

        private void JobHandler_Failed(object sender, Exception e)
        {
            // CHANGED: update the latest snapshot and let the timer emit it (within ~1s)
            lock (_lock)
            {
                if (_lastStatus != null)
                {
                    _lastStatus.Message = e.FlattenMessage();
                    _lastStatus.Status = TelemetryJobStatus.JobStatus.Failed;
                    _lastStatusArrivedUtc = DateTime.UtcNow;
                }
            }
        }

        public void Dispose()
        {
            Stop();
        }
    }
}