Module: MessageTranslator

Included in:
GetBatteryLevelReply, GetCurrentProgramNameReply, OutputState, PlaySoundFile, PlayTone, StartProgram
Defined in:
lib/telegrams/commands/message_translator.rb

Constant Summary collapse

FILENAME_MAX_LENGTH =

15.3 + null terminator

20

Instance Method Summary collapse

Instance Method Details

#add_default_extension_if_missing(filename, default_extension) ⇒ Object



16
17
18
# File 'lib/telegrams/commands/message_translator.rb', line 16

def add_default_extension_if_missing(filename, default_extension)
  /.+\.[A-Za-z0-9]{3}$/.match(filename).nil? ? "#{filename}.#{default_extension}" : filename
end

#boolean_as_bytes(boolean) ⇒ Object



20
21
22
# File 'lib/telegrams/commands/message_translator.rb', line 20

def boolean_as_bytes(boolean)
  boolean ? [0xff] : [0x00]
end

#boolean_from_bytes(bytes) ⇒ Object



24
25
26
# File 'lib/telegrams/commands/message_translator.rb', line 24

def boolean_from_bytes(bytes)
  bytes == [0x00] ? false : true
end

#integer_as_bytes(integer, bytes_length) ⇒ Object



36
37
38
39
40
# File 'lib/telegrams/commands/message_translator.rb', line 36

def integer_as_bytes(integer, bytes_length)
 uword_byte_length = bytes_length
 bytes_string = integer.to_s(16).rjust(uword_byte_length, "0")
 [bytes_string].pack('H*').bytes.to_a.reverse # reverse because it's MSB
end

#integer_as_ulong_bytes(integer) ⇒ Object



32
33
34
# File 'lib/telegrams/commands/message_translator.rb', line 32

def integer_as_ulong_bytes(integer)
 integer_as_bytes(integer, 8) # (4 bytes as 2 digit hex values each)
end

#integer_as_uword_bytes(integer) ⇒ Object



28
29
30
# File 'lib/telegrams/commands/message_translator.rb', line 28

def integer_as_uword_bytes(integer)
 integer_as_bytes(integer, 4) # make sure number is 4 bytes, or 2, 2 digit hex values
end

#integer_from_bytes(bytes) ⇒ Object



42
43
44
# File 'lib/telegrams/commands/message_translator.rb', line 42

def integer_from_bytes(bytes)
  bytes.reverse.pack('C*').unpack('H*')[0].hex
end

#string_as_bytes(string, max_length = FILENAME_MAX_LENGTH) ⇒ Object



4
5
6
7
8
# File 'lib/telegrams/commands/message_translator.rb', line 4

def string_as_bytes(string, max_length=FILENAME_MAX_LENGTH)
  # pad out to max length with null characters and then
  # convert all to ASCIIZ (null-terminated ascii string)
  string.ljust(max_length, "\0").unpack('C*')
end

#string_from_bytes(bytes) ⇒ Object



10
11
12
13
14
# File 'lib/telegrams/commands/message_translator.rb', line 10

def string_from_bytes(bytes)
  # convert from ASCIIZ (null-terminated ascii), removing all the 
  # trailing null characters
  bytes.pack("C*").strip
end