arduino-2020-06-21-0915.py
01234567890123456789012345678901234567890123456789012345678901234567890123456789









4567891011121314151617181920212223 2425262728293031323334353637383940414243 4445464748495051525354555657585960616263








300301302303304305306307308309310311312313314315316317318319320 321322 323 324325     326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363 364365366367368369370371372373374375376377378379380381382  383384     385386387388389390391392393394395396397398399400401402403404











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




import os
import random
import struct
import subprocess
import sys
import termios
import time


import psutil
import serial
import serial.tools.list_ports
from pySerialTransfer import pySerialTransfer

from constants import (
    RASPBERRY_PI, MESSAGEBOARD_PATH, WEBSERVER_PATH, SHUTDOWN_TEXT)
import messageboard


ARDUINO_LOG = 'arduino_log.txt'

ARDUINO_ROLLING_LOG = 'secure/arduino_rolling_log.txt'
SERIALS_LOG = 'secure/arduino_serials_log.txt'
VERBOSE = False  # log additional fine-grained details into ARDUINO_LOG
LOG_SERIALS = False  # log serial data sent from Arduino to ARDUINO_LOG
SIMULATE_ARDUINO = False

REMOTE_DISPLAY_MODE = 'display_mode.txt'

SERVO_SIMULATED_IN = 'servo_in.txt'
SERVO_SIMULATED_OUT = 'servo_out.txt'
REMOTE_SIMULATED_IN = 'remote_in.txt'
REMOTE_SIMULATED_OUT = 'remote_out.txt'

if RASPBERRY_PI:
  ARDUINO_LOG = MESSAGEBOARD_PATH + ARDUINO_LOG
  SERVO_SIMULATED_OUT = MESSAGEBOARD_PATH + SERVO_SIMULATED_OUT
  SERVO_SIMULATED_IN = MESSAGEBOARD_PATH + SERVO_SIMULATED_IN
  REMOTE_SIMULATED_OUT = MESSAGEBOARD_PATH + REMOTE_SIMULATED_OUT
  REMOTE_SIMULATED_IN = MESSAGEBOARD_PATH + REMOTE_SIMULATED_IN
  REMOTE_DISPLAY_MODE = MESSAGEBOARD_PATH + REMOTE_DISPLAY_MODE


  ARDUINO_ROLLING_LOG = WEBSERVER_PATH + ARDUINO_ROLLING_LOG
  SERIALS_LOG = WEBSERVER_PATH + SERIALS_LOG

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)




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




        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)

    # on OSError, record a disconnection and attempt to reconnect & re-read
    except OSError as e:
      failure_message = 'Failed to read from %s: %s' % (self.name, 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])

        message = '%10.3f RECD@%s: %s\n' % (ts, self.name, str_data)

        with open(SERIALS_LOG, 'a') as f:
          f.write(message)






    # If we haven't received data (despite reading) in more than the timeout,
    # close and reopen.
    if (
        self.read_timeout and
        self.last_read - self.last_receipt > self.read_timeout):
      failure_message = (
          'Heartbeat not received in %.2f seconds (expected: %.2f) on %s' % (
              self.last_read - self.last_receipt, self.read_timeout, self.name))
      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)

    if self.read_timeout and VERBOSE:
      Log('%s: last_read: %.1f; last_receipt: %.1f; '
          'delta: %.1f; read_timeout: %.1f' % (
              self.name, self.last_read, self.last_receipt,
              self.last_read - self.last_receipt, self.read_timeout))
    elif VERBOSE:
      Log('%s: read_timeout: %s' % (self.name, self.read_timeout))

    return data

  def Write(self, values, format_string=None):
    """Writes to an open serial.

    Writes to 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, this method
    will attempt to reopen the connection.

    Args:
      values: tuple of values to send matching that as identified
        in format_string.
      format_string: String of the form expected by struct.pack
    """
    ts = time.time() - self.start_time

    str_values = str(
        ['%7.2f' % v if isinstance(v, float) else str(v) for v in values])
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      with open(self.connection_tuple[1], 'a') as f:
        f.write('%10.3f: %s\n' % (ts, str_values))
      return

    if not format_string:
      format_string = self.write_format
    try:
      Write(self.link, values, format_string)
    except OSError as e:
      failure_message = 'Failed to write: %s' % e
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)
      self.Write(values)
    if LOG_SERIALS:
      message = '%10.3f SENT@%s: %s\n' % (ts, self.name, str_values)


      with open(SERIALS_LOG, 'a') as f:
        f.write(message)






  def HasReset(self):
    """Indicates exactly once whether serial has reset since last called."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      raise NotImplementedError('Not implemented for simulations')

    flag = self.reset_flag
    self.reset_flag = False
    return flag


def RunCommand(cmd, sleep_seconds=1, log=True):
  """Runs shell command, checking if it completed within timeout."""
  conn = subprocess.Popen(cmd, shell=True)
  time.sleep(sleep_seconds)
  conn.poll()

  if conn.returncode is None:
    Log('ERROR: %s did not complete within %d seconds'
        % (cmd, sleep_seconds))




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





01234567890123456789012345678901234567890123456789012345678901234567890123456789









4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465








302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422











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




import os
import random
import struct
import subprocess
import sys
import termios
import time


import psutil
import serial
import serial.tools.list_ports
from pySerialTransfer import pySerialTransfer

from constants import (
    RASPBERRY_PI, MESSAGEBOARD_PATH, WEBSERVER_PATH, SHUTDOWN_TEXT)
import messageboard


ARDUINO_LOG = 'arduino_log.txt'
SERIALS_LOG = 'arduino_serials_log.txt'
ARDUINO_ROLLING_LOG = 'secure/arduino_rolling_log.txt'
ROLLING_SERIALS_LOG = 'secure/arduino_rolling_serials_log.txt'
VERBOSE = False  # log additional fine-grained details into ARDUINO_LOG
LOG_SERIALS = False  # log serial data sent from Arduino to ARDUINO_LOG
SIMULATE_ARDUINO = False

REMOTE_DISPLAY_MODE = 'display_mode.txt'

SERVO_SIMULATED_IN = 'servo_in.txt'
SERVO_SIMULATED_OUT = 'servo_out.txt'
REMOTE_SIMULATED_IN = 'remote_in.txt'
REMOTE_SIMULATED_OUT = 'remote_out.txt'

if RASPBERRY_PI:
  ARDUINO_LOG = MESSAGEBOARD_PATH + ARDUINO_LOG
  SERVO_SIMULATED_OUT = MESSAGEBOARD_PATH + SERVO_SIMULATED_OUT
  SERVO_SIMULATED_IN = MESSAGEBOARD_PATH + SERVO_SIMULATED_IN
  REMOTE_SIMULATED_OUT = MESSAGEBOARD_PATH + REMOTE_SIMULATED_OUT
  REMOTE_SIMULATED_IN = MESSAGEBOARD_PATH + REMOTE_SIMULATED_IN
  REMOTE_DISPLAY_MODE = MESSAGEBOARD_PATH + REMOTE_DISPLAY_MODE
  SERIALS_LOG = MESSAGEBOARD_PATH + SERIALS_LOG

  ARDUINO_ROLLING_LOG = WEBSERVER_PATH + ARDUINO_ROLLING_LOG
  SERIALS_LOG = WEBSERVER_PATH + SERIALS_LOG

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)




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




        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)

    # on OSError, record a disconnection and attempt to reconnect & re-read
    except OSError as e:
      failure_message = 'Failed to read from %s: %s' % (self.name, 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:
        now = time.time()
        elapsed = now - self.start_time
        str_data = str(
            ['%7.2f' % d if isinstance(d, float) else str(d) for d in data])
        now_time = messageboard.EpochDisplayTime(now, '%d %H%M%S.%f')
        message = '%s %10.3f RECD@%s: %s\n' % (
            now_time, elapsed, self.name, str_data)
        with open(SERIALS_LOG, 'a') as f:
          f.write(message)
        messageboard.Tail(
            SERIALS_LOG,
            ROLLING_SERIALS_LOG,
            max_line_length=130,
            lines_to_keep=messageboard.ROLLING_LOG_SIZE)

    # If we haven't received data (despite reading) in more than the timeout,
    # close and reopen.
    if (
        self.read_timeout and
        self.last_read - self.last_receipt > self.read_timeout):
      failure_message = (
          'Heartbeat not received in %.2f seconds (expected: %.2f) on %s' % (
              self.last_read - self.last_receipt, self.read_timeout, self.name))
      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)

    if self.read_timeout and VERBOSE:
      Log('%s: last_read: %.1f; last_receipt: %.1f; '
          'delta: %.1f; read_timeout: %.1f' % (
              self.name, self.last_read, self.last_receipt,
              self.last_read - self.last_receipt, self.read_timeout))
    elif VERBOSE:
      Log('%s: read_timeout: %s' % (self.name, self.read_timeout))

    return data

  def Write(self, values, format_string=None):
    """Writes to an open serial.

    Writes to 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, this method
    will attempt to reopen the connection.

    Args:
      values: tuple of values to send matching that as identified
        in format_string.
      format_string: String of the form expected by struct.pack
    """
    now = time.time()
    elapsed = now - self.start_time
    str_values = str(
        ['%7.2f' % v if isinstance(v, float) else str(v) for v in values])
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      with open(self.connection_tuple[1], 'a') as f:
        f.write('%10.3f: %s\n' % (elapsed, str_values))
      return

    if not format_string:
      format_string = self.write_format
    try:
      Write(self.link, values, format_string)
    except OSError as e:
      failure_message = 'Failed to write: %s' % e
      if self.error_pin:
        self.to_parent_q.put(('pin', (self.error_pin, True, failure_message)))
      self.Reopen(log_message=failure_message)
      self.Write(values)
    if LOG_SERIALS:
      now_time = messageboard.EpochDisplayTime(now, '%d %H%M%S.%f')
      message = '%s %10.3f SENT@%s: %s\n' % (
          now_time, elapsed, self.name, str_values)
      with open(SERIALS_LOG, 'a') as f:
        f.write(message)
      messageboard.Tail(
          SERIALS_LOG,
          ROLLING_SERIALS_LOG,
          max_line_length=130,
          lines_to_keep=messageboard.ROLLING_LOG_SIZE)

  def HasReset(self):
    """Indicates exactly once whether serial has reset since last called."""
    if self.connection_type == CONNECTION_FLAG_SIMULATED:
      raise NotImplementedError('Not implemented for simulations')

    flag = self.reset_flag
    self.reset_flag = False
    return flag


def RunCommand(cmd, sleep_seconds=1, log=True):
  """Runs shell command, checking if it completed within timeout."""
  conn = subprocess.Popen(cmd, shell=True)
  time.sleep(sleep_seconds)
  conn.poll()

  if conn.returncode is None:
    Log('ERROR: %s did not complete within %d seconds'
        % (cmd, sleep_seconds))




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