arduino-2020-07-02-1009.py
01234567890123456789012345678901234567890123456789012345678901234567890123456789









4950515253545556575859606162636465666768697071727374757677787980818283848586878889








800801802803804805806807808809810811812813814815816817818819     820821822823824825826827828829830831832833834835836837838839








847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905











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





CONNECTION_FLAG_BLUETOOTH = 1
CONNECTION_FLAG_USB = 2
CONNECTION_FLAG_SIMULATED = 3
RASPBERRY_PI = psutil.sys.platform.title() == 'Linux'

SN_SERVO = '5583834303435111C1A0'
SERVO_CONNECTION = (CONNECTION_FLAG_BLUETOOTH, (2, '98:D3:11:FC:42:16', 1))

SN_REMOTE = '75835343130351802272'
REMOTE_CONNECTION = (CONNECTION_FLAG_BLUETOOTH, (1, '98:D3:91:FD:B3:C9', 1))

LASER_OFF = (False, False, False)
LASER_ALL = (True, True, True)
LASER_RED = (True, False, False)
LASER_GREEN = (False, True, False)
LASER_BLUE = (False, False, True)

LED_OFF = (0, 0, 0)
MAX_PWM = 255
GAMMA = 2.2

if SIMULATE_ARDUINO:
  SERVO_CONNECTION = (
      CONNECTION_FLAG_SIMULATED, (SERVO_SIMULATED_IN, SERVO_SIMULATED_OUT))
  REMOTE_CONNECTION = (
      CONNECTION_FLAG_SIMULATED, (REMOTE_SIMULATED_IN, REMOTE_SIMULATED_OUT))

KEY_NOT_PRESENT_STRING = 'N/A'

DISP_LAST_FLIGHT_NUMB_ORIG_DEST = 0
DISP_LAST_FLIGHT_AZIMUTH_ELEVATION = 1
DISP_FLIGHT_COUNT_LAST_SEEN = 2
DISP_RADIO_RANGE = 3
DISPLAY_MODE_NAMES = [
    'LAST_FLIGHT_NUMB_ORIG_DEST', 'LAST_FLIGHT_AZIMUTH_ELEVATION',
    'FLIGHT_COUNT_LAST_SEEN', 'RADIO_RANGE']

WRITE_DELAY_TIME = 0.2  # write to arduino every n seconds
READ_DELAY_TIME_SERVO = 1  # read from arduino every n seconds
READ_DELAY_TIME_REMOTE = 0.1  # read from arduino every n seconds




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






def HexColorToRGBTuple(hex_color):
  """Converts i.e.: #329a43 to (50, 154, 67)."""
  r = hex_color[1:3]
  g = hex_color[3:5]
  b = hex_color[5:7]
  return (int(r, 16), int(g, 16), int(b, 16))


def Gamma(c, gamma):
  """Converts a desired brightness 0..255 to a gamma-corrected PWM 0..255."""
  return round(((c / MAX_PWM) ** gamma) * MAX_PWM)


def GammaRGB(rgb, gamma):
  """Gamma converts an RGB tuple."""
  return Gamma(rgb[0], gamma), Gamma(rgb[1], gamma), Gamma(rgb[2], gamma)







def ServoMain(to_arduino_q, to_parent_q, shutdown):
  """Main servo controller for projecting the plane position on a hemisphere.

  Takes the latest flight from the to_arduino_q and converts that to the current
  azimuth and altitude of the plane on a hemisphere.
  """
  sys.stderr = open(messageboard.STDERR_FILE, 'a')

  Log('Process started with process id %d' % os.getpid())

  # Ensures that the child can exit if the parent exits unexpectedly
  # docs.python.org/2/library/multiprocessing.html
  # #multiprocessing.Queue.cancel_join_thread
  to_arduino_q.cancel_join_thread()
  to_parent_q.cancel_join_thread()

  #pylint: disable = bad-whitespace
  write_config = (
      ('azimuth',       'f'),  # 4 bytes
      ('altitude',      'f'),  # 4 bytes




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




  )
  #pylint: enable = bad-whitespace
  write_keys, write_format_tuple, write_format_string = SplitFormat(
      write_config)

  # write_format: azimuth, altitude, R, G, & B intensity
  # read heartbeat: millis
  link = Serial(
      *SERVO_CONNECTION, read_timeout=60,
      error_pin=messageboard.GPIO_ERROR_ARDUINO_SERVO_CONNECTION,
      to_parent_q=to_parent_q,
      read_format='l', write_format=write_format_string, name='Servo')
  link.Open()

  last_flight = {}
  flight, json_desc_dict, configuration, additional_attr = InitialMessageValues(
      to_arduino_q)
  next_read = 0
  next_write = 0
  now = GetNow(json_desc_dict, additional_attr)
  gamma = configuration['servo_rgb_gamma'] / 10  # gamma saved as whole number

  while not shutdown.value:
    SetLoggingGlobals(configuration)
    if not to_arduino_q.empty():
      flight, json_desc_dict, configuration, additional_attr = to_arduino_q.get(
          block=False)

      if 'test_servos_ordinal' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_ordinal')
        ServoTestOrdinal(link, write_keys, write_format_tuple)
      elif 'test_servos_sweep' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_sweep')
        ServoTestSweep(link, write_keys, write_format_tuple)
      elif 'test_servos_led' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_led')
        ServoTestLED(link, write_keys, write_format_tuple)

      gamma = configuration['servo_rgb_gamma']
      new_flight = DifferentFlights(flight, last_flight)
      if new_flight:
        Log('Flight changed from %s to %s' % (
            messageboard.DisplayFlightNumber(last_flight),
            messageboard.DisplayFlightNumber(flight)
        ), ser=link)

        # Turn off laser so line isn't traced while it moves to new position
        message_dict = GenerateServoMessage(laser=LASER_OFF)
        message_tuple = DictToValueTuple(
            message_dict, write_keys, write_format_tuple)
        link.Write(message_tuple)

      last_flight = flight

    if time.time() >= next_read:
      heartbeat = link.Read()  # simple ack message sent by servos
      next_read = time.time() + READ_DELAY_TIME_SERVO
      if heartbeat and VERBOSE:
        Log('Heartbeat read by Servo: %s' % str(heartbeat))




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





01234567890123456789012345678901234567890123456789012345678901234567890123456789









4950515253545556575859606162636465666768 6970717273747576777879808182838485868788








799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843








851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909











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





CONNECTION_FLAG_BLUETOOTH = 1
CONNECTION_FLAG_USB = 2
CONNECTION_FLAG_SIMULATED = 3
RASPBERRY_PI = psutil.sys.platform.title() == 'Linux'

SN_SERVO = '5583834303435111C1A0'
SERVO_CONNECTION = (CONNECTION_FLAG_BLUETOOTH, (2, '98:D3:11:FC:42:16', 1))

SN_REMOTE = '75835343130351802272'
REMOTE_CONNECTION = (CONNECTION_FLAG_BLUETOOTH, (1, '98:D3:91:FD:B3:C9', 1))

LASER_OFF = (False, False, False)
LASER_ALL = (True, True, True)
LASER_RED = (True, False, False)
LASER_GREEN = (False, True, False)
LASER_BLUE = (False, False, True)

LED_OFF = (0, 0, 0)
MAX_PWM = 255


if SIMULATE_ARDUINO:
  SERVO_CONNECTION = (
      CONNECTION_FLAG_SIMULATED, (SERVO_SIMULATED_IN, SERVO_SIMULATED_OUT))
  REMOTE_CONNECTION = (
      CONNECTION_FLAG_SIMULATED, (REMOTE_SIMULATED_IN, REMOTE_SIMULATED_OUT))

KEY_NOT_PRESENT_STRING = 'N/A'

DISP_LAST_FLIGHT_NUMB_ORIG_DEST = 0
DISP_LAST_FLIGHT_AZIMUTH_ELEVATION = 1
DISP_FLIGHT_COUNT_LAST_SEEN = 2
DISP_RADIO_RANGE = 3
DISPLAY_MODE_NAMES = [
    'LAST_FLIGHT_NUMB_ORIG_DEST', 'LAST_FLIGHT_AZIMUTH_ELEVATION',
    'FLIGHT_COUNT_LAST_SEEN', 'RADIO_RANGE']

WRITE_DELAY_TIME = 0.2  # write to arduino every n seconds
READ_DELAY_TIME_SERVO = 1  # read from arduino every n seconds
READ_DELAY_TIME_REMOTE = 0.1  # read from arduino every n seconds




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






def HexColorToRGBTuple(hex_color):
  """Converts i.e.: #329a43 to (50, 154, 67)."""
  r = hex_color[1:3]
  g = hex_color[3:5]
  b = hex_color[5:7]
  return (int(r, 16), int(g, 16), int(b, 16))


def Gamma(c, gamma):
  """Converts a desired brightness 0..255 to a gamma-corrected PWM 0..255."""
  return round(((c / MAX_PWM) ** gamma) * MAX_PWM)


def GammaRGB(rgb, gamma):
  """Gamma converts an RGB tuple."""
  return Gamma(rgb[0], gamma), Gamma(rgb[1], gamma), Gamma(rgb[2], gamma)


def GetGamma(configuration):
  """Returns gamma stored in configuration file."""
  return configuration['servo_rgb_gamma'] / 10  # gamma saved as whole number


def ServoMain(to_arduino_q, to_parent_q, shutdown):
  """Main servo controller for projecting the plane position on a hemisphere.

  Takes the latest flight from the to_arduino_q and converts that to the current
  azimuth and altitude of the plane on a hemisphere.
  """
  sys.stderr = open(messageboard.STDERR_FILE, 'a')

  Log('Process started with process id %d' % os.getpid())

  # Ensures that the child can exit if the parent exits unexpectedly
  # docs.python.org/2/library/multiprocessing.html
  # #multiprocessing.Queue.cancel_join_thread
  to_arduino_q.cancel_join_thread()
  to_parent_q.cancel_join_thread()

  #pylint: disable = bad-whitespace
  write_config = (
      ('azimuth',       'f'),  # 4 bytes
      ('altitude',      'f'),  # 4 bytes




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




  )
  #pylint: enable = bad-whitespace
  write_keys, write_format_tuple, write_format_string = SplitFormat(
      write_config)

  # write_format: azimuth, altitude, R, G, & B intensity
  # read heartbeat: millis
  link = Serial(
      *SERVO_CONNECTION, read_timeout=60,
      error_pin=messageboard.GPIO_ERROR_ARDUINO_SERVO_CONNECTION,
      to_parent_q=to_parent_q,
      read_format='l', write_format=write_format_string, name='Servo')
  link.Open()

  last_flight = {}
  flight, json_desc_dict, configuration, additional_attr = InitialMessageValues(
      to_arduino_q)
  next_read = 0
  next_write = 0
  now = GetNow(json_desc_dict, additional_attr)
  gamma = GetGamma(configuration)

  while not shutdown.value:
    SetLoggingGlobals(configuration)
    if not to_arduino_q.empty():
      flight, json_desc_dict, configuration, additional_attr = to_arduino_q.get(
          block=False)

      if 'test_servos_ordinal' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_ordinal')
        ServoTestOrdinal(link, write_keys, write_format_tuple)
      elif 'test_servos_sweep' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_sweep')
        ServoTestSweep(link, write_keys, write_format_tuple)
      elif 'test_servos_led' in configuration:
        messageboard.RemoveSetting(configuration, 'test_servos_led')
        ServoTestLED(link, write_keys, write_format_tuple)

      gamma = GetGamma(configuration)
      new_flight = DifferentFlights(flight, last_flight)
      if new_flight:
        Log('Flight changed from %s to %s' % (
            messageboard.DisplayFlightNumber(last_flight),
            messageboard.DisplayFlightNumber(flight)
        ), ser=link)

        # Turn off laser so line isn't traced while it moves to new position
        message_dict = GenerateServoMessage(laser=LASER_OFF)
        message_tuple = DictToValueTuple(
            message_dict, write_keys, write_format_tuple)
        link.Write(message_tuple)

      last_flight = flight

    if time.time() >= next_read:
      heartbeat = link.Read()  # simple ack message sent by servos
      next_read = time.time() + READ_DELAY_TIME_SERVO
      if heartbeat and VERBOSE:
        Log('Heartbeat read by Servo: %s' % str(heartbeat))




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