Class: Cosmos::LincInterface

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

Overview

Interface for connecting to Ball Aerospace LINC Labview targets

Constant Summary collapse

MAX_CONCURRENT_HANDSHAKES =

The maximum number of handshake responses 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.

100

Constants included from Extract

Extract::SCANNING_REGULAR_EXPRESSION

Instance Attribute Summary

Attributes inherited from Interface

#auto_reconnect, #bytes_read, #bytes_written, #connect_on_startup, #disable_disconnect, #interfaces, #name, #num_clients, #packet_log_writer_pairs, #raw_logger_pair, #read_count, #read_queue_size, #reconnect_delay, #routers, #target_names, #thread, #write_count, #write_queue_size

Instance Method Summary collapse

Methods inherited from StreamInterface

#bytes_read, #bytes_read=, #bytes_written, #bytes_written=, #connected?, #disconnect, #post_read_data, #post_read_packet, #pre_write_packet, #write_raw

Methods inherited from Interface

#connected?, #copy_to, #disconnect, #post_identify_packet, #read_allowed?, #start_raw_logging, #stop_raw_logging, #write_allowed?, #write_raw, #write_raw_allowed?

Methods included from Api

#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, #connect_interface, #connect_router, #disable_limits, #disable_limits_group, #disconnect_interface, #disconnect_router, #enable_limits, #enable_limits_group, #get_cmd_hazardous, #get_cmd_list, #get_cmd_log_filename, #get_cmd_param_list, #get_interface_names, #get_limits, #get_limits_event, #get_limits_groups, #get_limits_set, #get_limits_sets, #get_out_of_limits, #get_overall_limits_state, #get_packet_data, #get_router_names, #get_server_message_log_filename, #get_target_list, #get_tlm_details, #get_tlm_item_list, #get_tlm_list, #get_tlm_log_filename, #get_tlm_packet, #get_tlm_values, #interface_state, #limits_enabled?, #map_target_to_interface, #router_state, #send_raw, #set_limits, #set_limits_set, #set_tlm, #set_tlm_raw, #start_cmd_log, #start_logging, #start_new_server_message_log, #start_raw_logging_interface, #start_raw_logging_router, #start_tlm_log, #stop_cmd_log, #stop_logging, #stop_raw_logging_interface, #stop_raw_logging_router, #stop_tlm_log, #subscribe_limits_events, #subscribe_packet_data, #tlm, #tlm_formatted, #tlm_raw, #tlm_variable, #tlm_with_units, #unsubscribe_limits_events, #unsubscribe_packet_data

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.



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

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)
  @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 = []
  @handshakes = []
  @handshakes_mutex = Mutex.new
  @handshakes_resource = ConditionVariable.new

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

Instance Method Details

#connectObject

def initialize



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

def connect
  # Packet definitions need to be retrieved here because @target_names is not filled in until after initialize
  @handshake_packet = System.telemetry.packet(@target_names[0], 'HANDSHAKE')
  @error_packet = System.telemetry.packet(@target_names[0], 'ERROR')

  # Handle not defining the interface configuration commands (May not want to support this functionality)
  begin
    @error_ignore_command = nil
    @error_ignore_command = System.commands.packet(@target_names[0], 'COSMOS_ERROR_IGNORE')
  rescue
  end
  begin
    @error_handle_command = nil
    @error_handle_command = System.commands.packet(@target_names[0], 'COSMOS_ERROR_HANDLE')
  rescue
  end
  begin
    @handshake_enable_command = nil
    @handshake_enable_command = System.commands.packet(@target_names[0], 'COSMOS_HANDSHAKE_EN')
  rescue
  end
  begin
    @handshake_disable_command = nil
    @handshake_disable_command = System.commands.packet(@target_names[0], 'COSMOS_HANDSHAKE_DS')
  rescue
  end

  @handshakes_mutex.synchronize do
    @handshakes = []
  end

  # Actually connect
  super()
end

#readObject

def write



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

def read
  packet = super()
  if packet
    if @handshake_packet.identify?(packet.buffer(false))
      handshake_packet = @handshake_packet.clone
      handshake_packet.buffer = packet.buffer
      my_handshake = LincHandshake.new(handshake_packet, @target_names[0])

      if handshake_packet.read('origin') == "LCL"
        # Update the current value table for this command
        command = System.commands.packet(my_handshake.identified_command.target_name, my_handshake.identified_command.packet_name)
        command.received_time = my_handshake.identified_command.received_time
        command.buffer = my_handshake.identified_command.buffer
        command.received_count += 1

        # Put a log of the command onto the server for the user to see
        Logger.info("External Command: " + System.commands.format(my_handshake.identified_command, System.targets[@target_names[0]].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(my_handshake.identified_command)
        end
      else
        # This is a remote packet (sent from here).
        # Add to the array of handshake packet responses (only if handshakes are enabled).
        # The mutex is required by the command task due to the way it
        # first looks up the handshake before removing it.
        if @handshake_enabled
          @handshakes_mutex.synchronize do
            @handshakes.push(my_handshake)
            if @handshakes.length > MAX_CONCURRENT_HANDSHAKES
              len = @handshakes.length
              @handshakes = []
              raise "The handshakes response array has grown to #{len}. Clearing all handshakes!"
            end
            # Tell all waiting commands to take a look
            @handshakes_resource.broadcast
          end # @handshakes_mutex.synchronize
        end # if @handshake_enabled

      end # if handshake_packet.read('origin') == "LCL"
    end # @handshake_packet.identify?(packet.buffer(false))
  end # if packet

  return packet
end

#write(packet) ⇒ Object



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

def write(packet)
  ######################################
  # Commands handled in the COSMOS interface not the LINC target
  ######################################

  if @error_ignore_command and @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 << code unless @ignored_error_codes.include? code
    return
  end

  if @error_handle_command and @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.delete(code) if @ignored_error_codes.include? code
    return
  end

  if @handshake_enable_command and @handshake_enable_command.identify?(packet.buffer(false))
    @handshake_enabled = true
    return
  end

  if @handshake_disable_command and @handshake_disable_command.identify?(packet.buffer(false))
    @handshake_enabled = false
    return
  end

  # Verify we are connected to the LINC target
  if connected?()
    # Add a GUID to the GUID field if its defined
    if @fieldname_guid
      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.
        my_guid = UUIDTools::UUID.random_create.raw
        packet.write(@fieldname_guid, my_guid, :RAW)
      else
        my_guid = packet.read(@fieldname_guid)
      end
    end

    # Fix the length field to handle the cases where a variable length packet
    # is defined. COSMOS does not do this automatically.
    if @fieldname_cmd_length
      my_length = packet.length - @length_value_offset
      packet.write(@fieldname_cmd_length, my_length, :RAW)
    end

    # Always take the mutex (even if we aren't handshaking)
    @handshakes_mutex.synchronize do

      # Send the command
      super(packet)

      # Wait for the response if handshaking
      if @handshake_enabled
        begin
          my_handshake = nil

          # The time after which we will give up waiting for a response
          deadline = Time.now + @response_timeout

          # Loop until we find our response
          while my_handshake.nil?
            # How long should we wait in this loop. We could get notified
            # multiple times for handshakes that aren't ours so we need to
            # recalculate the wait time each time.
            to_wait = deadline - Time.now

            # If there is no more time to wait then this is a timeout so we break
            # out of the loop looking for handshakes
            if to_wait <= 0
              raise "Timeout waiting for handshake from #{System.commands.format(packet, System.targets[@target_names[0]].ignored_parameters)}"
            end

            # Wait until the telemetry side signals that there is a new handshake to check or timeout.
            # This releases the mutex until the telemetry side signals us
            @handshakes_resource.wait(@handshakes_mutex, to_wait)
            # We now have the mutex again

            # Loop if we have timed out so we can handle the timeout with common code
            next if (deadline - Time.now) <= 0

            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!
              my_handshake_index = @handshakes.index {|hs| hs.get_cmd_guid(@fieldname_guid) == my_guid}
              my_handshake = @handshakes.slice!(my_handshake_index) if my_handshake_index
            else
              # This is the synchronous version
              my_handshake = @handshakes.pop
            end
          end # while my_handshake.nil?

          # Handle handshake warnings and errors
          if my_handshake.handshake.read('STATUS') == "OK" and my_handshake.handshake.read('CODE') != 0
            unless @ignored_error_codes.include? my_handshake.handshake.read('CODE')
              Logger.warn "Warning sending command (#{my_handshake.handshake.read('CODE')}): #{my_handshake.error_source}"
            end
          elsif my_handshake.handshake.read('STATUS') == "ERROR"
            unless @ignored_error_codes.include? my_handshake.handshake.read('CODE')
              raise "Error sending command (#{my_handshake.handshake.read('CODE')}): #{my_handshake.error_source}"
            end
          end
        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.
          # COSMOS 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
      end # if @handshake_enabled
    end # @handshakes_mutex.synchronize
  else
    raise "Interface not connected"
  end # if connected

end