Class: OpenC3::LincInterface

Inherits:
TcpipClientInterface show all
Defined in:
lib/openc3/interfaces/linc_interface.rb

Overview

Interface for connecting to Ball Aerospace LINC Labview targets

Constant Summary collapse

MAX_CONCURRENT_HANDSHAKES =

The maximum number of asynchronous commands we can wait for at a time. We don’t ever expect to get close to this but we need to limit it to ensure the Array doesn’t grow out of control.

1000

Constants included from Api

Api::DELAY_METRICS, Api::DURATION_METRICS, Api::SUBSCRIPTION_DELIMITER, Api::SUM_METRICS

Constants included from ApiShared

ApiShared::DEFAULT_TLM_POLLING_RATE

Constants included from Extract

Extract::SCANNING_REGULAR_EXPRESSION

Instance Attribute Summary

Attributes inherited from StreamInterface

#stream

Attributes inherited from Interface

#auto_reconnect, #bytes_read, #bytes_written, #cmd_routers, #cmd_target_names, #config_params, #connect_on_startup, #disable_disconnect, #interfaces, #name, #num_clients, #options, #packet_log_writer_pairs, #protocol_info, #read_count, #read_protocols, #read_queue_size, #read_raw_data, #read_raw_data_time, #reconnect_delay, #routers, #scheduler, #secrets, #state, #stored_packet_log_writer_pairs, #stream_log_pair, #target_names, #tlm_target_names, #write_count, #write_protocols, #write_queue_size, #written_raw_data, #written_raw_data_time

Instance Method Summary collapse

Methods inherited from StreamInterface

#connected?, #disconnect, #read_interface, #write_interface

Methods inherited from Interface

#_write, #add_protocol, #as_json, #connected?, #convert_data_to_packet, #convert_packet_to_data, #copy_to, #disconnect, #interface_cmd, #protocol_cmd, #read_allowed?, #read_interface, #read_interface_base, #set_option, #start_raw_logging, #stop_raw_logging, #write_allowed?, #write_interface, #write_interface_base, #write_raw, #write_raw_allowed?

Methods included from Api

#_build_cmd_output_string, #_cmd_implementation, #_get_item, #_limits_group, #_set_tlm_process_args, #_tlm_process_args, #_validate_tlm_type, #build_command, #cmd, #cmd_no_checks, #cmd_no_hazardous_check, #cmd_no_range_check, #cmd_raw, #cmd_raw_no_checks, #cmd_raw_no_hazardous_check, #cmd_raw_no_range_check, #config_tool_names, #connect_interface, #connect_router, #delete_config, #disable_limits, #disable_limits_group, #disconnect_interface, #disconnect_router, #enable_limits, #enable_limits_group, #get_all_command_names, #get_all_commands, #get_all_interface_info, #get_all_router_info, #get_all_settings, #get_all_target_info, #get_all_telemetry, #get_all_telemetry_names, #get_cmd_buffer, #get_cmd_cnt, #get_cmd_cnts, #get_cmd_hazardous, #get_cmd_time, #get_cmd_value, #get_command, #get_interface, #get_interface_names, #get_item, #get_limits, #get_limits_events, #get_limits_groups, #get_limits_set, #get_limits_sets, #get_metrics, #get_out_of_limits, #get_overall_limits_state, #get_overrides, #get_packet_derived_items, #get_packets, #get_parameter, #get_router, #get_router_names, #get_setting, #get_settings, #get_target, #get_target_interfaces, #get_target_names, #get_telemetry, #get_tlm_buffer, #get_tlm_cnt, #get_tlm_cnts, #get_tlm_packet, #get_tlm_values, #inject_tlm, #interface_cmd, #interface_protocol_cmd, #limits_enabled?, #list_configs, #list_settings, #load_config, #map_target_to_interface, #normalize_tlm, #offline_access_needed, #override_tlm, #router_cmd, #router_protocol_cmd, #save_config, #send_raw, #set_limits, #set_limits_set, #set_offline_access, #set_setting, #set_tlm, #start_raw_logging_interface, #start_raw_logging_router, #stash_all, #stash_delete, #stash_get, #stash_keys, #stash_set, #stop_raw_logging_interface, #stop_raw_logging_router, #subscribe_packets, #tlm, #tlm_formatted, #tlm_raw, #tlm_variable, #tlm_with_units

Constructor Details

#initialize(hostname, port, handshake_enabled = true, response_timeout = 5.0, read_timeout = nil, write_timeout = 5.0, length_bitoffset = 0, length_bitsize = 16, length_value_offset = 4, fieldname_guid = 'HDR_GUID', endianness = 'BIG_ENDIAN', fieldname_cmd_length = 'HDR_LENGTH') ⇒ LincInterface

Returns a new instance of LincInterface.



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 34

def initialize(
  hostname,
  port,
  handshake_enabled = true,
  response_timeout = 5.0,
  read_timeout = nil,
  write_timeout = 5.0,
  length_bitoffset = 0,
  length_bitsize = 16,
  length_value_offset = 4,
  fieldname_guid = 'HDR_GUID',
  endianness = 'BIG_ENDIAN',
  fieldname_cmd_length = 'HDR_LENGTH'
)
  # Initialize Super Class
  super(hostname, port, port, write_timeout, read_timeout, 'LENGTH',
    length_bitoffset, length_bitsize, length_value_offset, 1, endianness, 0, nil, nil)

  # Configuration Settings
  @handshake_enabled = ConfigParser.handle_true_false(handshake_enabled)
  @handshake_enableds = nil
  @response_timeout = response_timeout.to_f
  @length_value_offset = Integer(length_value_offset)
  @fieldname_guid = ConfigParser.handle_nil(fieldname_guid)
  @fieldname_cmd_length = ConfigParser.handle_nil(fieldname_cmd_length)

  # Other instance variables
  @ignored_error_codes = {}
  @handshake_cmds = []
  @handshakes_mutex = Mutex.new

  # Call this once now because the first time is slow
  UUIDTools::UUID.random_create.raw
end

Instance Method Details

#connectObject

def initialize



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 69

def connect
  # Packet definitions need to be retrieved here because @target_names is not filled in until after initialize
  unless @handshake_enableds
    @handshake_enableds = {}
    @target_names.each do |target_name|
      @handshake_enableds[target_name] = @handshake_enabled
      @ignored_error_codes[target_name] = []
    end
  end
  @handshake_packets = []
  @error_packets = []
  @error_ignore_commands = nil
  @error_handle_commands = nil
  @handshake_enable_commands = nil
  @handshake_disable_commands = nil

  @target_names.each do |target_name|
    @handshake_packets << System.telemetry.packet(target_name, 'HANDSHAKE')
    @error_packets << System.telemetry.packet(target_name, 'ERROR')

    # Handle not defining the interface configuration commands (Targets may not want to support this functionality)
    begin
      command = System.commands.packet(target_name, 'OPENC3_ERROR_IGNORE')
      @error_ignore_commands ||= []
      @error_ignore_commands << command
    rescue
    end
    begin
      command = System.commands.packet(target_name, 'OPENC3_ERROR_HANDLE')
      @error_handle_commands ||= []
      @error_handle_commands << command
    rescue
    end
    begin
      command = System.commands.packet(target_name, 'OPENC3_HANDSHAKE_EN')
      @handshake_enable_commands ||= []
      @handshake_enable_commands << command
    rescue
    end
    begin
      command = System.commands.packet(target_name, 'OPENC3_HANDSHAKE_DS')
      @handshake_disable_commands ||= []
      @handshake_disable_commands << command
    rescue
    end
  end

  @handshakes_mutex.synchronize do
    @handshake_cmds = []
  end

  # Actually connect
  super()
end

#get_guid(packet) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
# File 'lib/openc3/interfaces/linc_interface.rb', line 200

def get_guid(packet)
  if not packet.read(@fieldname_guid) =~ /[\x01-\xFF]/
    # The GUID has not been set already (it has all \x00 values), so make a new one.
    # This enables a router GUI to make the GUIDs so it can process handshakes too.
    guid = UUIDTools::UUID.random_create.raw
    packet.write(@fieldname_guid, guid, :RAW)
  else
    guid = packet.read(@fieldname_guid)
  end
  return guid
end

#handle_local_handshake(linc_handshake) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/openc3/interfaces/linc_interface.rb', line 301

def handle_local_handshake(linc_handshake)
  # Update the current value table for this command
  command = System.commands.packet(linc_handshake.identified_command.target_name, linc_handshake.identified_command.packet_name)
  command.received_time = linc_handshake.identified_command.received_time
  command.buffer = linc_handshake.identified_command.buffer
  command.received_count += 1

  # Put a log of the command onto the server for the user to see
  Logger.info("#{@name}: External Command: " + System.commands.format(linc_handshake.identified_command, System.targets[linc_handshake.identified_command.target_name].ignored_parameters))

  # Log the command to the command log(s)
  @packet_log_writer_pairs.each do |packet_log_writer_pair|
    packet_log_writer_pair.cmd_log_writer.write(linc_handshake.identified_command)
  end
end

#handle_remote_handshake(linc_handshake) ⇒ Object



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 317

def handle_remote_handshake(linc_handshake)
  # This is a remote packet (sent from here).
  # Add to the array of handshake packet responses
  # The mutex is required by the command task due to the way it
  # first looks up the handshake before removing it.
  @handshakes_mutex.synchronize do
    if @fieldname_guid
      # A GUID means it's an asychronous packet type.
      # So look at the list of incoming handshakes and pick off (deleting)
      # the handshake from the list if it's for this command.
      #
      # The mutex is required because the telemetry task
      # could enqueue a response between the index lookup and the slice
      # function which would remove the wrong response. FAIL!

      # Loop through all waiting commands to see if this handshake belongs to them
      this_handshake_guid = linc_handshake.get_cmd_guid(@fieldname_guid)
      handshake_cmd_index = @handshake_cmds.index { |hsc| hsc.get_cmd_guid == this_handshake_guid }

      # If command was waiting (ie the loop above found one), then remove it from waiters and signal it
      if handshake_cmd_index
        handshake_cmd = @handshake_cmds.slice!(handshake_cmd_index)
        handshake_cmd.got_your_handshake(linc_handshake)
      else
        # No command match found!  Either it gave up and timed out or this wasn't originated from here.
        # Ignore this typically.  This case here for clarity.
      end

    else
      # Synchronous version: just pop the array (pull the command off) and send it the handshake
      handshake_cmd = @handshakes_cmds.pop
      handshake_cmd.got_your_handshake(linc_handshake)
    end # of handshaking type check
  end
end

#linc_interface_command(packet) ⇒ Object



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 152

def linc_interface_command(packet)
  if @error_ignore_commands
    @error_ignore_commands.each do |error_ignore_command|
      if error_ignore_command.identify?(packet.buffer(false))
        linc_cmd = error_ignore_command.clone
        linc_cmd.buffer = packet.buffer
        code = linc_cmd.read('CODE')
        @ignored_error_codes[error_ignore_command.target_name] << code unless @ignored_error_codes[error_ignore_command.target_name].include? code
        return true
      end
    end
  end

  if @error_handle_commands
    @error_handle_commands.each do |error_handle_command|
      if error_handle_command.identify?(packet.buffer(false))
        linc_cmd = error_handle_command.clone
        linc_cmd.buffer = packet.buffer
        code = linc_cmd.read('CODE')
        @ignored_error_codes[error_handle_command.target_name].delete(code) if @ignored_error_codes[error_handle_command.target_name].include? code
        return true
      end
    end
  end

  if @handshake_enable_commands
    @handshake_enable_commands.each do |handshake_enable_command|
      if handshake_enable_command.identify?(packet.buffer(false))
        @handshake_enabled = true
        @handshake_enableds[handshake_enable_command.target_name] = true
        return true
      end
    end
  end

  if @handshake_disable_commands
    @handshake_disable_commands.each do |handshake_disable_command|
      if handshake_disable_command.identify?(packet.buffer(false))
        @handshake_enabled = false
        @handshake_enableds[handshake_disable_command.target_name] = false
        return true
      end
    end
  end

  return false
end

#process_handshake_results(handshake_cmd) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/openc3/interfaces/linc_interface.rb', line 262

def process_handshake_results(handshake_cmd)
  status = handshake_cmd.handshake.handshake.read('STATUS')
  code = handshake_cmd.handshake.handshake.read('CODE')
  source = handshake_cmd.handshake.error_source

  # Handle handshake warnings and errors
  if status == "OK" and code != 0
    unless @ignored_error_codes[handshake_cmd.handshake.handshake.target_name].include? code
      Logger.warn "#{@name}: Warning sending command (#{code}): #{source}"
    end
  elsif status == "ERROR"
    unless @ignored_error_codes[handshake_cmd.handshake.handshake.target_name].include? code
      raise "Error sending command (#{code}): #{source}"
    end
  end
end

#readObject



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/openc3/interfaces/linc_interface.rb', line 279

def read
  packet = super()
  if packet
    @handshake_packets.each do |handshake_packet|
      if handshake_packet.identify?(packet.buffer(false))
        handshake_packet = handshake_packet.clone
        handshake_packet.buffer = packet.buffer
        linc_handshake = LincHandshake.new(handshake_packet, handshake_packet.target_name)

        # Check for a local handshake
        if handshake_packet.read('origin') == "LCL"
          handle_local_handshake(linc_handshake)
        else
          handle_remote_handshake(linc_handshake) if @handshake_enableds[handshake_packet.target_name]
        end # if handshake_packet.read('origin') == "LCL"
      end # @handshake_packet.identify?(packet.buffer(false))
    end
  end # if packet

  return packet
end

#update_length_field(packet) ⇒ Object



212
213
214
215
# File 'lib/openc3/interfaces/linc_interface.rb', line 212

def update_length_field(packet)
  length = packet.length - @length_value_offset
  packet.write(@fieldname_cmd_length, length, :RAW)
end

#wait_for_response(packet, guid) ⇒ Object



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 217

def wait_for_response(packet, guid)
  # Check the number of commands waiting for handshakes.  This is just for sanity
  # If the number of commands waiting for handshakes is very large then it can't be real
  # So raise an error.  Something has gone horribly wrong.
  if @handshake_cmds.length > MAX_CONCURRENT_HANDSHAKES
    len = @handshake_cmds.length
    @handshake_cmds = []
    raise "The number of commands waiting for handshakes to #{len}. Clearing all commands!"
  end

  # Create a handshake command object and add it to the list of commands waiting
  handshake_cmd = LincHandshakeCommand.new(@handshakes_mutex, guid)
  @handshake_cmds.push(handshake_cmd)

  # wait for that handshake. This releases the mutex so that the telemetry and other commands can start running again.
  timed_out = handshake_cmd.wait_for_handshake(@response_timeout)
  # We now have the mutex again.  This interface is blocked for the rest of the command handling,
  # which should be quick because it's just checking variables and logging.
  # We want to hold the mutex during that so that the commands get logged in order of handshake from here.

  if timed_out
    # Clean this command out of the array of items that require handshakes.
    @handshake_cmds.delete_if { |hsc| hsc == handshake_cmd }
    raise "Timeout waiting for handshake from #{System.commands.format(packet, System.targets[packet.target_name].ignored_parameters)}"
  end

  process_handshake_results(handshake_cmd)
rescue Exception => err
  # If anything goes wrong after successfully writing the packet to the LINC target
  # ensure that the packet gets updated in the CVT and logged to the packet log writer.
  # OpenC3 normally only does this if write returns successfully
  if packet.identified?
    command = System.commands.packet(packet.target_name, packet.packet_name)
  else
    command = System.commands.packet('UNKNOWN', 'UNKNOWN')
  end
  command.buffer = packet.buffer

  @packet_log_writer_pairs.each do |packet_log_writer_pair|
    packet_log_writer_pair.cmd_log_writer.write(packet)
  end

  raise err
end

#write(packet) ⇒ Object



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
# File 'lib/openc3/interfaces/linc_interface.rb', line 124

def write(packet)
  return if linc_interface_command(packet)
  raise "Interface not connected" unless connected?()

  # Add a GUID to the GUID field if its defined
  # A GUID means it's an asychronous packet type.
  if @fieldname_guid
    guid = get_guid(packet)
  else
    # If @fieldname_guid is not defined (syncronous) we don't care what the
    # GUID is because we're not trying to match it up with anything.
    # As soon as we get a response we free the command.
    guid = 0
  end

  # Fix the length field to handle the cases where a variable length packet
  # is defined. OpenC3 does not do this automatically.
  update_length_field(packet) if @fieldname_cmd_length

  # Always take the mutex (even if we aren't handshaking)
  # We do not want any incoming telemetry to be missed because
  # it could be the handshake to this command.
  @handshakes_mutex.synchronize do
    super(packet) # Send the command
    wait_for_response(packet, guid) if @handshake_enableds[packet.target_name]
  end
end