1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use crate::app::format::write::HeaderWriter;
use crate::app::parse::parser::{HeaderCollection, Response};
use crate::app::FunctionCode;
use crate::app::ResponseHeader;
use crate::link::EndpointAddress;
use crate::master::association::Association;
use crate::master::error::TaskError;
use crate::master::extract::extract_measurements;
use crate::master::handler::Promise;
use crate::master::poll::Poll;
use crate::master::request::{Classes, EventClasses};
use crate::master::tasks::auto::AutoTask;
use crate::master::tasks::command::CommandTask;
use crate::master::tasks::read::SingleReadTask;
use crate::master::tasks::restart::RestartTask;
use crate::master::tasks::time::TimeSyncTask;
use crate::master::{ReadType, TaskType};

use crate::master::tasks::deadbands::WriteDeadBandsTask;
use crate::master::tasks::empty_response::EmptyResponseTask;
use crate::master::tasks::file_read::FileReadTask;
use crate::master::tasks::get_file_info::GetFileInfoTask;

pub(crate) mod auto;
pub(crate) mod command;
pub(crate) mod deadbands;
pub(crate) mod empty_response;
pub(crate) mod file_read;
pub(crate) mod get_file_info;
pub(crate) mod read;
pub(crate) mod restart;
pub(crate) mod time;

/// Queued task requiring I/O
pub(crate) struct AssociationTask {
    /// Outstation address
    pub(crate) address: EndpointAddress,
    /// Actual task to perform
    pub(crate) details: Task,
}

impl AssociationTask {
    pub(crate) fn new(address: EndpointAddress, details: Task) -> Self {
        Self { address, details }
    }
}

/// There are two broad categories of tasks. Reads
/// require handling for multi-fragmented responses.
pub(crate) enum Task {
    /// Reads require handling for multi-fragmented responses
    Read(ReadTask),
    /// NonRead tasks always require FIR/FIN == 1, but might require multiple read/response cycles, e.g. SBO
    NonRead(NonReadTask),
    /// Send link status request
    LinkStatus(Promise<Result<(), TaskError>>),
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub(crate) enum TaskId {
    LinkStatus,
    Function(FunctionCode),
}

impl Task {
    pub(crate) fn on_task_error(self, association: Option<&mut Association>, err: TaskError) {
        match self {
            Task::NonRead(task) => task.on_task_error(association, err),
            Task::Read(task) => task.on_task_error(association, err),
            Task::LinkStatus(promise) => promise.complete(Err(err)),
        }
    }

    /// Perform operation before sending and check if the request should still be sent
    ///
    /// Returning Some means the task should proceed, returning None means
    /// the task was cancelled, forget about it.
    pub(crate) fn start(self, association: &mut Association) -> Option<Task> {
        if let Task::NonRead(task) = self {
            return task.start(association).map(|task| task.wrap());
        }

        Some(self)
    }

    pub(crate) fn get_id(&self) -> TaskId {
        match self {
            Task::LinkStatus(_) => TaskId::LinkStatus,
            Task::Read(_) => TaskId::Function(FunctionCode::Read),
            Task::NonRead(t) => TaskId::Function(t.function()),
        }
    }
}

pub(crate) trait RequestWriter {
    fn function(&self) -> FunctionCode;
    fn write(&self, writer: &mut HeaderWriter) -> Result<(), TaskError>;
}

pub(crate) enum ReadTask {
    /// Periodic polls that are configured when creating associations
    PeriodicPoll(Poll),
    /// Integrity poll that occurs during startup, or after outstation restarts
    StartupIntegrity(Classes),
    /// Event scan when IIN bit is detected
    EventScan(EventClasses),
    /// One-time read request
    SingleRead(SingleReadTask),
}

pub(crate) enum NonReadTask {
    /// tasks that occur automatically during startup, or based on events or configuration,
    Auto(AutoTask),
    /// commands initiated from the user API
    Command(CommandTask),
    /// time synchronization
    TimeSync(TimeSyncTask),
    /// restart operation
    Restart(RestartTask),
    /// write dead-bands
    DeadBands(WriteDeadBandsTask),
    /// Generic task for anything that doesn't have response object headers
    EmptyResponseTask(EmptyResponseTask),
    /// read file from the outstation
    FileRead(FileReadTask),
    /// get info about a file
    GetFileInfo(GetFileInfoTask),
}

impl RequestWriter for ReadTask {
    fn function(&self) -> FunctionCode {
        FunctionCode::Read
    }

    fn write(&self, writer: &mut HeaderWriter) -> Result<(), TaskError> {
        match self {
            ReadTask::PeriodicPoll(poll) => poll.format(writer)?,
            ReadTask::StartupIntegrity(classes) => classes.write(writer)?,
            ReadTask::EventScan(classes) => classes.write(writer)?,
            ReadTask::SingleRead(req) => req.format(writer)?,
        }
        Ok(())
    }
}

impl RequestWriter for NonReadTask {
    fn function(&self) -> FunctionCode {
        self.function()
    }

    fn write(&self, writer: &mut HeaderWriter) -> Result<(), TaskError> {
        match self {
            NonReadTask::Auto(t) => t.write(writer)?,
            NonReadTask::Command(t) => t.write(writer)?,
            NonReadTask::TimeSync(t) => t.write(writer)?,
            NonReadTask::Restart(_) => {}
            NonReadTask::DeadBands(t) => t.write(writer)?,
            NonReadTask::EmptyResponseTask(t) => t.write(writer)?,
            NonReadTask::FileRead(t) => t.write(writer)?,
            NonReadTask::GetFileInfo(t) => t.write(writer)?,
        }
        Ok(())
    }
}

impl From<crate::app::format::WriteError> for TaskError {
    fn from(_: crate::app::format::WriteError) -> Self {
        TaskError::WriteError
    }
}

impl ReadTask {
    pub(crate) fn wrap(self) -> Task {
        Task::Read(self)
    }

    pub(crate) async fn process_response(
        &mut self,
        association: &mut Association,
        header: ResponseHeader,
        objects: HeaderCollection<'_>,
    ) {
        match self {
            ReadTask::StartupIntegrity(_) => {
                association.handle_integrity_response(header, objects).await
            }
            ReadTask::PeriodicPoll(_) => association.handle_poll_response(header, objects).await,
            ReadTask::EventScan(_) => {
                association
                    .handle_event_scan_response(header, objects)
                    .await
            }
            ReadTask::SingleRead(task) => match &mut task.custom_handler {
                Some(handler) => {
                    extract_measurements(ReadType::SinglePoll, header, objects, handler.as_mut())
                        .await
                }
                None => association.handle_read_response(header, objects).await,
            },
        }
    }

    pub(crate) fn complete(self, association: &mut Association) {
        match self {
            ReadTask::StartupIntegrity(_) => association.on_integrity_scan_complete(),
            ReadTask::PeriodicPoll(poll) => association.complete_poll(poll.id),
            ReadTask::EventScan(_) => association.on_event_scan_complete(),
            ReadTask::SingleRead(task) => task.on_complete(),
        }
    }

    pub(crate) fn on_task_error(self, association: Option<&mut Association>, err: TaskError) {
        match self {
            ReadTask::StartupIntegrity(_) => {
                if let Some(association) = association {
                    association.on_integrity_scan_failure();
                }
            }
            ReadTask::PeriodicPoll(poll) => {
                if let Some(association) = association {
                    tracing::warn!("poll {} failed", poll.id);
                    association.complete_poll(poll.id);
                }
            }
            ReadTask::EventScan(_) => {
                if let Some(association) = association {
                    association.on_event_scan_failure();
                }
            }
            ReadTask::SingleRead(task) => task.on_task_error(err),
        }
    }

    pub(crate) fn as_task_type(&self) -> TaskType {
        match self {
            Self::PeriodicPoll(_) => TaskType::PeriodicPoll,
            Self::StartupIntegrity(_) => TaskType::StartupIntegrity,
            Self::EventScan(_) => TaskType::AutoEventScan,
            Self::SingleRead(_) => TaskType::UserRead,
        }
    }
}

impl NonReadTask {
    pub(crate) fn wrap(self) -> Task {
        Task::NonRead(self)
    }

    pub(crate) fn start(self, association: &mut Association) -> Option<NonReadTask> {
        match self {
            Self::Command(_) => Some(self),
            Self::Auto(_) => Some(self),
            Self::TimeSync(task) => task.start(association).map(|task| task.wrap()),
            Self::Restart(_) => Some(self),
            Self::DeadBands(_) => Some(self),
            Self::EmptyResponseTask(_) => Some(self),
            Self::FileRead(_) => Some(self),
            Self::GetFileInfo(_) => Some(self),
        }
    }

    pub(crate) fn function(&self) -> FunctionCode {
        match self {
            Self::Command(task) => task.function(),
            Self::Auto(task) => task.function(),
            Self::TimeSync(task) => task.function(),
            Self::Restart(task) => task.function(),
            Self::DeadBands(task) => task.function(),
            Self::EmptyResponseTask(task) => task.function(),
            Self::FileRead(task) => task.function(),
            Self::GetFileInfo(task) => task.function(),
        }
    }

    pub(crate) fn on_task_error(self, association: Option<&mut Association>, err: TaskError) {
        match self {
            Self::Command(task) => task.on_task_error(err),
            Self::TimeSync(task) => task.on_task_error(association, err),
            Self::Auto(task) => task.on_task_error(association, err),
            Self::Restart(task) => task.on_task_error(err),
            Self::DeadBands(task) => task.on_task_error(err),
            Self::EmptyResponseTask(task) => task.on_task_error(err),
            Self::FileRead(task) => task.on_task_error(err),
            Self::GetFileInfo(task) => task.on_task_error(err),
        }
    }

    pub(crate) async fn handle(
        self,
        association: &mut Association,
        response: Response<'_>,
    ) -> Option<NonReadTask> {
        match self {
            Self::Command(task) => task.handle(response),
            Self::Auto(task) => match response.objects.ok() {
                Some(headers) => task.handle(association, response.header, headers),
                None => None,
            },
            Self::TimeSync(task) => task.handle(association, response),
            Self::Restart(task) => task.handle(response),
            Self::DeadBands(task) => task.handle(response),
            Self::EmptyResponseTask(task) => task.handle(response),
            Self::FileRead(task) => task.handle(response).await,
            Self::GetFileInfo(task) => task.handle(response),
        }
    }

    pub(crate) fn as_task_type(&self) -> TaskType {
        match self {
            Self::Command(_) => TaskType::Command,
            Self::Auto(x) => match x {
                AutoTask::ClearRestartBit => TaskType::ClearRestartBit,
                AutoTask::EnableUnsolicited(_) => TaskType::EnableUnsolicited,
                AutoTask::DisableUnsolicited(_) => TaskType::DisableUnsolicited,
            },
            Self::TimeSync(_) => TaskType::TimeSync,
            Self::Restart(_) => TaskType::Restart,
            Self::DeadBands(_) => TaskType::WriteDeadBands,
            Self::EmptyResponseTask(_) => TaskType::GenericEmptyResponse(self.function()),
            Self::FileRead(_) => TaskType::FileRead,
            Self::GetFileInfo(_) => TaskType::GetFileInfo,
        }
    }
}