Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.51 KB | None | 0 0
  1. require 'serialport'
  2.  
  3. class DMX
  4.     START_OF_MESSAGE = "\x7E"
  5.     SEND_DMX_LABEL   = "\x06"
  6.     START_OF_DATA    = "\x00"
  7.     END_OF_MESSAGE   = "\xE7"
  8.  
  9.     SERIAL_PORT_PARAMS = {
  10.         'baud' => 115_200,
  11.         'data_bits' => 8,
  12.         'stop_bits' => 2,
  13.         'parity' => SerialPort::NONE
  14.     }
  15.  
  16.     #
  17.     # Wikipedia says "A maximum-sized packet, which has 512 channels, takes
  18.     # approximately 23 ms to send, corresponding to a max refresh rate of ~44 Hz.
  19.     # For higher refresh rates, packets having fewer than 512 channels can be sent.
  20.     #
  21.     def initialize(path, channel_count)
  22.         raise ArgumentError.new("channel_count must be between 25 and 512") if (channel_count < 25 or channel_count > 512)
  23.  
  24.         @path, @channel_count = path, channel_count
  25.  
  26.         @port = SerialPort.new(@path, SERIAL_PORT_PARAMS)
  27.  
  28.         # Allocate a buffer once, so we don't continually produce garbage
  29.         @packet = "\0" * (@channel_count + 6)       # 6 bytes of START_OF_MESSAGE, etc.
  30.  
  31.         # Set the static values
  32.         payload_size = (@channel_count + 1)     # +1 for the start code
  33.  
  34.         @packet[0] = START_OF_MESSAGE
  35.         @packet[1] = SEND_DMX_LABEL
  36.         @packet[2] = (payload_size & 255).chr                   # LSB of size
  37.         @packet[3] = ((payload_size >> 8) & 255).chr    # MSB of size
  38.         @packet[4] = START_OF_DATA
  39.         # @channel_count bytes of DMX channels
  40.         @packet[4 + @channel_count + 1] = END_OF_MESSAGE
  41.     end
  42.  
  43.     def set(index, value)
  44.         raise ArgumentError.new("index out of range") if (index < 0 or index >= @channel_count)
  45.         @packet[5 + index] = value.chr
  46.     end
  47.  
  48.     def send
  49.         @port.write(@packet)
  50.     end
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement