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
//!     
//!     #Open Pixel Control
//!     
//!     Open Pixel Control is a protocol that is used to control arrays of RGB lights
//!     like [Total Control Lighting](http://www.coolneon.com/) and [Fadecandy devices](https://github.com/scanlime/fadecandy).
//!     
//!     
//!     # Examples
//!     Setup Server to Listen for Messages: 
//!     
//!     ```rust,no_run
//!     extern crate opc;
//!     extern crate futures;
//!     extern crate tokio_core;
//!     extern crate tokio_io;
//!     
//!     use opc::OpcCodec;
//!     use futures::{Future, Stream};
//!     
//!     use tokio_io::AsyncRead;
//!     use tokio_core::net::TcpListener;
//!     use tokio_core::reactor::Core;
//!     
//!     fn main() {
//!         let mut core = Core::new().unwrap();
//!         let handle = core.handle();
//!         let remote_addr = "127.0.0.1:7890".parse().unwrap();
//!     
//!         let listener = TcpListener::bind(&remote_addr, &handle).unwrap();
//!     
//!         // Accept all incoming sockets
//!         let server = listener.incoming().for_each(move |(socket, _)| {
//!             // `OpcCodec` handles encoding / decoding frames.
//!             let transport = socket.framed(OpcCodec);
//!     
//!             let process_connection = transport.for_each(|message| {
//!                 println!("GOT: {:?}", message);
//!                 Ok(())
//!             });
//!     
//!             // Spawn a new task dedicated to processing the connection
//!             handle.spawn(process_connection.map_err(|_| ()));
//!     
//!             Ok(())
//!         });
//!     
//!         // Open listener
//!         core.run(server).unwrap();
//!     }
//!     ```

extern crate tokio_io;
extern crate bytes;

use std::io;

use tokio_io::codec::{Encoder, Decoder};
use bytes::{BytesMut, BufMut, Buf, IntoBuf, BigEndian};

/// Default openpixel tcp port
pub const DEFAULT_OPC_PORT: usize = 7890;

const MAX_MESSAGE_SIZE: usize = 0xffff;
const SYS_EXCLUSIVE: u8 = 0xff;
const SET_PIXEL_COLORS: u8 = 0x00;
const BROADCAST_CHANNEL: u8 = 0;

/// Describes an OPC Command.
#[derive (Clone, Debug, PartialEq)]
pub enum Command {
    /// Contains and array of RGB values: three bytes in red, green, blue order for each pixel to set.
    SetPixelColors {
        /// If the data block has length 3*n, then the first n pixels of the specified channel are set.
        /// All other pixels are unaffected and retain their current colour values.
        /// If the data length is not a multiple of 3, or there is data for more pixels than are present, the extra data is ignored.
        pixels: Vec<[u8; 3]>,
    },
    /// Used to send a message that is specific to a particular device or software system.
    SystemExclusive {
        /// The data block should begin with a two-byte system ID.
        id: [u8; 2],
        /// designers of that system are then free to define any message format for the rest of the data block.
        data: Vec<u8>,
    },
}

/// Describes a single message that follows the OPC protocol
#[derive (Clone, Debug, PartialEq)]
pub struct Message {
    /// Up to 255 separate strands of pixels can be controlled.
    /// Channel 0 are considered broadcast messages.
    /// Channels number from 1 to 255 are for each strand and listen for messages with that channel number.
    pub channel: u8,
    /// Designates the message type
    pub command: Command,
}

impl Message {
    /// Create new Message Instance from Pixel Array
    pub fn from_pixels(ch: u8, pixels: &[[u8; 3]]) -> Message {
        Message {
            channel: ch,
            command: Command::SetPixelColors { pixels: pixels.to_owned() },
        }
    }

    /// Create new Message Instance from Data Array
    pub fn from_data(ch: u8, id: &[u8; 2], data: &[u8]) -> Message {
        Message {
            channel: ch,
            command: Command::SystemExclusive {
                id: id.to_owned(),
                data: data.to_owned(),
            },
        }
    }

    /// Check Message Data Length
    pub fn len(&self) -> usize {
        match self.command {
            Command::SetPixelColors { ref pixels } => pixels.len() * 3,
            Command::SystemExclusive { id: _, ref data } => data.len() + 2,
        }
    }

    /// Check is Message has a valid size
    pub fn is_valid(&self) -> bool {
        self.len() <= MAX_MESSAGE_SIZE
    }

    /// Check if Message is a broadcast message
    pub fn is_broadcast(&self) -> bool {
        self.channel == BROADCAST_CHANNEL
    }
}

/// Open Pixel Codec Instance
///
/// See the `tokio-core::io::Codec` Trait on how to use as a transport
pub struct OpcCodec;

impl Decoder for OpcCodec {
    type Item = Message;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> io::Result<Option<Self::Item>> {

        let (msg, length) = {
            // Get Temporary Src
            let mut src = src.clone();

            // Check if buf length is more than 4;
            if src.len() < 4 {
                return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid Message Command"));
            };
            let mut buf = src.split_to(4).into_buf();

            let (channel, command) = (buf.get_u8(), buf.get_u8());
            let length = buf.get_u16::<BigEndian>() as usize;

            if src.len() < length {
                return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid Message Command"));
            }
            let mut buf = src.split_to(length).into_buf();

            let msg = match command {
                SET_PIXEL_COLORS => {
                    let pixels: Vec<_> = buf.bytes()[..length - (length % 3)]
                        .chunks(3)
                        .map(|chunk| [chunk[0], chunk[1], chunk[2]])
                        .collect();
                    Message {
                        channel: channel,
                        command: Command::SetPixelColors { pixels: pixels },
                    }
                }
                SYS_EXCLUSIVE => {
                    Message {
                        channel: channel,
                        command: Command::SystemExclusive {
                            id: [buf.get_u8(), buf.get_u8()],
                            data: buf.collect(),
                        },
                    }
                }
                // TODO: What to do if incorrect?
                _ => {
                    return Err(io::Error::new(io::ErrorKind::InvalidData,
                                              "Invalid Message Command"))
                }
            };

            (msg, length + 4)
        };

        // Advance
        src.split_to(length);
        Ok(Some(msg))
    }
}

impl Encoder for OpcCodec {
    type Item = Message;
    type Error = io::Error;

    fn encode(&mut self, msg: Self::Item, dst: &mut BytesMut) -> io::Result<()> {

        let ser_len = msg.len();
        dst.reserve(4 + ser_len);

        match msg.command {
            Command::SetPixelColors { pixels } => {

                // Insert Channel and Command
                dst.put_slice(&[msg.channel, SET_PIXEL_COLORS]);
                // Insert Data Length
                dst.put_u16::<BigEndian>(ser_len as u16);

                // Insert Data
                for pixel in pixels {
                    dst.put_slice(&pixel);
                }
            }
            Command::SystemExclusive { id, data } => {

                // Insert Channel and Command
                dst.put_slice(&[msg.channel, SYS_EXCLUSIVE]);
                // Insert Data Length
                dst.put_u16::<BigEndian>(ser_len as u16);

                // Insert Data
                dst.put_slice(&id);
                dst.put_slice(&data);
            }
        }

        Ok(())
    }
}

#[test]
fn should_roundtrip_pixel_command() {

    let mut codec = OpcCodec;
    let mut buf = BytesMut::new();
    let test_msg = Message {
        channel: 4,
        command: Command::SetPixelColors { pixels: vec![[9; 3]; 10] },
    };

    assert!(codec.encode(test_msg.clone(), &mut buf).is_ok());

    let recv_msg = codec.decode(&mut buf.into()).unwrap().unwrap();

    assert_eq!(test_msg, recv_msg);

}

#[test]
fn server_roundtrip_system_command() {

    let mut codec = OpcCodec;
    let mut buf = BytesMut::new();
    let test_msg = Message {
        channel: 4,
        command: Command::SystemExclusive {
            id: [0; 2],
            data: vec![8; 10],
        },
    };

    assert!(codec.encode(test_msg.clone(), &mut buf).is_ok());

    let recv_msg = codec.decode(&mut buf.into()).unwrap().unwrap();

    assert_eq!(test_msg, recv_msg);

}