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
extern crate wdg_uri; use std::error::Error; use std::fmt; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } #[allow(dead_code)] struct MeasurementTag { key: String, value: String, } #[allow(dead_code)] struct MeasurementField { key: String, value: String, } #[allow(dead_code)] struct Measurement { name: String, tags: Option<Vec<MeasurementTag>>, fields: Vec<MeasurementField>, timestamp: Option<i64>, } #[derive(Debug)] struct InfluxError(String); impl fmt::Display for InfluxError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "Error: {}", self.0) } } impl Error for InfluxError {} pub enum Authentication { None, BasicAuthenticationQueryParameters(String, String), BasicAuthenticationRequestBody(String, String), } pub struct Influx { uri: String, stream: Option<TcpStream>, #[allow(dead_code)] authentication: Authentication, } impl Influx { pub fn new(uri: String) -> Influx { Influx { uri, stream: None, authentication: Authentication::None, } } pub fn connect(&mut self) -> Result<(), Box<dyn Error>> { let stream = TcpStream::connect(&self.uri)?; stream.set_nodelay(true)?; self.stream = Some(stream); Ok(()) } pub fn disconnect(&mut self) -> Result<(), Box<dyn Error>> { match &self.stream { Some(stream) => stream.shutdown(Shutdown::Both)?, None => {} } Ok(()) } pub fn ping(&mut self) -> Result<bool, Box<dyn Error>> { match &mut self.stream { Some(stream) => { stream.write( format!("HEAD /ping HTTP/1.1\r\nHost: {}\r\n\r\n", self.uri).as_bytes(), )?; let mut buffer = [0u8; 12]; stream.read(&mut buffer)?; Ok(buffer[9] == 0x32 && buffer[10] == 0x30 && buffer[11] == 0x34) } None => Err(Box::new(InfluxError("no stream".into()))), } } }