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
// Copyright (c) 2016 Brandon Thomas <bt@brand.io>, <echelon@gmail.com>

//! This module contains the EtherDream hardware interface.

use byteorder::LittleEndian;
use byteorder::WriteBytesExt;
use error::EtherdreamError;
use point::PipelinePoint;
use point::SimplePoint;
use protocol::Begin;
use protocol::COMMAND_PING;
use protocol::COMMAND_PREPARE;
use protocol::CommandCode;
use protocol::DacResponse;
use protocol::Point;
use std::io::Read;
use std::io::Write;
use std::net::IpAddr;
use std::net::TcpStream;
use std::time::Duration;

/// An EtherDream DAC.
/// Controls what we display on the projector.
pub struct Dac {
  ip_address: IpAddr,
  stream: TcpStream,
}

impl Dac {
  /// CTOR.
  pub fn new(ip_address: IpAddr) -> Dac {
    let stream = TcpStream::connect((ip_address, 7765u16)).unwrap(); // FIXME

    // These should be reasonable timeouts for any arbitrary laser show.
    stream.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); // FIXME
    stream.set_write_timeout(Some(Duration::from_millis(500))).unwrap();

    Dac {
      ip_address: ip_address,
      stream: stream,
    }
  }

  /// IP address the DAC lives at.
  pub fn get_ip_address(&self) -> &IpAddr {
    &self.ip_address
  }

  /// Stream points generated by a function.
  /// The function takes the number of points it needs to generate.
  pub fn play_function<F>(&mut self, mut make_points: F)
      -> Result<(), EtherdreamError> where F: FnMut(u16) -> Vec<Point> {
    // Read initial hello message from DAC.
    let mut response = self.read_response()?;

    self.try_prepare(response);

    let mut started = false;

    loop {
      let num_points = 1799 - response.status.buffer_fullness;
      let points = make_points(num_points);

      let mut cmd : Vec<u8> = Vec::new();
      cmd.push(0x64); // 'data' command.
      cmd.write_u16::<LittleEndian>(num_points)?;

      for point in points {
        cmd.extend(point.serialize());
      }

      response = self.write_serialized_points(&cmd)?;

      if !started {
        response = self.begin()?;
        started = true;
      }
    }
  }

  /// Stream points generated by a function.
  /// The function takes the number of points it needs to generate.
  pub fn stream_pipeline_points<F>(&mut self, mut make_points: F)
      -> Result<(), EtherdreamError> where F: FnMut(u16) -> Vec<PipelinePoint> {
    // Read initial hello message from DAC.
    let mut response = self.read_response()?;

    self.try_prepare(response);

    let mut started = false;

    loop {
      let num_points = 1799 - response.status.buffer_fullness;
      let points = make_points(num_points);

      let mut cmd : Vec<u8> = Vec::new();
      cmd.push(0x64); // 'data' command.
      cmd.write_u16::<LittleEndian>(num_points)?;

      for point in points {
        cmd.write_u16::<LittleEndian>(0)?; // Control
        cmd.write_i16::<LittleEndian>(point.x as i16)?;
        cmd.write_i16::<LittleEndian>(point.y as i16)?;

        if point.is_blank {
          cmd.write_u16::<LittleEndian>(0)?;
          cmd.write_u16::<LittleEndian>(0)?;
          cmd.write_u16::<LittleEndian>(0)?;
        } else {
          // TODO/FIXME:
          //cmd.write_u16::<LittleEndian>(point.r as u16)?;
          //cmd.write_u16::<LittleEndian>(point.g as u16)?;
          //cmd.write_u16::<LittleEndian>(point.b as u16)?;
          cmd.write_u16::<LittleEndian>(65535)?;
          cmd.write_u16::<LittleEndian>(65535)?;
          cmd.write_u16::<LittleEndian>(65535)?;
        }

        cmd.write_u16::<LittleEndian>(0)?; // i
        cmd.write_u16::<LittleEndian>(0)?; // u1
        cmd.write_u16::<LittleEndian>(0)?; // u2
      }

      response = self.write_serialized_points(&cmd)?;

      if !started {
        response = self.begin()?;
        started = true;
      }
    }
  }

  /// Stream points generated by a function.
  /// The function takes the number of points it needs to generate.
  pub fn stream_simple_points<F>(&mut self, mut make_points: F)
      -> Result<(), EtherdreamError> where F: FnMut(u16) -> Vec<SimplePoint> {
    // Read initial hello message from DAC.
    let mut response = self.read_response()?;

    self.try_prepare(response);

    let mut started = false;

    #[inline(always)]
    fn expand(color: u8) -> u16 {
      (color as u16) * 257
    }

    loop {
      let num_points = 1799 - response.status.buffer_fullness;
      let points = make_points(num_points);

      let mut cmd : Vec<u8> = Vec::new();
      cmd.push(0x64); // 'data' command.
      cmd.write_u16::<LittleEndian>(num_points)?;

      for point in points {
        cmd.write_u16::<LittleEndian>(0)?; // Control
        cmd.write_i16::<LittleEndian>(point.x)?;
        cmd.write_i16::<LittleEndian>(point.y)?;
        if point.is_blank {
          cmd.write_u16::<LittleEndian>(0)?;
          cmd.write_u16::<LittleEndian>(0)?;
          cmd.write_u16::<LittleEndian>(0)?;
        } else {
          cmd.write_u16::<LittleEndian>(expand(point.r))?;
          cmd.write_u16::<LittleEndian>(expand(point.g))?;
          cmd.write_u16::<LittleEndian>(expand(point.b))?;
        }
        cmd.write_u16::<LittleEndian>(0)?; // i
        cmd.write_u16::<LittleEndian>(0)?; // u1
        cmd.write_u16::<LittleEndian>(0)?; // u2
      }

      response = self.write_serialized_points(&cmd)?;

      if !started {
        response = self.begin()?;
        started = true;
      }
    }
  }

  fn hello(&mut self) -> Result<DacResponse, EtherdreamError> {
    let _bytes = self.stream.write(&[COMMAND_PING])?;
    self.read_response() // FIXME
  }

  fn prepare(&mut self) -> Result<DacResponse, EtherdreamError> {
    let _bytes = self.stream.write(&[COMMAND_PREPARE])?;
    self.read_expected_response(CommandCode::Prepare)
  }

  fn begin(&mut self) -> Result<DacResponse, EtherdreamError> {
    let cmd = Begin { low_water_mark: 0, point_rate: 30_000 };
    let _bytes = self.stream.write(&cmd.serialize())?;
    self.read_expected_response(CommandCode::Begin)
  }

  /// Clear emergency stop state.
  fn clear_emergency_stop(&mut self) -> Result<DacResponse, EtherdreamError> {
    let cmd = [ 0x63u8 ]; // 'c'
    let _bytes = self.stream.write(&cmd)?;
    self.read_response() // FIXME
  }

  fn try_prepare(&mut self, response: DacResponse) {
    // Documentation for playback_flags:
    // [0]: Emergency stop occurred due to E-Stop packet or invalid command.
    // [1]: Emergency stop occurred due to E-Stop input to projector.
    // [2]: Emergency stop input to projector is currently active.
    // [3]: Emergency stop occurred due to overtemperature condition.
    // [4]: Overtemperature condition is currently active.
    // [5]: Emergency stop occurred due to loss of Ethernet link.
    // [15:5]: Future use.
    let response = match response.status.playback_flags {
      0x1 | 0x2 | 0x4 | 0x6 => {
        // A previous E-Stop state must be cleared.
        self.clear_emergency_stop().unwrap() // FIXME
      },
      _ => response,
    };

    if response.status.playback_flags != 0x0 && response.status.playback_flags != 0x1 {
      println!("\nBad playback flags, must PREPARE: {}", response.status.playback_flags);
      println!("\nSend prepare");
      let resp = self.prepare().unwrap();
      println!("Response: {:?}", resp);
      if !resp.is_ack() {
        println!("Failure!");
        panic!("Non-ACK received");
      }
      return;
    }

    if response.status.playback_state == 0x2 {
      println!("\nBad playback_state, must PREPARE: {}", response.status.playback_state);
      println!("\nSend prepare");
      let resp = self.prepare().unwrap();
      println!("Response: {:?}", resp);
      if !resp.is_ack() {
        println!("Failure!");
        panic!("Non-ACK received");
      }
    }
  }

  // TODO:
  // Sends (3 + 18*n) bytes.
  // fn write_data(&mut self, num_points: u16) -> Result<DacResponse, EtherdreamError>

  /// Write a slice of points to the DAC.
  fn write_serialized_points(&mut self, serialized_points: &[u8])
                                 -> Result<DacResponse, EtherdreamError> {
    self.stream.write(&serialized_points)?;
    self.read_expected_response(CommandCode::Data)
  }

  /// Read a response from the DAC, and parse error conditions.
  /// Called after sending a command.
  fn read_expected_response(&mut self, expected_command: CommandCode)
      -> Result<DacResponse, EtherdreamError> {

    let response = self.read_response()?;

    if !response.acknowledgement.is_ack() {
      return Err(EtherdreamError::ReceivedNack {
        code: response.acknowledgement,
        command: response.command,
      });
    }

    if response.command != expected_command {
      return Err(EtherdreamError::WrongResponse);
    }

    Ok(response)
  }

  fn read_response(&mut self) -> Result<DacResponse, EtherdreamError> {
    let mut buf = [0; 22];
    let _size = self.stream.read(&mut buf)?;
    DacResponse::parse(&buf)
  }
}