Class: OpenC3::BinaryAccessor

Inherits:
Accessor show all
Defined in:
lib/openc3/accessors/binary_accessor.rb,
ext/openc3/ext/structure/structure.c

Overview

Provides methods for binary reading and writing

Constant Summary collapse

PACK_8_BIT_INT =

Constants for ruby packing directives

'c'
PACK_NATIVE_16_BIT_INT =
's'
PACK_LITTLE_ENDIAN_16_BIT_UINT =
'v'
PACK_BIG_ENDIAN_16_BIT_UINT =
'n'
PACK_NATIVE_32_BIT_INT =
'l'
PACK_NATIVE_32_BIT_UINT =
'L'
PACK_NATIVE_64_BIT_INT =
'q'
PACK_NATIVE_64_BIT_UINT =
'Q'
PACK_LITTLE_ENDIAN_32_BIT_UINT =
'V'
PACK_BIG_ENDIAN_32_BIT_UINT =
'N'
PACK_LITTLE_ENDIAN_32_BIT_FLOAT =
'e'
PACK_LITTLE_ENDIAN_64_BIT_FLOAT =
'E'
PACK_BIG_ENDIAN_32_BIT_FLOAT =
'g'
PACK_BIG_ENDIAN_64_BIT_FLOAT =
'G'
PACK_NULL_TERMINATED_STRING =
'Z*'
PACK_BLOCK =
'a*'
PACK_8_BIT_INT_ARRAY =
'c*'
PACK_8_BIT_UINT_ARRAY =
'C*'
PACK_NATIVE_16_BIT_INT_ARRAY =
's*'
PACK_BIG_ENDIAN_16_BIT_UINT_ARRAY =
'n*'
PACK_LITTLE_ENDIAN_16_BIT_UINT_ARRAY =
'v*'
PACK_NATIVE_32_BIT_INT_ARRAY =
'l*'
PACK_BIG_ENDIAN_32_BIT_UINT_ARRAY =
'N*'
PACK_LITTLE_ENDIAN_32_BIT_UINT_ARRAY =
'V*'
PACK_NATIVE_64_BIT_INT_ARRAY =
'q*'
PACK_NATIVE_64_BIT_UINT_ARRAY =
'Q*'
PACK_LITTLE_ENDIAN_32_BIT_FLOAT_ARRAY =
'e*'
PACK_LITTLE_ENDIAN_64_BIT_FLOAT_ARRAY =
'E*'
PACK_BIG_ENDIAN_32_BIT_FLOAT_ARRAY =
'g*'
PACK_BIG_ENDIAN_64_BIT_FLOAT_ARRAY =
'G*'
MIN_INT8 =
MIN_INT8
MAX_INT8 =
MAX_INT8
MAX_UINT8 =
MAX_UINT8
MIN_INT16 =
MIN_INT16
MAX_INT16 =
MAX_INT16
MAX_UINT16 =
MAX_UINT16
MIN_INT32 =
MIN_INT32
MAX_INT32 =
MAX_INT32
MAX_UINT32 =
MAX_UINT32
MIN_INT64 =
MIN_INT64
MAX_INT64 =
MAX_INT64
MAX_UINT64 =
MAX_UINT64
ZERO_STRING =

Additional Constants

"\000"
DATA_TYPES =

Valid data types

[:INT, :UINT, :FLOAT, :STRING, :BLOCK]
OVERFLOW_TYPES =

Valid overflow types

[:TRUNCATE, :SATURATE, :ERROR, :ERROR_ALLOW_HEX]
HOST_ENDIANNESS =

Store the host endianness so that it only has to be determined once

get_host_endianness()
ENDIANNESS =

Valid endianess

[:BIG_ENDIAN, :LITTLE_ENDIAN]

Instance Attribute Summary

Attributes inherited from Accessor

#packet

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Accessor

#args, convert_to_type, #initialize, #read_items, read_items, #write_items, write_items

Constructor Details

This class inherits a constructor from OpenC3::Accessor

Class Method Details

.adjust_packed_size(num_bytes, packed) ⇒ Object

Adjusts the packed array to be the given number of bytes

Parameters:

  • num_bytes (Integer)

    The desired number of bytes

  • packed (Array)

    The packed data buffer



1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/openc3/accessors/binary_accessor.rb', line 1302

def self.adjust_packed_size(num_bytes, packed)
  difference = num_bytes - packed.length
  if difference > 0
    packed << (ZERO_STRING * difference)
  elsif difference < 0
    packed = packed[0..(packed.length - 1 + difference)]
  end
  packed
end

.byte_aligned(value) ⇒ Object



860
861
862
# File 'lib/openc3/accessors/binary_accessor.rb', line 860

def self.byte_aligned(value)
  (value % 8) == 0
end

.byte_swap_buffer(buffer, num_bytes_per_word) ⇒ String

Byte swaps every X bytes of data in a buffer into a new buffer

Parameters:

  • buffer (String)

    Buffer that will be copied then modified

  • num_bytes_per_word (Integer)

    Number of bytes per word that will be swapped

Returns:

  • (String)

    modified buffer



1333
1334
1335
1336
# File 'lib/openc3/accessors/binary_accessor.rb', line 1333

def self.byte_swap_buffer(buffer, num_bytes_per_word)
  buffer = buffer.clone
  self.byte_swap_buffer!(buffer, num_bytes_per_word)
end

.byte_swap_buffer!(buffer, num_bytes_per_word) ⇒ String

Byte swaps every X bytes of data in a buffer overwriting the buffer

Parameters:

  • buffer (String)

    Buffer to modify

  • num_bytes_per_word (Integer)

    Number of bytes per word that will be swapped

Returns:

  • (String)

    buffer passed in as a parameter



1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
# File 'lib/openc3/accessors/binary_accessor.rb', line 1317

def self.byte_swap_buffer!(buffer, num_bytes_per_word)
  num_swaps = buffer.length / num_bytes_per_word
  index = 0
  num_swaps.times do
    range = index..(index + num_bytes_per_word - 1)
    buffer[range] = buffer[range].reverse
    index += num_bytes_per_word
  end
  buffer
end

.check_bit_offset_and_size(read_or_write, given_bit_offset, given_bit_size, data_type, buffer) ⇒ Object

Check the bit size and bit offset for problems. Recalulate the bit offset and return back through the passed in pointer.



754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/openc3/accessors/binary_accessor.rb', line 754

def self.check_bit_offset_and_size(read_or_write, given_bit_offset, given_bit_size, data_type, buffer)
  bit_offset = given_bit_offset

  if (given_bit_size <= 0) && (data_type != :STRING) && (data_type != :BLOCK)
    raise(ArgumentError, "bit_size #{given_bit_size} must be positive for data types other than :STRING and :BLOCK")
  end

  if (given_bit_size <= 0) && (given_bit_offset < 0)
    raise(ArgumentError, "negative or zero bit_sizes (#{given_bit_size}) cannot be given with negative bit_offsets (#{given_bit_offset})")
  end

  if given_bit_offset < 0
    bit_offset = (buffer.length * 8) + bit_offset
    if bit_offset < 0
      raise_buffer_error(read_or_write, buffer, data_type, given_bit_offset, given_bit_size)
    end
  end

  return bit_offset
end

.check_bounds_and_buffer_size(bit_offset, bit_size, buffer_length, endianness, data_type) ⇒ Object

Calculate the bounds of the string to access the item based on the bit_offset and bit_size. Also determine if the buffer size is sufficient.



777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/openc3/accessors/binary_accessor.rb', line 777

def self.check_bounds_and_buffer_size(bit_offset, bit_size, buffer_length, endianness, data_type)
  result = true # Assume ok

  # Define bounds of string to access this item
  lower_bound = bit_offset / 8
  upper_bound = (bit_offset + bit_size - 1) / 8

  # Sanity check buffer size
  if upper_bound >= buffer_length
    # If it's not the special case of little endian bit field then we fail and return false
    if !((endianness == :LITTLE_ENDIAN) &&
           ((data_type == :INT) || (data_type == :UINT)) &&
           # Not byte aligned with an even bit size
           (!((byte_aligned(bit_offset)) && (even_bit_size(bit_size)))) &&
           (lower_bound < buffer_length)
        )
      result = false
    end
  end
  return result, lower_bound, upper_bound
end

.check_overflow(value, min_value, max_value, hex_max_value, bit_size, data_type, overflow) ⇒ Integer

Checks for overflow of an integer data type

Parameters:

  • value (Integer)

    Value to write into the buffer

  • min_value (Integer)

    Minimum allowed value

  • max_value (Integer)

    Maximum allowed value

  • hex_max_value (Integer)

    Maximum allowed value if specified in hex

  • bit_size (Integer)

    Size of the item in bits

  • data_type (Symbol)
  • overflow (Symbol)

Returns:

  • (Integer)

    Potentially modified value



1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
# File 'lib/openc3/accessors/binary_accessor.rb', line 1348

def self.check_overflow(value, min_value, max_value, hex_max_value, bit_size, data_type, overflow)
  if overflow == :TRUNCATE
    # Note this will always convert to unsigned equivalent for signed integers
    value = value % (hex_max_value + 1)
  else
    if value > max_value
      if overflow == :SATURATE
        value = max_value
      else
        if overflow == :ERROR or value > hex_max_value
          raise ArgumentError, "value of #{value} invalid for #{bit_size}-bit #{data_type}"
        end
      end
    elsif value < min_value
      if overflow == :SATURATE
        value = min_value
      else
        raise ArgumentError, "value of #{value} invalid for #{bit_size}-bit #{data_type}"
      end
    end
  end
  value
end

.check_overflow_array(values, min_value, max_value, hex_max_value, bit_size, data_type, overflow) ⇒ Array[Integer]

Checks for overflow of an array of integer data types

Parameters:

  • values (Array[Integer])

    Values to write into the buffer

  • min_value (Integer)

    Minimum allowed value

  • max_value (Integer)

    Maximum allowed value

  • hex_max_value (Integer)

    Maximum allowed value if specified in hex

  • bit_size (Integer)

    Size of the item in bits

  • data_type (Symbol)
  • overflow (Symbol)

Returns:

  • (Array[Integer])

    Potentially modified values



1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/openc3/accessors/binary_accessor.rb', line 1382

def self.check_overflow_array(values, min_value, max_value, hex_max_value, bit_size, data_type, overflow)
  if overflow != :TRUNCATE
    values.each_with_index do |value, index|
      values[index] = check_overflow(value, min_value, max_value, hex_max_value, bit_size, data_type, overflow)
    end
  end
  values
end

.even_bit_size(bit_size) ⇒ Object



864
865
866
# File 'lib/openc3/accessors/binary_accessor.rb', line 864

def self.even_bit_size(bit_size)
  (bit_size == 8) || (bit_size == 16) || (bit_size == 32) || (bit_size == 64)
end

.get_check_overflow_ranges(bit_size, data_type) ⇒ Object



799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/openc3/accessors/binary_accessor.rb', line 799

def self.get_check_overflow_ranges(bit_size, data_type)
  min_value = 0 # Default for UINT cases

  case bit_size
  when 8
    hex_max_value = MAX_UINT8
    if data_type == :INT
      min_value = MIN_INT8
      max_value = MAX_INT8
    else
      max_value = MAX_UINT8
    end
  when 16
    hex_max_value = MAX_UINT16
    if data_type == :INT
      min_value = MIN_INT16
      max_value = MAX_INT16
    else
      max_value = MAX_UINT16
    end
  when 32
    hex_max_value = MAX_UINT32
    if data_type == :INT
      min_value = MIN_INT32
      max_value = MAX_INT32
    else
      max_value = MAX_UINT32
    end
  when 64
    hex_max_value = MAX_UINT64
    if data_type == :INT
      min_value = MIN_INT64
      max_value = MAX_INT64
    else
      max_value = MAX_UINT64
    end
  else # Bitfield
    if data_type == :INT
      # Note signed integers must allow up to the maximum unsigned value to support values given in hex
      if bit_size > 1
        max_value = 2**(bit_size - 1)
        # min_value = -(2 ** bit_size - 1)
        min_value = -max_value
        # max_value = (2 ** bit_size - 1) - 1
        max_value -= 1
        # hex_max_value = (2 ** bit_size) - 1
        hex_max_value = (2**bit_size) - 1
      else # 1-bit signed
        min_value = -1
        max_value = 1
        hex_max_value = 1
      end
    else
      max_value = (2**bit_size) - 1
      hex_max_value = max_value
    end
  end

  return min_value, max_value, hex_max_value
end

.get_host_endiannessSymbol

Determines the endianness of the host running this code

This method is protected to force the use of the constant HOST_ENDIANNESS rather than this method

Returns:

  • (Symbol)

    :BIG_ENDIAN or :LITTLE_ENDIAN



94
95
96
97
98
99
100
101
102
103
# File 'lib/openc3/accessors/binary_accessor.rb', line 94

def self.get_host_endianness
  value = 0x01020304
  packed = [value].pack(PACK_NATIVE_32_BIT_UINT)
  unpacked = packed.unpack(PACK_LITTLE_ENDIAN_32_BIT_UINT)[0]
  if unpacked == value
    :LITTLE_ENDIAN
  else
    :BIG_ENDIAN
  end
end

.raise_buffer_error(read_write, buffer, data_type, given_bit_offset, given_bit_size) ⇒ Object

Raises:

  • (ArgumentError)


105
106
107
# File 'lib/openc3/accessors/binary_accessor.rb', line 105

def self.raise_buffer_error(read_write, buffer, data_type, given_bit_offset, given_bit_size)
  raise ArgumentError, "#{buffer.length} byte buffer insufficient to #{read_write} #{data_type} at bit_offset #{given_bit_offset} with bit_size #{given_bit_size}"
end

.read(param_bit_offset, param_bit_size, param_data_type, param_buffer, param_endianness) ⇒ Integer

Reads binary data of any data type from a buffer

Parameters:

  • bit_offset (Integer)

    Bit offset to the start of the item. A negative number means to offset from the end of the buffer.

  • bit_size (Integer)

    Size of the item in bits

  • data_type (Symbol)
  • buffer (String)

    Binary string buffer to read from

  • endianness (Symbol)

Returns:

  • (Integer)

    value read from the buffer



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/openc3/accessors/binary_accessor.rb', line 307

def self.read(bit_offset, bit_size, data_type, buffer, endianness)
  given_bit_offset = bit_offset
  given_bit_size = bit_size

  bit_offset = check_bit_offset_and_size(:read, given_bit_offset, given_bit_size, data_type, buffer)

  # If passed a negative bit size with strings or blocks
  # recalculate based on the buffer length
  if (bit_size <= 0) && ((data_type == :STRING) || (data_type == :BLOCK))
    bit_size = (buffer.length * 8) - bit_offset + bit_size
    if bit_size == 0
      return ""
    elsif bit_size < 0
      raise_buffer_error(:read, buffer, data_type, given_bit_offset, given_bit_size)
    end
  end

  result, lower_bound, upper_bound = check_bounds_and_buffer_size(bit_offset, bit_size, buffer.length, endianness, data_type)
  raise_buffer_error(:read, buffer, data_type, given_bit_offset, given_bit_size) unless result

  if (data_type == :STRING) || (data_type == :BLOCK)
    #######################################
    # Handle :STRING and :BLOCK data types
    #######################################

    if byte_aligned(bit_offset)
      if data_type == :STRING
        return buffer[lower_bound..upper_bound].unpack('Z*')[0]
      else
        return buffer[lower_bound..upper_bound].unpack('a*')[0]
      end
    else
      raise(ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}")
    end

  elsif (data_type == :INT) || (data_type == :UINT)
    ###################################
    # Handle :INT and :UINT data types
    ###################################

    if byte_aligned(bit_offset) && even_bit_size(bit_size)

      if data_type == :INT
        ###########################################################
        # Handle byte-aligned 8, 16, 32, and 64 bit :INT
        ###########################################################

        case bit_size
        when 8
          return buffer[lower_bound].unpack(PACK_8_BIT_INT)[0]
        when 16
          if endianness == HOST_ENDIANNESS
            return buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_16_BIT_INT)[0]
          else # endianness != HOST_ENDIANNESS
            temp = buffer[lower_bound..upper_bound].reverse
            return temp.unpack(PACK_NATIVE_16_BIT_INT)[0]
          end
        when 32
          if endianness == HOST_ENDIANNESS
            return buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_32_BIT_INT)[0]
          else # endianness != HOST_ENDIANNESS
            temp = buffer[lower_bound..upper_bound].reverse
            return temp.unpack(PACK_NATIVE_32_BIT_INT)[0]
          end
        when 64
          if endianness == HOST_ENDIANNESS
            return buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_64_BIT_INT)[0]
          else # endianness != HOST_ENDIANNESS
            temp = buffer[lower_bound..upper_bound].reverse
            return temp.unpack(PACK_NATIVE_64_BIT_INT)[0]
          end
        end
      else # data_type == :UINT
        ###########################################################
        # Handle byte-aligned 8, 16, 32, and 64 bit :UINT
        ###########################################################

        case bit_size
        when 8
          return buffer.getbyte(lower_bound)
        when 16
          if endianness == :BIG_ENDIAN
            return buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_16_BIT_UINT)[0]
          else # endianness == :LITTLE_ENDIAN
            return buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_16_BIT_UINT)[0]
          end
        when 32
          if endianness == :BIG_ENDIAN
            return buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_32_BIT_UINT)[0]
          else # endianness == :LITTLE_ENDIAN
            return buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_32_BIT_UINT)[0]
          end
        when 64
          if endianness == HOST_ENDIANNESS
            return buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_64_BIT_UINT)[0]
          else # endianness != HOST_ENDIANNESS
            temp = buffer[lower_bound..upper_bound].reverse
            return temp.unpack(PACK_NATIVE_64_BIT_UINT)[0]
          end
        end
      end

    else
      ##########################
      # Handle :INT and :UINT Bitfields
      ##########################

      # Extract Data for Bitfield
      if endianness == :LITTLE_ENDIAN
        # Bitoffset always refers to the most significant bit of a bitfield
        num_bytes = (((bit_offset % 8) + bit_size - 1) / 8) + 1
        upper_bound = bit_offset / 8
        lower_bound = upper_bound - num_bytes + 1

        if lower_bound < 0
          raise(ArgumentError, "LITTLE_ENDIAN bitfield with bit_offset #{given_bit_offset} and bit_size #{given_bit_size} is invalid")
        end

        temp_data = buffer[lower_bound..upper_bound].reverse
      else
        temp_data = buffer[lower_bound..upper_bound]
      end

      # Determine temp upper bound
      temp_upper = upper_bound - lower_bound

      # Handle Bitfield
      start_bits = bit_offset % 8
      start_mask = ~(0xFF << (8 - start_bits))
      total_bits = (temp_upper + 1) * 8
      right_shift = total_bits - start_bits - bit_size

      # Mask off unwanted bits at beginning
      temp = temp_data.getbyte(0) & start_mask

      if upper_bound > lower_bound
        # Combine bytes into a FixNum
        temp_data[1..temp_upper].each_byte do |temp_value|
          temp = temp << 8
          temp = temp + temp_value
        end
      end

      # Shift off unwanted bits at end
      temp = temp >> right_shift

      if data_type == :INT
        # Convert to negative if necessary
        if (bit_size > 1) && (temp[bit_size - 1] == 1)
          temp = -((1 << bit_size) - temp)
        end
      end

      return temp
    end

  elsif data_type == :FLOAT
    ##########################
    # Handle :FLOAT data type
    ##########################

    if byte_aligned(bit_offset)
      case bit_size
      when 32
        if endianness == :BIG_ENDIAN
          return buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_32_BIT_FLOAT)[0]
        else # endianness == :LITTLE_ENDIAN
          return buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_32_BIT_FLOAT)[0]
        end
      when 64
        if endianness == :BIG_ENDIAN
          return buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_64_BIT_FLOAT)[0]
        else # endianness == :LITTLE_ENDIAN
          return buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_64_BIT_FLOAT)[0]
        end
      else
        raise(ArgumentError, "bit_size is #{given_bit_size} but must be 32 or 64 for data_type #{data_type}")
      end
    else
      raise(ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}")
    end

  else
    ############################
    # Handle Unknown data types
    ############################

    raise(ArgumentError, "data_type #{data_type} is not recognized")
  end

  return return_value
end

.read_array(bit_offset, bit_size, data_type, array_size, buffer, endianness) ⇒ Array

Reads an array of binary data of any data type from a buffer

Parameters:

  • bit_offset (Integer)

    Bit offset to the start of the array. A negative number means to offset from the end of the buffer.

  • bit_size (Integer)

    Size of each item in the array in bits

  • data_type (Symbol)
  • array_size (Integer)

    Size in bits of the array. 0 or negative means fill the array with as many bit_size number of items that exist (negative means excluding the final X number of bits).

  • buffer (String)

    Binary string buffer to read from

  • endianness (Symbol)

Returns:

  • (Array)

    Array created from reading the buffer

Raises:

  • (ArgumentError)


883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
# File 'lib/openc3/accessors/binary_accessor.rb', line 883

def self.read_array(bit_offset, bit_size, data_type, array_size, buffer, endianness)
  # Save given values of bit offset, bit size, and array_size
  given_bit_offset = bit_offset
  given_bit_size = bit_size
  given_array_size = array_size

  # Handle negative and zero bit sizes
  raise ArgumentError, "bit_size #{given_bit_size} must be positive for arrays" if bit_size <= 0

  # Handle negative bit offsets
  if bit_offset < 0
    bit_offset = ((buffer.length * 8) + bit_offset)
    raise_buffer_error(:read, buffer, data_type, given_bit_offset, given_bit_size) if bit_offset < 0
  end

  # Handle negative and zero array sizes
  if array_size <= 0
    if given_bit_offset < 0
      raise ArgumentError, "negative or zero array_size (#{given_array_size}) cannot be given with negative bit_offset (#{given_bit_offset})"
    else
      array_size = ((buffer.length * 8) - bit_offset + array_size)
      if array_size == 0
        return []
      elsif array_size < 0
        raise_buffer_error(:read, buffer, data_type, given_bit_offset, given_bit_size)
      end
    end
  end

  # Calculate number of items in the array
  # If there is a remainder then we have a problem
  raise ArgumentError, "array_size #{given_array_size} not a multiple of bit_size #{given_bit_size}" if array_size % bit_size != 0

  num_items = array_size / bit_size

  # Define bounds of string to access this item
  lower_bound = bit_offset / 8
  upper_bound = (bit_offset + array_size - 1) / 8

  # Check for byte alignment
  byte_aligned = ((bit_offset % 8) == 0)

  case data_type
  when :STRING, :BLOCK
    #######################################
    # Handle :STRING and :BLOCK data types
    #######################################

    if byte_aligned
      value = []
      num_items.times do
        value << self.read(bit_offset, bit_size, data_type, buffer, endianness)
        bit_offset += bit_size
      end
    else
      raise ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}"
    end

  when :INT, :UINT
    ###################################
    # Handle :INT and :UINT data types
    ###################################

    if byte_aligned and (bit_size == 8 or bit_size == 16 or bit_size == 32 or bit_size == 64)
      ###########################################################
      # Handle byte-aligned 8, 16, 32, and 64 bit :INT and :UINT
      ###########################################################

      case bit_size
      when 8
        if data_type == :INT
          value = buffer[lower_bound..upper_bound].unpack(PACK_8_BIT_INT_ARRAY)
        else # data_type == :UINT
          value = buffer[lower_bound..upper_bound].unpack(PACK_8_BIT_UINT_ARRAY)
        end

      when 16
        if data_type == :INT
          if endianness == HOST_ENDIANNESS
            value = buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_16_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            temp = self.byte_swap_buffer(buffer[lower_bound..upper_bound], 2)
            value = temp.to_s.unpack(PACK_NATIVE_16_BIT_INT_ARRAY)
          end
        else # data_type == :UINT
          if endianness == :BIG_ENDIAN
            value = buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_16_BIT_UINT_ARRAY)
          else # endianness == :LITTLE_ENDIAN
            value = buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_16_BIT_UINT_ARRAY)
          end
        end

      when 32
        if data_type == :INT
          if endianness == HOST_ENDIANNESS
            value = buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_32_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            temp = self.byte_swap_buffer(buffer[lower_bound..upper_bound], 4)
            value = temp.to_s.unpack(PACK_NATIVE_32_BIT_INT_ARRAY)
          end
        else # data_type == :UINT
          if endianness == :BIG_ENDIAN
            value = buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_32_BIT_UINT_ARRAY)
          else # endianness == :LITTLE_ENDIAN
            value = buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_32_BIT_UINT_ARRAY)
          end
        end

      when 64
        if data_type == :INT
          if endianness == HOST_ENDIANNESS
            value = buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_64_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            temp = self.byte_swap_buffer(buffer[lower_bound..upper_bound], 8)
            value = temp.to_s.unpack(PACK_NATIVE_64_BIT_INT_ARRAY)
          end
        else # data_type == :UINT
          if endianness == HOST_ENDIANNESS
            value = buffer[lower_bound..upper_bound].unpack(PACK_NATIVE_64_BIT_UINT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            temp = self.byte_swap_buffer(buffer[lower_bound..upper_bound], 8)
            value = temp.to_s.unpack(PACK_NATIVE_64_BIT_UINT_ARRAY)
          end
        end
      end

    else
      ##################################
      # Handle :INT and :UINT Bitfields
      ##################################
      raise ArgumentError, "read_array does not support little endian bit fields with bit_size greater than 1-bit" if endianness == :LITTLE_ENDIAN and bit_size > 1

      value = []
      num_items.times do
        value << self.read(bit_offset, bit_size, data_type, buffer, endianness)
        bit_offset += bit_size
      end
    end

  when :FLOAT
    ##########################
    # Handle :FLOAT data type
    ##########################

    if byte_aligned
      case bit_size
      when 32
        if endianness == :BIG_ENDIAN
          value = buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_32_BIT_FLOAT_ARRAY)
        else # endianness == :LITTLE_ENDIAN
          value = buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_32_BIT_FLOAT_ARRAY)
        end

      when 64
        if endianness == :BIG_ENDIAN
          value = buffer[lower_bound..upper_bound].unpack(PACK_BIG_ENDIAN_64_BIT_FLOAT_ARRAY)
        else # endianness == :LITTLE_ENDIAN
          value = buffer[lower_bound..upper_bound].unpack(PACK_LITTLE_ENDIAN_64_BIT_FLOAT_ARRAY)
        end

      else
        raise ArgumentError, "bit_size is #{given_bit_size} but must be 32 or 64 for data_type #{data_type}"
      end

    else
      raise ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}"
    end

  else
    ############################
    # Handle Unknown data types
    ############################

    raise ArgumentError, "data_type #{data_type} is not recognized"
  end

  value
end

.read_item(item, buffer) ⇒ Object

Note: do not use directly - use instance read_item



278
279
280
281
282
283
284
285
# File 'lib/openc3/accessors/binary_accessor.rb', line 278

def self.read_item(item, buffer)
  return nil if item.data_type == :DERIVED
  if item.array_size
    return read_array(item.bit_offset, item.bit_size, item.data_type, item.array_size, buffer, item.endianness)
  else
    return read(item.bit_offset, item.bit_size, item.data_type, buffer, item.endianness)
  end
end

.write(value, param_bit_offset, param_bit_size, param_data_type, param_buffer, param_endianness, param_overflow) ⇒ Integer

Writes binary data of any data type to a buffer

Parameters:

  • bit_offset (Integer)

    Bit offset to the start of the item. A negative number means to offset from the end of the buffer.

  • bit_size (Integer)

    Size of the item in bits

  • data_type (Symbol)
  • buffer (String)

    Binary string buffer to read from

  • endianness (Symbol)

Returns:

  • (Integer)

    value read from the buffer



511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/openc3/accessors/binary_accessor.rb', line 511

def self.write(value, bit_offset, bit_size, data_type, buffer, endianness, overflow)
  given_bit_offset = bit_offset
  given_bit_size = bit_size

  bit_offset = check_bit_offset_and_size(:write, given_bit_offset, given_bit_size, data_type, buffer)

  # If passed a negative bit size with strings or blocks
  # recalculate based on the value length in bytes
  if (bit_size <= 0) && ((data_type == :STRING) || (data_type == :BLOCK))
    value = value.to_s
    bit_size = value.length * 8
  end

  result, lower_bound, upper_bound = check_bounds_and_buffer_size(bit_offset, bit_size, buffer.length, endianness, data_type)
  raise_buffer_error(:write, buffer, data_type, given_bit_offset, given_bit_size) if !result && (given_bit_size > 0)

  # Check overflow type
  if (overflow != :TRUNCATE) && (overflow != :SATURATE) && (overflow != :ERROR) && (overflow != :ERROR_ALLOW_HEX)
    raise(ArgumentError, "unknown overflow type #{overflow}")
  end

  if (data_type == :STRING) || (data_type == :BLOCK)
    #######################################
    # Handle :STRING and :BLOCK data types
    #######################################
    value = value.to_s

    if byte_aligned(bit_offset)
      temp = value
      if given_bit_size <= 0
        end_bytes = -(given_bit_size / 8)
        old_upper_bound = buffer.length - 1 - end_bytes
        # Lower bound + end_bytes can never be more than 1 byte outside of the given buffer
        if (lower_bound + end_bytes) > buffer.length
          raise_buffer_error(:write, buffer, data_type, given_bit_offset, given_bit_size)
        end

        if old_upper_bound < lower_bound
          # String was completely empty
          if end_bytes > 0
            # Preserve bytes at end of buffer
            buffer << ("\000" * value.length)
            buffer[lower_bound + value.length, end_bytes] = buffer[lower_bound, end_bytes]
          end
        elsif bit_size == 0
          # Remove entire string
          buffer[lower_bound, old_upper_bound - lower_bound + 1] = ''
        elsif upper_bound < old_upper_bound
          # Remove extra bytes from old string
          buffer[upper_bound + 1, old_upper_bound - upper_bound] = ''
        elsif (upper_bound > old_upper_bound) && (end_bytes > 0)
          # Preserve bytes at end of buffer
          diff = upper_bound - old_upper_bound
          buffer << ("\000" * diff)
          buffer[upper_bound + 1, end_bytes] = buffer[old_upper_bound + 1, end_bytes]
        end
      else # given_bit_size > 0
        byte_size = bit_size / 8
        if value.length < byte_size
          # Pad the requested size with zeros
          temp = value.ljust(byte_size, "\000")
        elsif value.length > byte_size
          if overflow == :TRUNCATE
            # Resize the value to fit the field
            value[byte_size, value.length - byte_size] = ''
          else
            raise(ArgumentError, "value of #{value.length} bytes does not fit into #{byte_size} bytes for data_type #{data_type}")
          end
        end
      end
      if bit_size != 0
        buffer[lower_bound, temp.length] = temp
      end
    else
      raise(ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}")
    end

  elsif (data_type == :INT) || (data_type == :UINT)
    ###################################
    # Handle :INT data type
    ###################################
    value = Integer(value)
    min_value, max_value, hex_max_value = get_check_overflow_ranges(bit_size, data_type)
    value = check_overflow(value, min_value, max_value, hex_max_value, bit_size, data_type, overflow)

    if byte_aligned(bit_offset) && even_bit_size(bit_size)
      ###########################################################
      # Handle byte-aligned 8, 16, 32, and 64 bit
      ###########################################################

      if data_type == :INT
        ###########################################################
        # Handle byte-aligned 8, 16, 32, and 64 bit :INT
        ###########################################################

        case bit_size
        when 8
          buffer.setbyte(lower_bound, value)
        when 16
          if endianness == HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_16_BIT_INT)
          else # endianness != HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_16_BIT_INT).reverse
          end
        when 32
          if endianness == HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_32_BIT_INT)
          else # endianness != HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_32_BIT_INT).reverse
          end
        when 64
          if endianness == HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_64_BIT_INT)
          else # endianness != HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_64_BIT_INT).reverse
          end
        end
      else # data_type == :UINT
        ###########################################################
        # Handle byte-aligned 8, 16, 32, and 64 bit :UINT
        ###########################################################

        case bit_size
        when 8
          buffer.setbyte(lower_bound, value)
        when 16
          if endianness == :BIG_ENDIAN
            buffer[lower_bound..upper_bound] = [value].pack(PACK_BIG_ENDIAN_16_BIT_UINT)
          else # endianness == :LITTLE_ENDIAN
            buffer[lower_bound..upper_bound] = [value].pack(PACK_LITTLE_ENDIAN_16_BIT_UINT)
          end
        when 32
          if endianness == :BIG_ENDIAN
            buffer[lower_bound..upper_bound] = [value].pack(PACK_BIG_ENDIAN_32_BIT_UINT)
          else # endianness == :LITTLE_ENDIAN
            buffer[lower_bound..upper_bound] = [value].pack(PACK_LITTLE_ENDIAN_32_BIT_UINT)
          end
        when 64
          if endianness == HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_64_BIT_UINT)
          else # endianness != HOST_ENDIANNESS
            buffer[lower_bound..upper_bound] = [value].pack(PACK_NATIVE_64_BIT_UINT).reverse
          end
        end
      end

    else
      ###########################################################
      # Handle bit fields
      ###########################################################

      # Extract Existing Data
      if endianness == :LITTLE_ENDIAN
        # Bitoffset always refers to the most significant bit of a bitfield
        num_bytes = (((bit_offset % 8) + bit_size - 1) / 8) + 1
        upper_bound = bit_offset / 8
        lower_bound = upper_bound - num_bytes + 1
        if lower_bound < 0
          raise(ArgumentError, "LITTLE_ENDIAN bitfield with bit_offset #{given_bit_offset} and bit_size #{given_bit_size} is invalid")
        end

        temp_data = buffer[lower_bound..upper_bound].reverse
      else
        temp_data = buffer[lower_bound..upper_bound]
      end

      # Determine temp upper bound
      temp_upper = upper_bound - lower_bound

      # Determine Values needed to Handle Bitfield
      start_bits = bit_offset % 8
      start_mask = (0xFF << (8 - start_bits))
      total_bits = (temp_upper + 1) * 8
      end_bits = total_bits - start_bits - bit_size
      end_mask = ~(0xFF << end_bits)

      # Add in Start Bits
      temp = temp_data.getbyte(0) & start_mask

      # Adjust value to correct number of bits
      temp_mask = (2**bit_size) - 1
      temp_value = value & temp_mask

      # Add in New Data
      temp = (temp << (bit_size - (8 - start_bits))) + temp_value

      # Add in Remainder of Existing Data
      temp = (temp << end_bits) + (temp_data.getbyte(temp_upper) & end_mask)

      # Extract into an array of bytes
      temp_array = []
      (0..temp_upper).each { temp_array.insert(0, (temp & 0xFF)); temp = temp >> 8 }

      # Store into data
      if endianness == :LITTLE_ENDIAN
        buffer[lower_bound..upper_bound] = temp_array.pack(PACK_8_BIT_UINT_ARRAY).reverse
      else
        buffer[lower_bound..upper_bound] = temp_array.pack(PACK_8_BIT_UINT_ARRAY)
      end

    end

  elsif data_type == :FLOAT
    ##########################
    # Handle :FLOAT data type
    ##########################
    value = Float(value)

    if byte_aligned(bit_offset)
      case bit_size
      when 32
        if endianness == :BIG_ENDIAN
          buffer[lower_bound..upper_bound] = [value].pack(PACK_BIG_ENDIAN_32_BIT_FLOAT)
        else # endianness == :LITTLE_ENDIAN
          buffer[lower_bound..upper_bound] = [value].pack(PACK_LITTLE_ENDIAN_32_BIT_FLOAT)
        end
      when 64
        if endianness == :BIG_ENDIAN
          buffer[lower_bound..upper_bound] = [value].pack(PACK_BIG_ENDIAN_64_BIT_FLOAT)
        else # endianness == :LITTLE_ENDIAN
          buffer[lower_bound..upper_bound] = [value].pack(PACK_LITTLE_ENDIAN_64_BIT_FLOAT)
        end
      else
        raise(ArgumentError, "bit_size is #{given_bit_size} but must be 32 or 64 for data_type #{data_type}")
      end
    else
      raise(ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}")
    end

  else
    ############################
    # Handle Unknown data types
    ############################

    raise(ArgumentError, "data_type #{data_type} is not recognized")
  end

  return value
end

.write_array(values, bit_offset, bit_size, data_type, array_size, buffer, endianness, overflow) ⇒ Array

Writes an array of binary data of any data type to a buffer

Parameters:

  • values (Array)

    Values to write into the buffer

  • bit_offset (Integer)

    Bit offset to the start of the array. A negative number means to offset from the end of the buffer.

  • bit_size (Integer)

    Size of each item in the array in bits

  • data_type (Symbol)
  • array_size (Integer)

    Size in bits of the array as represented in the buffer. Size 0 means to fill the buffer with as many bit_size number of items that exist (negative means excluding the final X number of bits).

  • buffer (String)

    Binary string buffer to write to

  • endianness (Symbol)

Returns:

  • (Array)

    values passed in as a parameter

Raises:

  • (ArgumentError)


1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/openc3/accessors/binary_accessor.rb', line 1075

def self.write_array(values, bit_offset, bit_size, data_type, array_size, buffer, endianness, overflow)
  # Save given values of bit offset, bit size, and array_size
  given_bit_offset = bit_offset
  given_bit_size = bit_size
  given_array_size = array_size

  # Verify an array was given
  raise ArgumentError, "values must be an Array type class is #{values.class}" unless values.kind_of? Array

  # Handle negative and zero bit sizes
  raise ArgumentError, "bit_size #{given_bit_size} must be positive for arrays" if bit_size <= 0

  # Handle negative bit offsets
  if bit_offset < 0
    bit_offset = ((buffer.length * 8) + bit_offset)
    raise_buffer_error(:write, buffer, data_type, given_bit_offset, given_bit_size) if bit_offset < 0
  end

  # Handle negative and zero array sizes
  if array_size <= 0
    if given_bit_offset < 0
      raise ArgumentError, "negative or zero array_size (#{given_array_size}) cannot be given with negative bit_offset (#{given_bit_offset})"
    else
      end_bytes = -(given_array_size / 8)
      lower_bound = bit_offset / 8
      upper_bound = (bit_offset + (bit_size * values.length) - 1) / 8
      old_upper_bound = buffer.length - 1 - end_bytes

      if upper_bound < old_upper_bound
        # Remove extra bytes from old buffer
        buffer[(upper_bound + 1)..old_upper_bound] = ''
      elsif upper_bound > old_upper_bound
        # Grow buffer and preserve bytes at end of buffer if necesssary
        buffer_length = buffer.length
        diff = upper_bound - old_upper_bound
        buffer << (ZERO_STRING * diff)
        if end_bytes > 0
          buffer[(upper_bound + 1)..(buffer.length - 1)] = buffer[(old_upper_bound + 1)..(buffer_length - 1)]
        end
      end

      array_size = ((buffer.length * 8) - bit_offset + array_size)
    end
  end

  # Get data bounds for this array
  lower_bound = bit_offset / 8
  upper_bound = (bit_offset + array_size - 1) / 8
  num_bytes   = upper_bound - lower_bound + 1

  # Check for byte alignment
  byte_aligned = ((bit_offset % 8) == 0)

  # Calculate the number of writes
  num_writes = array_size / bit_size
  # Check for a negative array_size and adjust the number of writes
  # to simply be the number of values in the passed in array
  if given_array_size <= 0
    num_writes = values.length
  end

  # Ensure the buffer has enough room
  if bit_offset + (num_writes * bit_size) > buffer.length * 8
    raise_buffer_error(:write, buffer, data_type, given_bit_offset, given_bit_size)
  end

  # Ensure the given_array_size is an even multiple of bit_size
  raise ArgumentError, "array_size #{given_array_size} not a multiple of bit_size #{given_bit_size}" if array_size % bit_size != 0

  raise ArgumentError, "too many values #{values.length} for given array_size #{given_array_size} and bit_size #{given_bit_size}" if num_writes < values.length

  # Check overflow type
  raise "unknown overflow type #{overflow}" unless OVERFLOW_TYPES.include?(overflow)

  case data_type
  when :STRING, :BLOCK
    #######################################
    # Handle :STRING and :BLOCK data types
    #######################################

    if byte_aligned
      num_writes.times do |index|
        self.write(values[index], bit_offset, bit_size, data_type, buffer, endianness, overflow)
        bit_offset += bit_size
      end
    else
      raise ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}"
    end

  when :INT, :UINT
    ###################################
    # Handle :INT and :UINT data types
    ###################################

    if byte_aligned and (bit_size == 8 or bit_size == 16 or bit_size == 32 or bit_size == 64)
      ###########################################################
      # Handle byte-aligned 8, 16, 32, and 64 bit :INT and :UINT
      ###########################################################

      case bit_size
      when 8
        if data_type == :INT
          values = self.check_overflow_array(values, MIN_INT8, MAX_INT8, MAX_UINT8, bit_size, data_type, overflow)
          packed = values.pack(PACK_8_BIT_INT_ARRAY)
        else # data_type == :UINT
          values = self.check_overflow_array(values, 0, MAX_UINT8, MAX_UINT8, bit_size, data_type, overflow)
          packed = values.pack(PACK_8_BIT_UINT_ARRAY)
        end

      when 16
        if data_type == :INT
          values = self.check_overflow_array(values, MIN_INT16, MAX_INT16, MAX_UINT16, bit_size, data_type, overflow)
          if endianness == HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_16_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_16_BIT_INT_ARRAY)
            self.byte_swap_buffer!(packed, 2)
          end
        else # data_type == :UINT
          values = self.check_overflow_array(values, 0, MAX_UINT16, MAX_UINT16, bit_size, data_type, overflow)
          if endianness == :BIG_ENDIAN
            packed = values.pack(PACK_BIG_ENDIAN_16_BIT_UINT_ARRAY)
          else # endianness == :LITTLE_ENDIAN
            packed = values.pack(PACK_LITTLE_ENDIAN_16_BIT_UINT_ARRAY)
          end
        end

      when 32
        if data_type == :INT
          values = self.check_overflow_array(values, MIN_INT32, MAX_INT32, MAX_UINT32, bit_size, data_type, overflow)
          if endianness == HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_32_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_32_BIT_INT_ARRAY)
            self.byte_swap_buffer!(packed, 4)
          end
        else # data_type == :UINT
          values = self.check_overflow_array(values, 0, MAX_UINT32, MAX_UINT32, bit_size, data_type, overflow)
          if endianness == :BIG_ENDIAN
            packed = values.pack(PACK_BIG_ENDIAN_32_BIT_UINT_ARRAY)
          else # endianness == :LITTLE_ENDIAN
            packed = values.pack(PACK_LITTLE_ENDIAN_32_BIT_UINT_ARRAY)
          end
        end

      when 64
        if data_type == :INT
          values = self.check_overflow_array(values, MIN_INT64, MAX_INT64, MAX_UINT64, bit_size, data_type, overflow)
          if endianness == HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_64_BIT_INT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_64_BIT_INT_ARRAY)
            self.byte_swap_buffer!(packed, 8)
          end
        else # data_type == :UINT
          values = self.check_overflow_array(values, 0, MAX_UINT64, MAX_UINT64, bit_size, data_type, overflow)
          if endianness == HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_64_BIT_UINT_ARRAY)
          else # endianness != HOST_ENDIANNESS
            packed = values.pack(PACK_NATIVE_64_BIT_UINT_ARRAY)
            self.byte_swap_buffer!(packed, 8)
          end
        end
      end

      # Adjust packed size to hold number of items written
      buffer[lower_bound..upper_bound] = adjust_packed_size(num_bytes, packed) if num_bytes > 0

    else
      ##################################
      # Handle :INT and :UINT Bitfields
      ##################################

      raise ArgumentError, "write_array does not support little endian bit fields with bit_size greater than 1-bit" if endianness == :LITTLE_ENDIAN and bit_size > 1

      num_writes.times do |index|
        self.write(values[index], bit_offset, bit_size, data_type, buffer, endianness, overflow)
        bit_offset += bit_size
      end
    end

  when :FLOAT
    ##########################
    # Handle :FLOAT data type
    ##########################

    if byte_aligned
      case bit_size
      when 32
        if endianness == :BIG_ENDIAN
          packed = values.pack(PACK_BIG_ENDIAN_32_BIT_FLOAT_ARRAY)
        else # endianness == :LITTLE_ENDIAN
          packed = values.pack(PACK_LITTLE_ENDIAN_32_BIT_FLOAT_ARRAY)
        end

      when 64
        if endianness == :BIG_ENDIAN
          packed = values.pack(PACK_BIG_ENDIAN_64_BIT_FLOAT_ARRAY)
        else # endianness == :LITTLE_ENDIAN
          packed = values.pack(PACK_LITTLE_ENDIAN_64_BIT_FLOAT_ARRAY)
        end

      else
        raise ArgumentError, "bit_size is #{given_bit_size} but must be 32 or 64 for data_type #{data_type}"
      end

      # Adjust packed size to hold number of items written
      buffer[lower_bound..upper_bound] = adjust_packed_size(num_bytes, packed) if num_bytes > 0

    else
      raise ArgumentError, "bit_offset #{given_bit_offset} is not byte aligned for data_type #{data_type}"
    end

  else
    ############################
    # Handle Unknown data types
    ############################
    raise ArgumentError, "data_type #{data_type} is not recognized"
  end # case data_type

  values
end

.write_item(item, value, buffer) ⇒ Object

Note: do not use directly - use instance write_item



288
289
290
291
292
293
294
295
# File 'lib/openc3/accessors/binary_accessor.rb', line 288

def self.write_item(item, value, buffer)
  return nil if item.data_type == :DERIVED
  if item.array_size
    return write_array(value, item.bit_offset, item.bit_size, item.data_type, item.array_size, buffer, item.endianness, item.overflow)
  else
    return write(value, item.bit_offset, item.bit_size, item.data_type, buffer, item.endianness, item.overflow)
  end
end

Instance Method Details

#enforce_derived_write_conversion(_item) ⇒ Object

If this is true it will enfore that COSMOS DERIVED items must have a write_conversion to be written



1413
1414
1415
# File 'lib/openc3/accessors/binary_accessor.rb', line 1413

def enforce_derived_write_conversion(_item)
  return true
end

#enforce_encodingObject

If this is set it will enforce that buffer data is encoded in a specific encoding



1393
1394
1395
# File 'lib/openc3/accessors/binary_accessor.rb', line 1393

def enforce_encoding
  return 'ASCII-8BIT'.freeze
end

#enforce_lengthObject

This affects whether the Packet class enforces the buffer length at all. Set to false to remove any correlation between buffer length and defined sizes of items in COSMOS



1400
1401
1402
# File 'lib/openc3/accessors/binary_accessor.rb', line 1400

def enforce_length
  return true
end

#enforce_short_buffer_allowedObject

This sets the short_buffer_allowed flag in the Packet class which allows packets that have a buffer shorter than the defined size. Note that the buffer is still resized to the defined length



1407
1408
1409
# File 'lib/openc3/accessors/binary_accessor.rb', line 1407

def enforce_short_buffer_allowed
  return false
end

#handle_read_variable_bit_size(item, _buffer) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/openc3/accessors/binary_accessor.rb', line 114

def handle_read_variable_bit_size(item, _buffer)
  length_value = @packet.read(item.variable_bit_size['length_item_name'], :CONVERTED)
  if item.array_size
    item.array_size = (length_value * item.variable_bit_size['length_bits_per_count']) + item.variable_bit_size['length_value_bit_offset']
  else
    if item.data_type == :INT or item.data_type == :UINT
      # QUIC encoding is currently assumed for individual variable sized integers
      # see https://datatracker.ietf.org/doc/html/rfc9000#name-variable-length-integer-enc
      case length_value
      when 0
        item.bit_size = 6
      when 1
        item.bit_size = 14
      when 2
        item.bit_size = 30
      else
        item.bit_size = 62
      end
    else
      item.bit_size = (length_value * item.variable_bit_size['length_bits_per_count']) + item.variable_bit_size['length_value_bit_offset']
    end
  end
end

#handle_write_variable_bit_size(item, value, buffer) ⇒ Object



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
# File 'lib/openc3/accessors/binary_accessor.rb', line 144

def handle_write_variable_bit_size(item, value, buffer)
  # Update length field to new size
  if (item.data_type == :INT or item.data_type == :UINT) and not item.original_array_size
    # QUIC encoding is currently assumed for individual variable sized integers
    # see https://datatracker.ietf.org/doc/html/rfc9000#name-variable-length-integer-enc

    # Calculate current bit size so we can preserve bytes after the item
    length_item_value = @packet.read(item.variable_bit_size['length_item_name'], :CONVERTED)
    case length_item_value
    when 0
      current_bit_size = 6
    when 1
      current_bit_size = 14
    when 2
      current_bit_size = 30
    when 3
      current_bit_size = 62
    else
      raise "Value #{item.variable_bit_size['length_item_name']} has unknown QUIC bit size encoding: #{length_item_value}"
    end

    if item.data_type == :UINT
      if value <= 63
        # Length = 0, value up to 6-bits
        new_bit_size = 6
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 0)
      elsif value <= 16383
        # Length = 1, value up to 14-bits
        new_bit_size = 14
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 1)
      elsif value <= 1073741823
        # Length = 2, value up to 30-bits
        new_bit_size = 30
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 2)
      else
        # Length = 3, value up to 62-bits
        new_bit_size = 62
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 3)
      end
    else
      if value <= 31 and value >= -32
        # Length = 0, value up to 6-bits
        new_bit_size = 6
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 0)
      elsif value <= 8191 and value >= -8192
        # Length = 1, value up to 14-bits
        new_bit_size = 14
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 1)
      elsif value <= 536870911 and value >= -536870912
        # Length = 2, value up to 30-bits
        new_bit_size = 30
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 2)
      else
        # Length = 3, value up to 62-bits
        new_bit_size = 62
        item.bit_size = new_bit_size
        @packet.write(item.variable_bit_size['length_item_name'], 3)
      end
    end

    # Later items need their bit_offset adjusted by the change in this item
    adjustment = new_bit_size - current_bit_size
    bytes = (adjustment / 8)
    item_offset = item.bit_offset / 8
    if bytes > 0
      original_length = buffer.length
      # Add extra bytes because we're adjusting larger
      buffer << ("\000" * bytes)
      # We added bytes to the end so now we have to shift the buffer over
      #   NOTE: buffer[offset, length]
      # We copy to the shifted offset location with the remaining buffer length
      buffer[item_offset + bytes, buffer.length - (item_offset + bytes)] =
          # We copy from the original offset location with the original length minus the offset
          buffer[item_offset, original_length - item_offset]
    elsif bytes < 0
      # Remove extra bytes because we're adjusting smaller
      buffer[item_offset + 1, -bytes] = ''
    end
  # Probably not possible to get this condition because we don't allow 0 sized floats
  # but check for it just to cover all the possible data_types
  elsif item.data_type == :FLOAT
    raise "Variable bit size not currently supported for FLOAT data type"
  else
    # STRING, BLOCK, or array types

    # Calculate current bit size so we can preserve bytes after the item
    length_item_value = @packet.read(item.variable_bit_size['length_item_name'], :CONVERTED)
    current_bit_size = (length_item_value * item.variable_bit_size['length_bits_per_count']) + item.variable_bit_size['length_value_bit_offset']

    # Calculate bits after this item
    bits_with_item = item.bit_offset + current_bit_size
    bits_after_item = (buffer.length * 8) - bits_with_item
    if item.original_array_size
      item.array_size = -bits_after_item
    else
      item.bit_size = -bits_after_item
    end

    new_bit_size = value.length * 8
    length_value = (new_bit_size - item.variable_bit_size['length_value_bit_offset']) / item.variable_bit_size['length_bits_per_count']
    @packet.write(item.variable_bit_size['length_item_name'], length_value)

    # Later items need their bit_offset adjusted by the change in this item
    adjustment = new_bit_size - current_bit_size
  end

  # Recalculate bit offsets after this item
  if adjustment != 0 and item.bit_offset >= 0
    @packet.sorted_items.each do |sitem|
      if sitem.data_type == :DERIVED or sitem.bit_offset < item.bit_offset
        # Skip items before this item and derived items and items with negative bit offsets
        next
      end
      if sitem != item
        sitem.bit_offset += adjustment
      end
    end
  end
end

#read_item(item, buffer) ⇒ Object



138
139
140
141
142
# File 'lib/openc3/accessors/binary_accessor.rb', line 138

def read_item(item, buffer)
  return nil if item.data_type == :DERIVED
  handle_read_variable_bit_size(item, buffer) if item.variable_bit_size
  self.class.read_item(item, buffer)
end

#write_item(item, value, buffer) ⇒ Object



271
272
273
274
275
# File 'lib/openc3/accessors/binary_accessor.rb', line 271

def write_item(item, value, buffer)
  return nil if item.data_type == :DERIVED
  handle_write_variable_bit_size(item, value, buffer) if item.variable_bit_size
  self.class.write_item(item, value, buffer)
end