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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_xml_rs;
use serde_xml_rs::deserialize;
extern crate chrono;
extern crate miniseed;
use std::net::TcpStream;
use std::io::{Write,Read};
use std::io;
use std::time::Duration;
use chrono::DateTime;
use chrono::Utc;
use miniseed::ms_record;
#[derive(Debug)]
pub struct SeedLinkClient {
addr: String,
stream: TcpStream,
verbose: bool
}
#[derive(Debug,Clone)]
pub struct StreamID {
network: String,
station: String,
location: String,
channel: String,
}
impl StreamID {
pub fn new(net: &str, sta: &str, loc: &str, cha: &str) -> Self {
StreamID {network: net.to_owned(),
station: sta.to_owned(),
location: loc.to_owned(),
channel: cha.to_owned()
}
}
}
#[derive(Debug)]
pub enum SLError {
String(String),
Io(io::Error),
Int(std::num::ParseIntError),
}
impl SeedLinkClient {
pub fn new(host: &str, port: i64) -> SeedLinkClient {
let addr = format!("{}:{}", host, port);
let stream = TcpStream::connect(&addr)
.expect("Cannot connect to server");
SeedLinkClient{ stream: stream,
addr: addr,
verbose: false}
}
pub fn timeout(&mut self, millis: u64) -> Result<usize,SLError> {
let s = &self.stream;
let duration = Duration::from_millis( millis );
match s.set_read_timeout(Some(duration)) {
Ok(_) => {},
Err(err) => {return Err(SLError::Io(err)); }
}
Ok(0)
}
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize,SLError> {
let mut s = &self.stream;
s.read(buf).map_err(SLError::Io)
}
pub fn write<S: Into<String>>(&mut self, buf: S) -> Result<usize,SLError> {
let mut s = &self.stream;
s.write(&buf.into().as_bytes()).map_err(SLError::Io)
}
pub fn cmd(&mut self, cmd: &str) -> Result<usize,SLError> {
if self.verbose {
println!("SEND: {}", cmd);
}
self.write([cmd.to_owned() + "\r\n"].join(""))
}
pub fn bye(&mut self) -> Result<usize,SLError> {
self.cmd("BYE")
}
pub fn cat(&mut self) -> Result<usize,SLError> {
self.cmd("CAT")
}
pub fn hello(&mut self) -> Result<usize,SLError> {
self.cmd("HELLO")
}
pub fn end(&mut self) -> Result<usize,SLError> {
self.cmd("END")
}
pub fn start(&mut self) -> Result<usize,SLError> {
self.end()
}
pub fn data_please(&mut self) -> Result<usize,SLError> {
self.end()
}
pub fn backfill(&mut self, when: DateTime<Utc>) -> Result<usize,SLError> {
let s = format!("TIME {}", when.format("%Y,%m,%d,%H,%M,%S"));
self.cmd(s.as_str())
}
pub fn stream(&mut self, id: &StreamID) -> Result<usize, SLError> {
self.station(id)?;
self.select(id)
}
pub fn station(&mut self, sid: &StreamID) -> Result<usize, SLError> {
let s = format!("STATION {} {}", sid.station, sid.network);
self.cmd(s.as_str())?;
self.expect_ok()
}
pub fn select(&mut self, sid: &StreamID) -> Result<usize, SLError> {
let s = format!("SELECT {:2}{:3}", sid.location, sid.channel);
try!(self.cmd(s.as_str()));
self.expect_ok()
}
pub fn expect_ok(&mut self) -> Result<usize, SLError> {
let mut rbuf = [0u8;2048];
let n = try!(self.read(&mut rbuf));
let s = String::from_utf8_lossy(&rbuf[..n]);
if self.verbose {
println!("===>: {:?}", s);
}
if s == "ERROR\r\n" {
return Err(SLError::String(String::from("Seedlink returned an Error")));
}
if s != "OK\r\n" {
return Err(SLError::String(format!("Seedlink returned an unexpected message: {}", s)));
}
return Ok(0);
}
pub fn time_range(&mut self, t0: DateTime<Utc>, t1: DateTime<Utc>) -> Result<usize, SLError> {
let st0 = t0.format("%Y,%m,%d,%H,%M,%S").to_string();
let st1 = t1.format("%Y,%m,%d,%H,%M,%S").to_string();
if st0 == st1 {
return Err(SLError::String(String::from("Time Range has no Duration")));
}
let s = format!("TIME {} {}", st0, st1);
self.cmd(s.as_str())?;
self.expect_ok()
}
pub fn connect(&mut self, verbose: bool) -> Result<usize, SLError> {
try!(self.hello());
self.verbose = verbose;
let mut data = vec![0u8;2048];
let n = try!(self.read(&mut data));
let v = data[..n].to_vec();
let s = String::from_utf8(v).expect("Found invalid UTF-8");
if self.verbose {
println!("===>: {:?}", s);
}
Ok(n)
}
pub fn available_streams(&mut self) -> Result<Seedlink, SLError> {
let mut txt = String::with_capacity(1024);
let mut rbuf = [0u8;4096];
let mut buf = vec![];
try!(self.cmd("INFO STREAMS"));
loop {
let mut id = 0;
let n = try!(self.read(&mut rbuf));
buf.extend(rbuf[..n].iter().cloned());
while buf.len() >= 520 {
id = parse_header(&buf)?;
buf.drain(..8);
let msr = ms_record::parse(&buf);
buf.drain(..512);
let chunk = msr.as_string().unwrap();
txt += &chunk;
}
if id < 0 {
break;
}
}
match deserialize(txt.as_bytes()) {
Ok(sl) => Ok(sl),
Err(_) => Err(SLError::String(String::from("Error parsing xml"))),
}
}
}
pub fn parse(mut buf: &mut Vec<u8>) -> Result<(i64,ms_record),SLError> {
let num = parse_header(&buf)?;
buf.drain(..8);
let msr = ms_record::parse(&mut buf);
buf.drain(..512);
Ok((num, msr))
}
pub fn parse_header(buf: &[u8]) -> Result<i64,SLError> {
if buf[0] as char != 'S' || buf[1] as char != 'L' {
return Err(SLError::String(String::from("Not SeedLink Packet")));
}
let ss = String::from_utf8_lossy(&buf[2..8]);
if ss == "INFO *" {
return Ok(0);
}
if ss == "INFO " {
return Ok(-1);
}
let seqnum = i64::from_str_radix(&ss, 16).map_err(SLError::Int)?;
Ok(seqnum)
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct Seedlink {
software: String,
organization: String,
started: String,
station: Vec<Station>,
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct Station {
name: String,
network: String,
description: String,
begin_seq: String,
end_seq: String,
stream_check: String,
stream: Vec<Stream>
}
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct Stream {
seedname: String,
location: String,
#[serde(rename = "type")]
stype: String,
begin_time: String,
end_time: String,
begin_recno: Option<String>,
end_recno: Option<String>,
gap_check: Option<String>,
gap_threshold: Option<String>,
}
use std::fmt;
impl fmt::Display for Stream {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}_{}", self.location.trim(), self.seedname.trim())
}
}
impl fmt::Display for Station {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}_{}", self.network.trim(), self.name.trim())
}
}
impl Seedlink {
pub fn streams(&self) -> Vec<String> {
let mut st = vec![];
for sta in &self.station {
for cha in &sta.stream {
st.push( format!("{}_{}", sta,cha) );
}
}
st.sort();
st
}
#[doc(hidden)]
pub fn read(file: &str) -> Seedlink {
let mut fp = std::fs::File::open(file).expect("Error opening file");
let mut buf = vec![];
let _ = fp.read_to_end(&mut buf).unwrap();
let txt = String::from_utf8(buf).unwrap();
deserialize(txt.as_bytes()).unwrap()
}
}
#[cfg(test)]
mod tests {
}