arduino-2020-06-03-1254.py
01234567890123456789012345678901234567890123456789012345678901234567890123456789









240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270 271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306








496497498499500501502503504505506507508509510511512513514515516517518  519520521522523524525526527528529530531532533534535536537538








121012111212121312141215121612171218121912201221122212231224122512261227122812291230 12311232123312341235123612371238



                            <----SKIPPED LINES---->




    self.reset_flag = True
    self.last_read = time.time()
    self.last_receipt = time.time()

  def Close(self, close_message):
    """Closes an open serial connection."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      return

    self.link.close()
    if self.error_pin:
      self.to_parent_q.put(('pin', (self.error_pin, True, close_message)))
    Log(close_message, self)

  def Available(self):
    """Calls self.link.available()."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      raise NotImplementedError('Not implemented for simulations')
    self.link.available()

  def Read(self, format_string=None):
    """Reads from an open serial.

    Reads from an open serial values as identified in the format_string provided here,
    or if not provided in this call, as saved on the Serial instance.  If an OSError
    exception is detected, or if this read, in failing to return non-empty results, means
    that the heartbeat timeout time has elapsed, this method will attempt to reopen
    the connection.

    Args:
      format_string: String of the form expected by struct.pack


    Returns:
      Tuple of values matching that as identified in format_string.
    """
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      if (
          self.__simulated_reads__ and
          time.time() - self.start_time > self.__simulated_reads__[0][0]):  # time for next
        next_line = self.__simulated_reads__.pop(0)
        return next_line[1]
      return ()

    if not format_string:
      format_string = self.read_format
    try:
      data = Read(self.link, format_string)
    except OSError as e:
      failure_message = 'Failed to read: %s' % e
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)
      return self.Read(format_string=format_string)
    self.last_read = time.time()
    if data:
      self.last_receipt = time.time()
      if LOG_SERIALS:
        ts = time.time() - self.start_time
        str_data = str(['%7.2f' % d if isinstance(d, float) else str(d) for d in data])
        with open(SERIALS_LOG, 'a') as f:
          f.write('%10.3f RECD@%s: %s\n' % (ts, self.name, str_data))
    if self.read_timeout and self.last_read - self.last_receipt > self.read_timeout:
      failure_message = 'Heartbeat not received in %.2f seconds (expected: %.2f)' % (
          self.last_read - self.last_receipt, self.read_timeout)
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)




                            <----SKIPPED LINES---->




      read_bytes = []
      for index in range(link.bytesRead):
        read_bytes.append(link.rxBuff[index])
  except (serial.SerialException, termios.error) as e:
    Log('Error in ReadBytes: %s' % e)
    read_bytes = []
  return read_bytes


def Unpack(read_bytes, format_string):
  """Unpacks a byte object into a tuple of values."""
  try:
    data = struct.unpack(format_string, bytearray(read_bytes))
  except struct.error as e:  # exception desc is missing some key detail, so re-raise
    raise struct.error(
        '%s but %d bytes provided (%s)' % (e, len(read_bytes), read_bytes))
  data = [str(d, 'ascii').split('\x00')[0] if isinstance(d, bytes) else d for d in data]
  return data


def Read(link, format_string):
  """Read and unpacks the bytes in one go."""
  read_bytes = ReadBytes(link)


  data = ()
  if read_bytes:
    data = Unpack(read_bytes, format_string)
  return data


def AzimuthAltitude(flight, now):
  """Provides current best-estimate location details given last known position.

  Given a flight dictionary, this determines the plane's best estimate for current
  location using its last-known position in the flight's lat / lon / speed / altitude /
  and track. Those attributes may have already been updated by messageboard using a
  more recently obtained radio signal from dump1090 than that in the canonical location,
  and if so, key flight_loc_now indicates the time at which those locations are current
  as of.

  Args:
    flight: dictionary of flight attributes.
    now: epoch indicating the timestamp for which the azimuth and altitude should be
      calculated.




                            <----SKIPPED LINES---->




      if 'test_remote' in configuration:
        messageboard.RemoveSetting(configuration, 'test_remote')

        def TestDisplayMode(m):
          SendRemoteMessage(
              flight, json_desc_dict, configuration, additional_attr,
              m, write_keys, write_format_tuple, link)
          time.sleep(1)

        TestDisplayMode(DISP_LAST_FLIGHT_NUMB_ORIG_DEST)
        TestDisplayMode(DISP_LAST_FLIGHT_AZIMUTH_ELEVATION)
        TestDisplayMode(DISP_FLIGHT_COUNT_LAST_SEEN)
        TestDisplayMode(DISP_RADIO_RANGE)

    if time.time() >= next_write:
      next_write = SendRemoteMessage(
          flight, json_desc_dict, configuration, additional_attr,
          display_mode, write_keys, write_format_tuple, link)

    if time.time() >= next_read:
      values_t = link.Read()  # simple ack message sent by servos

      values_d = dict(zip(read_keys, values_t))
      if values_d.get('confirmed'):
        Log(str(values_t) + '\n' + str(values_d))
        display_mode, low_batt = ExecuteArduinoCommand(
            values_d, configuration, display_mode, low_batt, to_parent_q, link)
      next_read = time.time() + READ_DELAY_TIME

  link.Close(SHUTDOWN_TEXT)

01234567890123456789012345678901234567890123456789012345678901234567890123456789









240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307








497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541








121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242



                            <----SKIPPED LINES---->




    self.reset_flag = True
    self.last_read = time.time()
    self.last_receipt = time.time()

  def Close(self, close_message):
    """Closes an open serial connection."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      return

    self.link.close()
    if self.error_pin:
      self.to_parent_q.put(('pin', (self.error_pin, True, close_message)))
    Log(close_message, self)

  def Available(self):
    """Calls self.link.available()."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      raise NotImplementedError('Not implemented for simulations')
    self.link.available()

  def Read(self, format_string=None, bytes_read=None):
    """Reads from an open serial.

    Reads from an open serial values as identified in the format_string provided here,
    or if not provided in this call, as saved on the Serial instance.  If an OSError
    exception is detected, or if this read, in failing to return non-empty results, means
    that the heartbeat timeout time has elapsed, this method will attempt to reopen
    the connection.

    Args:
      format_string: String of the form expected by struct.pack
      bytes_read: if passed, the bytes that are read are appended to the list.

    Returns:
      Tuple of values matching that as identified in format_string.
    """
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      if (
          self.__simulated_reads__ and
          time.time() - self.start_time > self.__simulated_reads__[0][0]):  # time for next
        next_line = self.__simulated_reads__.pop(0)
        return next_line[1]
      return ()

    if not format_string:
      format_string = self.read_format
    try:
      data = Read(self.link, format_string, bytes_read=bytes_read)
    except OSError as e:
      failure_message = 'Failed to read: %s' % e
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)
      return self.Read(format_string=format_string)
    self.last_read = time.time()
    if data:
      self.last_receipt = time.time()
      if LOG_SERIALS:
        ts = time.time() - self.start_time
        str_data = str(['%7.2f' % d if isinstance(d, float) else str(d) for d in data])
        with open(SERIALS_LOG, 'a') as f:
          f.write('%10.3f RECD@%s: %s\n' % (ts, self.name, str_data))
    if self.read_timeout and self.last_read - self.last_receipt > self.read_timeout:
      failure_message = 'Heartbeat not received in %.2f seconds (expected: %.2f)' % (
          self.last_read - self.last_receipt, self.read_timeout)
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)




                            <----SKIPPED LINES---->




      read_bytes = []
      for index in range(link.bytesRead):
        read_bytes.append(link.rxBuff[index])
  except (serial.SerialException, termios.error) as e:
    Log('Error in ReadBytes: %s' % e)
    read_bytes = []
  return read_bytes


def Unpack(read_bytes, format_string):
  """Unpacks a byte object into a tuple of values."""
  try:
    data = struct.unpack(format_string, bytearray(read_bytes))
  except struct.error as e:  # exception desc is missing some key detail, so re-raise
    raise struct.error(
        '%s but %d bytes provided (%s)' % (e, len(read_bytes), read_bytes))
  data = [str(d, 'ascii').split('\x00')[0] if isinstance(d, bytes) else d for d in data]
  return data


def Read(link, format_string, bytes_read=None):
  """Read and unpacks the bytes in one go."""
  read_bytes = ReadBytes(link)
  if isinstance(bytes_read, list):
    bytes_read.extend(read_bytes)
  data = ()
  if read_bytes:
    data = Unpack(read_bytes, format_string)
  return data


def AzimuthAltitude(flight, now):
  """Provides current best-estimate location details given last known position.

  Given a flight dictionary, this determines the plane's best estimate for current
  location using its last-known position in the flight's lat / lon / speed / altitude /
  and track. Those attributes may have already been updated by messageboard using a
  more recently obtained radio signal from dump1090 than that in the canonical location,
  and if so, key flight_loc_now indicates the time at which those locations are current
  as of.

  Args:
    flight: dictionary of flight attributes.
    now: epoch indicating the timestamp for which the azimuth and altitude should be
      calculated.




                            <----SKIPPED LINES---->




      if 'test_remote' in configuration:
        messageboard.RemoveSetting(configuration, 'test_remote')

        def TestDisplayMode(m):
          SendRemoteMessage(
              flight, json_desc_dict, configuration, additional_attr,
              m, write_keys, write_format_tuple, link)
          time.sleep(1)

        TestDisplayMode(DISP_LAST_FLIGHT_NUMB_ORIG_DEST)
        TestDisplayMode(DISP_LAST_FLIGHT_AZIMUTH_ELEVATION)
        TestDisplayMode(DISP_FLIGHT_COUNT_LAST_SEEN)
        TestDisplayMode(DISP_RADIO_RANGE)

    if time.time() >= next_write:
      next_write = SendRemoteMessage(
          flight, json_desc_dict, configuration, additional_attr,
          display_mode, write_keys, write_format_tuple, link)

    if time.time() >= next_read:
      bytes_read = []
      values_t = link.Read(bytes_read)
      values_d = dict(zip(read_keys, values_t))
      if values_d.get('confirmed'):
        Log(str(bytes_read) + '\n' + str(values_t) + '\n' + str(values_d))
        display_mode, low_batt = ExecuteArduinoCommand(
            values_d, configuration, display_mode, low_batt, to_parent_q, link)
      next_read = time.time() + READ_DELAY_TIME

  link.Close(SHUTDOWN_TEXT)