Exemple #1
0
def main():

    _log = Logger("status test", Level.INFO)

    _log.info("status task run()")

    # read YAML configuration
    _loader = ConfigLoader(Level.INFO)
    filename = 'config.yaml'
    _config = _loader.configure(filename)

    _status = Status(_config, GPIO, Level.INFO)

    try:
        _status.blink(True)
        for i in range(10):
            _log.info("blinking...")
            time.sleep(1)
        _status.blink(False)

        _status.enable()
        time.sleep(5)

    except KeyboardInterrupt:
        _log.info('Ctrl-C caught: interrupted.')
    finally:
        _log.info("status task close()")
        _status.close()
Exemple #2
0
 def status(self):
     toast("Calculating...")
     status = Status()
     if status == "Good":
         SweetAlert().fire(
             "Good",
             type='success',
         )
     elif status == "Not bad":
         SweetAlert().fire(
             "Not bad",
             type='info'
         )
     elif status == "Bad":
         SweetAlert().fire(
             "Not bad",
             type='question'
         )
     elif status == "Very bad":
         SweetAlert().fire(
             "Very bad",
             type='warning'
         )
     elif status == "Not work":
         SweetAlert().fire(
             "Not work",
             type='failure'
         )
Exemple #3
0
def test_status():

    print(Fore.CYAN + "status task running...")
    # read YAML configuration
    _loader = ConfigLoader(Level.INFO)
    filename = 'config.yaml'
    _config = _loader.configure(filename)

    _status = Status(_config, Level.INFO)
    _status.blink(True)
    for i in range(5):
        print(Fore.CYAN + "blinking...")
        time.sleep(1)
    _status.blink(False)

    _status.enable()
    time.sleep(5)
    _status.close()
Exemple #4
0
 def __init__(self, level, config, switch, infrared_trio, motors, rgbmatrix,
              lidar, callback_shutdown):
     super().__init__()
     self._log = Logger('controller', level)
     self._config = config
     self._enable_self_shutdown = self._config['ros'].get(
         'enable_self_shutdown')
     self._switch = switch
     #       self._info = info
     self._infrared_trio = infrared_trio
     self._motors = motors
     self._rgbmatrix = rgbmatrix
     self._lidar = lidar
     self._callback_shutdown = callback_shutdown
     self._status = Status(GPIO, level)
     self._current_message = None
     self._standby = False
     self._log.debug('ready.')
Exemple #5
0
 def __init__(self, config, ifs, motors, callback_shutdown, level):
     super().__init__()
     self._log = Logger('controller', level)
     self._config = config
     self._enable_self_shutdown = self._config['ros'].get(
         'enable_self_shutdown')
     #       self._switch = switch
     self._ifs = ifs
     self._motors = motors
     self._port_motor = motors.get_motor(Orientation.PORT)
     self._port_pid = self._port_motor.get_pid_controller()
     self._stbd_motor = motors.get_motor(Orientation.STBD)
     self._stbd_pid = self._stbd_motor.get_pid_controller()
     self._callback_shutdown = callback_shutdown
     self._status = Status(config, GPIO, level)
     self._current_message = None
     self._standby = False
     self._enabled = True
     # behaviours .................................
     self._behaviours = Behaviours(motors, ifs, Level.INFO)
     self._roam_behaviour = RoamBehaviour(motors, Level.INFO)
     self._log.debug('ready.')
Exemple #6
0
def menu():
    """
    The main structure of the cli mode, this function prints the menu, 
    listens to the entries, makes the directions.
    """

    animation = [
        "[■□□□□□□□□□]", "[■■□□□□□□□□]", "[■■■□□□□□□□]", "[■■■■□□□□□□]",
        "[■■■■■□□□□□]", "[■■■■■■□□□□]", "[■■■■■■■□□□]", "[■■■■■■■■□□]",
        "[■■■■■■■■■□]", "[■■■■■■■■■■]"
    ]

    for i in range(len(animation)):
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i])
        sys.stdout.flush()

    while True:
        show_menu()
        choices_input = question_maker(mode="main")

        if choices_input == "pw":
            print_wallets()

        if choices_input == "w":
            wallet_selector()

        if choices_input == "cw":
            create_a_wallet()

        if choices_input == "dw":
            if "y" == input("Are you sure ? (y or n): "):
                delete_current_wallet()
        if choices_input == "sc":
            send_the_coin(input("Please write receiver adress: "),
                          input("Coin Amount (ex. 1.0): "),
                          getpass("Password: "******"gb":
            print_balance()
        if choices_input == "help":
            show_menu()
        if choices_input == "ndstart":
            ndstart(str(input("ip: ")), int(input("port: ")))
        if choices_input == "ndstop":
            ndstop()
        if choices_input == "ndconnect":
            ndconnect(str(input("node ip: ")), int(input("node port: ")))

        if choices_input == "ndconnectmixdb":
            ndconnectmixdb()
        if choices_input == "ndnewunl":
            save_new_unl_node(input("Please write ID of the node: "))
        if choices_input == "ndid":
            print(ndid())
        if choices_input == "testmodeon":
            test_mode(True)
        if choices_input == "testmodeoff":
            test_mode(False)
        if choices_input == "debugmodeon":
            debug_mode(True)
        if choices_input == "debugmodeoff":
            debug_mode(False)

        if choices_input == "exptrcsv":
            if export_the_transactions():
                print(
                    f"CSV file created in {MY_TRANSACTION_EXPORT_PATH} directory"
                )
            else:
                print("You have not a transaction")

        if choices_input == "returntrs":
            PrintTransactions()

        if choices_input == "getblock":
            if the_settings()["test_mode"]:
                CreateBlock()
            else:
                GetBlockFromOtherNode()

        if choices_input == "status":
            print(Status())

        if choices_input == "0":
            exit()
Exemple #7
0
def arguments():
    parser = argparse.ArgumentParser(
        description=
        "This is an open source decentralized application network. In this network, you can develop and publish decentralized applications. Use the menu (-m) or GUI to gain full control and use the node, operation, etc."
    )

    parser.add_argument('-pw',
                        '--printwallet',
                        action='store_true',
                        help='Print Wallets')

    parser.add_argument('-w', '--wallet', type=int, help='Change Wallet')

    parser.add_argument('-cw', '--createwallet', help='Create wallet')

    parser.add_argument('-dw',
                        '--deletewallet',
                        action='store_true',
                        help='Delete wallet')

    parser.add_argument('-gb',
                        '--getbalance',
                        action='store_true',
                        help='Get Balance')

    parser.add_argument('-ndnunl',
                        '--ndnewunl',
                        type=str,
                        help='Add new UNL node')

    parser.add_argument('-ndid',
                        '--ndid',
                        action='store_true',
                        help='Print my id')

    parser.add_argument('-tmon',
                        '--testmodeon',
                        action='store_true',
                        help='Test Mode On')
    parser.add_argument('-tmoff',
                        '--testmodeoff',
                        action='store_true',
                        help='Test Mode Off')

    parser.add_argument('-dmon',
                        '--debugmodeon',
                        action='store_true',
                        help='Debug Mode On')
    parser.add_argument('-dmoff',
                        '--debugmodeoff',
                        action='store_true',
                        help='Debug Mode Off')

    parser.add_argument('-exptrcsv',
                        '--exporttransactioncsv',
                        action='store_true',
                        help='Exports the transaction as csv')

    parser.add_argument('-returntrans',
                        '--returntransactions',
                        action='store_true',
                        help='Exports the transaction as csv')

    parser.add_argument('-st',
                        '--status',
                        action='store_true',
                        help='Exports the transaction as csv')

    parser.add_argument('-m',
                        '--menu',
                        action='store_true',
                        help='An optional boolean for open the menu.')

    args = parser.parse_args()

    if len(sys.argv) < 2:
        parser.print_help()

    if args.printwallet:
        print_wallets()

    if not args.wallet is None:
        wallet_selector(args.wallet)

    if not args.createwallet is None:
        create_a_wallet(args.createwallet)

    if args.deletewallet:
        delete_current_wallet()

    if args.getbalance:
        print_balance()

    if not args.ndnewunl is None:
        save_new_unl_node(args.ndnewunl)

    if args.ndid:
        print(ndid())

    if args.testmodeon:
        test_mode(True)
    if args.testmodeoff:
        test_mode(False)
    if args.debugmodeon:
        debug_mode(True)
    if args.debugmodeoff:
        debug_mode(False)

    if args.exporttransactioncsv:
        if export_the_transactions():
            print(
                f"CSV file created in {MY_TRANSACTION_EXPORT_PATH} directory")
        else:
            print("You have not a transaction")

    if args.returntransactions:
        PrintTransactions()

    if args.status:
        print(Status())

    if args.menu:
        menu()
Exemple #8
0
from time import sleep
from lib.check import check
from lib.status import Status
from config import PINGS_BREAK_ONLINE, PINGS_BREAK_OFFLINE

if __name__ == "__main__":
    print("Starting...")

    connection_status = Status()

    while True:
        spleep_time = PINGS_BREAK_ONLINE
        if connection_status.internet_connection == False:
            spleep_time = PINGS_BREAK_OFFLINE

        try:
            sleep(spleep_time)
        except KeyboardInterrupt:
            print('\n\nStopping...')
            break

        connection_status.change(check())
from lib.view_monkeypatch import ViewMonkeypatch
from lib.status import Status
from configparser import ConfigParser
from time import sleep
from lib.ras import RasPi

config = ConfigParser()
config.read("config.ini")

# Use custom requester which ignores self-signed certificates
requester = Requester(config["jenkins"]["username"], config["jenkins"]["password"], ssl_verify=False)
jenkins = Jenkins(config["jenkins"]["base_url"], requester=requester)

# Monkeypatch the jenkinsapi provided view
ViewMonkeypatch().apply()

view_url = config["jenkins"]["base_url"] + "/view/" + config["jenkins"]["view"]
polling_interval = float(config["general"]["polling_interval"])

raspi_address = config["raspberry_pi"]["address"]
raspi_port = int(config["raspberry_pi"]["port"])
raspi = RasPi(raspi_address, raspi_port)

while True:
    view = jenkins.get_view_by_url(view_url)
    jobs = view.get_jobs()
    status = Status(jobs)
    current_status = status.get()
    print(current_status)
    raspi.update(current_status)
    sleep(polling_interval)
Exemple #10
0
def main():

    _level = Level.INFO
    _log = Logger('main', _level)

    _adjust_velocity = True  # otherwise kp or kd

    _loader = ConfigLoader(_level)
    filename = 'config.yaml'
    _config = _loader.configure(filename)
    _pot = Potentiometer(_config, _level)
    _status = Status(_config, _level)

    try:

        _status.enable()
        _motors = Motors(_config, None, _level)
        _port_motor = _motors.get_motor(Orientation.PORT)
        _stbd_motor = _motors.get_motor(Orientation.STBD)

        _port_pid = PIDController(_config, _port_motor, level=_level)
        _stbd_pid = PIDController(_config, _stbd_motor, level=_level)

        _value = _pot.get_scaled_value()
        if _adjust_velocity:  # otherwise kp or kd
            _port_pid.velocity = _value
            _stbd_pid.velocity = _value
        else:
            _port_pid.velocity = 40.0
            _stbd_pid.velocity = 40.0
            _port_pid.kp = _value
            _stbd_pid.kp = _value
#           _stbd_pid.pid.kd = _value

        _port_pid.enable()
        _stbd_pid.enable()

        try:

            while True:
                _value = _pot.get_scaled_value()
                if _adjust_velocity:  # otherwise kp or kd
                    _port_pid.velocity = _value
                    _stbd_pid.velocity = _value
                else:
                    _port_pid.kp = _value
                    _stbd_pid.kp = _value


#                   _stbd_pid.kd = _value

#               _log.info(Fore.BLACK + 'STBD setpoint={:>5.2f}.'.format(_stbd_pid.get_velocity()))
                time.sleep(0.1)

        except KeyboardInterrupt:
            _log.info(Fore.CYAN + Style.BRIGHT + 'PID test complete.')
        finally:
            _stbd_pid.disable()
            _motors.brake()
            _status.disable()

    except Exception as e:
        _log.info(Fore.RED + Style.BRIGHT +
                  'error in PID controller: {}'.format(e))
        traceback.print_exc(file=sys.stdout)
    finally:
        _log.info(Fore.YELLOW + Style.BRIGHT + 'C. finally.')
Exemple #11
0
def status_page():
    return jsonify(Status())
Exemple #12
0
class Controller():
    '''
        Responds to Events. Simple tasks are handled within this script, more
        complicated ones are farmed out to task files.

        There are two API methods for this class:

          .get_current_message()   returns the last message received
          .act(_current_message, _action_complete_callback)
                                   act upon the current message, with
                                   a callback called upon completion
    '''
    def __init__(self, config, ifs, motors, callback_shutdown, level):
        super().__init__()
        self._log = Logger('controller', level)
        self._config = config
        self._enable_self_shutdown = self._config['ros'].get(
            'enable_self_shutdown')
        #       self._switch = switch
        self._ifs = ifs
        self._motors = motors
        self._port_motor = motors.get_motor(Orientation.PORT)
        self._port_pid = self._port_motor.get_pid_controller()
        self._stbd_motor = motors.get_motor(Orientation.STBD)
        self._stbd_pid = self._stbd_motor.get_pid_controller()
        self._callback_shutdown = callback_shutdown
        self._status = Status(config, GPIO, level)
        self._current_message = None
        self._standby = False
        self._enabled = True
        # behaviours .................................
        self._behaviours = Behaviours(motors, ifs, Level.INFO)
        self._roam_behaviour = RoamBehaviour(motors, Level.INFO)
        self._log.debug('ready.')

    # ..........................................................................
    def set_standby(self, is_standby):
        if is_standby:
            self._log.info('standby.')
            self._status.blink(True)
            self._motors.disable()
            #           self._switch.off()
            self._ifs.disable()
            self._standby = True
        else:
            self._log.info('active (standby off).')
            self._status.blink(False)
            self._motors.enable()
            #           self._switch.on()
            self._ifs.enable()
            self._status.enable()
            self._standby = False

    # ................................................................
    def enable(self):
        self._enabled = True
        self._status.enable()
        self._log.info('enabled.')

    # ................................................................
    def disable(self):
        self._enabled = False
        self._status.disable()
        self._log.info('disabled.')

    # ..........................................................................
    def get_current_message(self):
        return self._current_message

    # ..........................................................................
    def _clear_current_message(self):
        self._log.debug('clear current message  {}.'.format(
            self._current_message))
        self._current_message = None

    # ..........................................................................
    def _slow_down(self, orientation):
        self._log.info(Fore.CYAN + 'slow down {}.'.format(orientation.name))
        self._motors.slow_down(orientation)
        pass

    # ..........................................................................
    def _avoid(self, orientation):
        self._log.info(Fore.CYAN + 'avoid {}.'.format(orientation.name))
        self._behaviours.avoid(orientation)

    # ..........................................................................
    def act(self, message, callback):
        '''
            Responds to the Event contained within the Message.

            The callback method's API is:

              callback(self._current_message, _current_power_levels)
        '''
        if not self._enabled:
            self._log.warning('action ignored: controller disabled.')
            return

        _start_time = dt.datetime.now()
        self._current_message = message
        #       _port_speed = self._motors.get_current_power_level(Orientation.PORT)
        #       _stbd_speed = self._motors.get_current_power_level(Orientation.STBD)
        #       if _port_speed is not None and _stbd_speed is not None:
        #           self._log.debug('last set power port: {:6.1f}, starboard: {:6.1f}'.format(_port_speed, _stbd_speed))
        #       else:
        #           self._log.debug('last set power port: {}, starboard: {}'.format(_port_speed, _stbd_speed))

        _event = self._current_message.get_event()
        self._log.debug(Fore.CYAN + 'act()' + Style.BRIGHT +
                        ' event: {}.'.format(_event) + Fore.YELLOW)
        self._current_message.start()

        # no action ............................................................
        if _event is Event.NO_ACTION:
            self._log.info('event: no action.')
            pass

        # BUTTON                  ..............................................
        # button ...............................................................
        elif _event is Event.BUTTON:
            # if button pressed we change standby mode but don't do anything else
            _value = self._current_message.get_value()
            # toggle value
            #           self.set_standby(not _value)
            if _value:
                self._log.critical('event: button value: {}.'.format(_value))
                self.set_standby(False)
            else:
                self._log.error('event: button value: {}.'.format(_value))
                self.set_standby(True)

            # if in standby mode we don't process the event, but we do perform the callback

#       # stopping and halting ...................................................

# SHUTDOWN                ..............................................
# shutdown ............................................................
        elif _event is Event.SHUTDOWN:
            self._log.info('event: shutdown.')
            self._motors.stop()
            self._callback_shutdown()

        # STOP                    ..............................................
        # stop .................................................................
        elif _event is Event.STOP:
            self._log.info('event: stop.')
            self._motors.stop()

        # HALT                    ..............................................
        # halt .................................................................
        elif _event is Event.HALT:
            self._log.info('event: halt.')
            self._motors.halt()

        # BRAKE                   ...................................
        # brake ................................................................
        elif _event is Event.BRAKE:
            self._log.info('event: brake.')
            self._motors.brake()

        # STANDBY                 ..............................................
        # standby ..............................................................
        elif _event is Event.STANDBY:
            # toggle standby state
            _value = self._current_message.get_value()
            if _value == 1:
                if self._standby:
                    self.set_standby(False)
                else:
                    self.set_standby(True)
            else:
                pass

        # ROAM                 .................................................
        elif _event is Event.ROAM:
            self._log.info('event: roam.')
            self._roam_behaviour.roam()

        # SNIFF                .................................................
        elif _event is Event.SNIFF:
            self._log.info('event: sniff.')
            self._behaviours.sniff()
            time.sleep(0.5)  # debounce gamepad

        # D-PAD HORIZONTAL     .................................................
        elif _event is Event.FORWARD_VELOCITY:
            _direction = message.get_value()
            _speed = 80.0
            if _direction == -1:  # then ahead
                self._log.info('event: d-pad movement: ahead.')
                #               self._motors.change_velocity(0.5, 0.5, SlewRate.SLOW, -1)
                self._motors.ahead(_speed)
                time.sleep(2.0)
            elif _direction == 1:  # then astern
                self._log.info('event: d-pad movement: astern.')
                #               self._motors.change_velocity(-0.5, -0.5, SlewRate.SLOW, -1)
                self._motors.astern(_speed)
                time.sleep(2.0)
            else:
                self._log.info('event: d-pad movement: halt.')

        # D-PAD VERTICAL       .................................................
        elif _event is Event.THETA:
            _direction = message.get_value()
            if _direction == -1:  # then ahead
                self._log.info('event: d-pad rotate: counter-clockwise.')
                self._motors.step(-100.0, 100.0, -1, -1)
                time.sleep(2.0)
            elif _direction == 1:  # then astern
                self._log.info('event: d-pad rotate: clockwise.')
                self._motors.step(100.0, -100.0, -1, -1)
                time.sleep(2.0)
            else:
                self._log.info('event: d-pad rotate: none.')

        # PORT_VELOCITY         ................................................
        elif _event is Event.PORT_VELOCITY:
            _velocity = Gamepad.convert_range(message.get_value())
            self._log.info(
                Fore.GREEN + Style.BRIGHT +
                '{};\tvalue: {:>5.2f}'.format(_event.description, _velocity))
            self._port_motor.set_motor_power(_velocity)

        # PORT_THETA         ...................................................
        elif _event is Event.PORT_THETA:
            _velocity = -1 * Gamepad.convert_range(message.get_value())
            self._log.info(
                Fore.MAGENTA + Style.BRIGHT +
                '{};\tvalue: {:>5.2f}'.format(_event.description, _velocity))

        # STBD_VELOCITY         ................................................
        elif _event is Event.STBD_VELOCITY:
            _velocity = Gamepad.convert_range(message.get_value())
            self._log.info(
                Fore.GREEN + Style.BRIGHT +
                '{};\tvalue: {:>5.2f}'.format(_event.description, _velocity))
            self._stbd_motor.set_motor_power(_velocity)

        # STBD_THETA         ...................................................
        elif _event is Event.STBD_THETA:
            _velocity = -1 * Gamepad.convert_range(message.get_value())
            self._log.info(
                Fore.MAGENTA + Style.BRIGHT +
                '{};\tvalue: {:>5.2f}'.format(_event.description, _velocity))

        # # bumper .............................................................
        # BUMPER_PORT             ..............................................
        elif _event is Event.BUMPER_PORT:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.RED +
                           ' port bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._ifs.disable()
                self._motors.stop()
                #               self._motors.astern(Speed.HALF.value)
                self._motors.turn_astern(Speed.THREE_QUARTER.value,
                                         Speed.HALF.value)
                time.sleep(0.5)
                self._motors.brake()
                self._ifs.enable()
                self._log.info('action complete: port bumper.')
            else:
                self._log.info('no action required (not moving): port bumper.')

        # BUMPER_CNTR           ..............................................
        elif _event is Event.BUMPER_CNTR:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' center bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._ifs.disable()
                self._motors.stop()
                self._motors.astern(Speed.HALF.value)
                time.sleep(0.5)
                self._motors.brake()
                self._ifs.enable()
                self._log.info('action complete: center bumper.')
            else:
                self._log.info(
                    'no action required (not moving): center bumper.')

        # BUMPER_STBD        ..............................................
        elif _event is Event.BUMPER_STBD:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL +
                           Fore.GREEN + ' starboard bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._motors.stop()
                #               self._motors.astern(Speed.FULL.value)
                self._motors.turn_astern(Speed.HALF.value,
                                         Speed.THREE_QUARTER.value)
                time.sleep(0.5)
                self._motors.brake()
                self._log.info('action complete: starboard bumper.')
            else:
                self._log.info(
                    'no action required (not moving): starboard bumper.')

        # # infrared ...........................................................

        # INFRARED_PORT_SIDE      ..............................................
        elif _event is Event.INFRARED_PORT_SIDE:
            _value = message.get_value()
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.RED +
                           ' port side infrared; ' + Fore.YELLOW +
                           'value: {}'.format(_value))
            pass

        # INFRARED_PORT           ..............................................
        elif _event is Event.INFRARED_PORT:
            _value = message.get_value()
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.RED +
                           ' port infrared; ' + Fore.YELLOW +
                           'value: {}'.format(_value))
            if self._motors.is_in_motion():  # if we're moving then avoid
                self._avoid(Orientation.PORT)
                self._log.info('action complete: port infrared.')
            else:
                self._log.info(
                    'no action required (not moving): port infrared.')
            pass

        # INFRARED_CNTR         ..............................................
        elif _event is Event.INFRARED_CNTR:
            _value = message.get_value()
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' center infrared; ' + Fore.YELLOW +
                           'value: {}'.format(_value))
            if self._motors.is_in_motion():  # if we're moving then avoid
                self._avoid(Orientation.CNTR)
                self._log.info('action complete: center infrared.')
            else:
                self._log.info(
                    'no action required (not moving): center infrared.')
            pass

        # INFRARED_STBD      ...................................................
        elif _event is Event.INFRARED_STBD:
            _value = message.get_value()
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL +
                           Fore.GREEN + ' starboard infrared; ' + Fore.YELLOW +
                           'value: {}'.format(_value))
            if self._motors.is_in_motion():  # if we're moving then avoid
                self._avoid(Orientation.STBD)
                self._log.info('action complete: starboard infrared.')
            else:
                self._log.info(
                    'no action required (not moving): starboard infrared.')
            pass

        # INFRARED_STBD_SIDE         ...........................................
        elif _event is Event.INFRARED_STBD_SIDE:
            _value = message.get_value()
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL +
                           Fore.GREEN + ' starboard side infrared; ' +
                           Fore.YELLOW + 'value: {}'.format(_value))
            pass

        # EVENT UNKNOWN: FAILURE ...............................................
        else:
            self._log.error('unrecognised event: {}'.format(_event))
            pass

        _current_power_levels = self._motors.get_current_power_levels()
        if callback is not None:
            self._log.debug(
                Fore.MAGENTA + 'callback message: {}; '.format(
                    self._current_message.get_value()) + Fore.CYAN +
                'current power levels: {}'.format(_current_power_levels))
            callback(self._current_message, _current_power_levels)
        self._clear_current_message()

        _delta = dt.datetime.now() - _start_time
        _elapsed_ms = int(_delta.total_seconds() * 1000)
        self._log.debug(Fore.MAGENTA + Style.DIM +
                        'elapsed: {}ms'.format(_elapsed_ms) + Style.DIM)
Exemple #13
0
class Controller():
    '''
        Responds to Events.
    '''
    def __init__(self, level, config, switch, infrared_trio, motors, rgbmatrix,
                 lidar, callback_shutdown):
        super().__init__()
        self._log = Logger('controller', level)
        self._config = config
        self._enable_self_shutdown = self._config['ros'].get(
            'enable_self_shutdown')
        self._switch = switch
        #       self._info = info
        self._infrared_trio = infrared_trio
        self._motors = motors
        self._rgbmatrix = rgbmatrix
        self._lidar = lidar
        self._callback_shutdown = callback_shutdown
        self._status = Status(GPIO, level)
        self._current_message = None
        self._standby = False
        self._log.debug('ready.')

    # ..........................................................................
    def set_standby(self, is_standby):
        if is_standby:
            self._status.blink(True)
            self._motors.disable()
            self._switch.off()
            self._infrared_trio.disable()
            self._standby = True
        else:
            self._status.blink(False)
            self._motors.enable()
            self._switch.on()
            self._infrared_trio.enable()
            self._status.enable()
            self._standby = False

    # ..........................................................................
    def get_current_message(self):
        return self._current_message

    # ..........................................................................
    def _clear_current_message(self):
        self._current_message = None
        self._log.info('clear current message  {}.'.format(
            self._current_message))

    # ..........................................................................
    def act(self, message, callback):
        '''
            Responds to the Event contained within the Message.
        '''
        self._current_message = message
        _port_speed = self._motors.get_current_power_level(Orientation.PORT)
        _stbd_speed = self._motors.get_current_power_level(Orientation.STBD)
        if _port_speed is not None and _stbd_speed is not None:
            self._log.debug(
                'last set power port: {:6.1f}, starboard: {:6.1f}'.format(
                    _port_speed, _stbd_speed))
        else:
            self._log.debug('last set power port: {}, starboard: {}'.format(
                _port_speed, _stbd_speed))

        event = self._current_message.get_event()
        self._current_message.start()

        # BUTTON                  ..............................................
        # button ...............................................................
        if event is Event.BUTTON:
            # if button pressed we change standby mode but don't do anything else
            _value = self._current_message.get_value()
            # toggle value
            #           self.set_standby(not _value)
            if _value:
                self._log.critical('event: button value: {}.'.format(_value))
                self.set_standby(False)
            else:
                self._log.error('event: button value: {}.'.format(_value))
                self.set_standby(True)

        # if in standby mode we don't process the event, but we do perform the callback
        if self._standby:
            self._log.info('event: disabled, currently in standby mode.')
            callback(self._current_message,
                     self._motors.get_current_power_levels())

        # ballistic behaviours ...........................................................

        # BATTERY_LOW             ..............................................
        elif event is Event.BATTERY_LOW:
            if self._enable_self_shutdown:
                self._log.critical('event: battery low.')
                self.set_standby(True)
                self._current_message.complete()
                self._callback_shutdown()
            else:
                self._log.warning(
                    'event ignored: battery low (self shutdown disabled).')
                self._current_message.complete()
#               callback(self._current_message, None)
#               self._clear_current_message()
#               return

# SHUTDOWN                ..............................................
# shutdown .............................................................
        elif event is Event.SHUTDOWN:
            if self._enable_self_shutdown:
                self._log.info('event: shutdown.')
                self.set_standby(True)
                self._callback_shutdown()
            else:
                self._log.warning(
                    'event ignored: shutdown (self shutdown disabled).')
#               self._current_message.complete()
#               callback(self._current_message, None)
#               self._clear_current_message()
#               return

#     # stopping and halting ...................................................

# STOP                    ..............................................
# stop .................................................................
        elif event is Event.STOP:
            self._log.info('event: stop.')
            self._motors.stop()

        # HALT                    ..............................................
        # halt .................................................................
        elif event is Event.HALT:
            self._log.info('event: halt.')
            self._motors.halt()

        # BRAKE                   ...................................
        # brake ................................................................
        elif event is Event.BRAKE:
            self._log.info('event: brake.')
            self._motors.brake()

        # STANDBY                 ..............................................
        # standby ..............................................................
        elif event is Event.STANDBY:
            self._log.info('event: standby.')
            # disable motors until button press
            self._motors.disable()
            self._switch.off()
            self._standby = True

        # # bumper .............................................................
        # BUMPER_PORT             ..............................................
        elif event is Event.BUMPER_PORT:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.RED +
                           ' port bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._infrared_trio.disable()
                self._motors.stop()
                #               self._info.blink_side(Orientation.PORT, 1)
                #               self._motors.astern(Speed.HALF.value)
                self._motors.turnAstern(Speed.THREE_QUARTER.value,
                                        Speed.HALF.value)
                time.sleep(0.5)
                self._motors.brake()
                self._infrared_trio.enable()
                self._log.info('action complete: port bumper.')
            else:
                self._log.info('no action required (not moving): port bumper.')

        # BUMPER_CENTER           ..............................................
        elif event is Event.BUMPER_CENTER:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' center bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._infrared_trio.disable()
                self._motors.stop()
                #               self._info.blink(1)
                self._motors.astern(Speed.HALF.value)
                time.sleep(0.5)
                self._motors.brake()
                self._infrared_trio.enable()
                self._log.info('action complete: center bumper.')
            else:
                self._log.info(
                    'no action required (not moving): center bumper.')

        # BUMPER_STBD        ..............................................
        elif event is Event.BUMPER_STBD:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL +
                           Fore.GREEN + ' starboard bumper.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._motors.stop()
                #               self._info.blink_side(Orientation.STBD, 1)
                #               self._motors.astern(Speed.FULL.value)
                self._motors.turnAstern(Speed.HALF.value,
                                        Speed.THREE_QUARTER.value)
                time.sleep(0.5)
                self._motors.brake()
                self._log.info('action complete: starboard bumper.')
            else:
                self._log.info(
                    'no action required (not moving): starboard bumper.')

        # BUMPER_UPPER            ..............................................
        elif event is Event.BUMPER_UPPER:
            self._log.info(Fore.RED + Style.BRIGHT + 'event: emergency stop.')
            self._motors.stop()

        # # infrared ...........................................................
        # INFRARED_PORT           ..............................................
        elif event is Event.INFRARED_PORT:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.RED +
                           ' port infrared.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._infrared_trio.disable()
                self._motors.halt()
                #               self._info.blink_side(Orientation.PORT, 1)
                #               self._motors.astern(Speed.HALF.value)
                self._motors.turnAstern(Speed.THREE_QUARTER.value,
                                        Speed.HALF.value)
                time.sleep(0.1)
                self._motors.brake()
                self._infrared_trio.enable()
                self._log.info('action complete: port infrared.')
            else:
                self._log.info(
                    'no action required (not moving): port infrared.')

        # INFRARED_CENTER         ..............................................
        elif event is Event.INFRARED_CENTER:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' center infrared.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._infrared_trio.disable()
                self._motors.halt()
                #               self._info.blink(1)
                self._motors.astern(Speed.HALF.value)
                time.sleep(0.2)
                self._motors.brake()
                self._infrared_trio.enable()
                self._log.info('action complete: center infrared.')
            else:
                self._log.info(
                    'no action required (not moving): center infrared.')

        # INFRARED_SHORT_RANGE         .........................................
        elif event is Event.INFRARED_SHORT_RANGE:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' short range infrared.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._infrared_trio.disable()
                self._motors.halt()
                #               self._info.blink(1)
                self._motors.astern(Speed.HALF.value)
                time.sleep(0.34)
                self._motors.brake()
                self._infrared_trio.enable()
                self._log.info('action complete: short range infrared.')
            else:
                self._log.info(
                    'no action required (not moving): short range infrared.')
            self._infrared_trio.set_long_range_scan(True)

        # INFRARED_LONG_RANGE         .........................................
        elif event is Event.INFRARED_LONG_RANGE:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL + Fore.BLUE +
                           ' long range infrared.' + Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._log.critical(
                    "WE'RE GOING TOO FAST!         xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "
                )
                self._infrared_trio.set_long_range_scan(False)
                self._motors.change_speed(Speed.DEAD_SLOW.value)
                #               self._motors.ahead(Speed.DEAD_SLOW.value)
                self._log.info('action complete: long range infrared.')
#           if self._motors.is_faster_than(Speed.SLOW) or True: # if we're moving fast then slow down
#               self._log.critical('WE\'RE GOING TOO FAST!')
#               self._motors.ahead(Speed.SLOW.value)
#               self._log.info('action complete: long range infrared.')
            else:
                self._log.critical(
                    'no action required (not moving): long range infrared.')

        # INFRARED_STBD      ..............................................
        elif event is Event.INFRARED_STBD:
            self._log.info(Style.BRIGHT + 'event:' + Style.NORMAL +
                           Fore.GREEN + ' starboard infrared.' +
                           Style.RESET_ALL)
            if self._motors.is_in_motion():  # if we're moving then halt
                self._motors.halt()
                #               self._info.blink_side(Orientation.STBD, 1)
                #               self._motors.astern(Speed.FULL.value)
                self._motors.turnAstern(Speed.HALF.value,
                                        Speed.THREE_QUARTER.value)
                time.sleep(0.1)
                self._motors.brake()
                self._log.info('action complete: starboard infrared.')
            else:
                self._log.info(
                    'no action required (not moving): starboard infrared.')

        # # emergency movements ................................................
        # EMERGENCY_ASTERN        ..............................................

        # # movement ahead .....................................................
        # FULL_AHEAD              ..............................................
        # HALF_AHEAD              ..............................................
        # SLOW_AHEAD              ..............................................
        # DEAD_SLOW_AHEAD         ..............................................

        # AHEAD                   ..............................................
        # 8 ahead ..............................................................
        elif event is Event.AHEAD:
            if self._infrared_trio.get_long_range_hits() > 0:
                self._log.info('event: ahead slow speed.')
                _port_speed = Speed.SLOW.value
                _stbd_speed = Speed.SLOW.value
            else:
                self._log.info('event: ahead half speed.')
                _port_speed = Speed.HALF.value
                _stbd_speed = Speed.HALF.value
            self._motors.ahead(Speed.HALF.value)
            self._log.info('action complete: ahead.')

        # # movement astern ....................................................
        # ASTERN                  ..............................................
        # 2 astern .............................................................
        elif event is Event.ASTERN:
            #           _port_speed = -1.0 * Speed.HALF.value
            #           _stbd_speed = -1.0 * Speed.HALF.value
            self._log.critical('event: astern.')
            self._infrared_trio.disable()
            self._motors.astern(Speed.HALF.value)
            self._infrared_trio.enable()
            self._log.critical('event (returned already): astern.')

        # DEAD_SLOW_ASTERN        ..............................................
        # SLOW_ASTERN             ..............................................
        # HALF_ASTERN             ..............................................
        # FULL_ASTERN             ..............................................

        # # relative change ....................................................
        # INCREASE_SPEED          ..............................................
        # EVEN                    ..............................................
        # DECREASE_SPEED          ..............................................

        # # port turns .........................................................
        # TURN_AHEAD_PORT         ..............................................
        # 9 turn ahead port ....................................................
        elif event is Event.TURN_AHEAD_PORT:
            self._log.critical('event: turn ahead to port.')
            _stbd_speed += step_value
            _stbd_speed = min(Speed.MAXIMUM.value, _stbd_speed)
            self._log.info(
                'event: turn ahead to port: {:6.1f}, {:6.1f}'.format(
                    _port_speed, _stbd_speed))
            self._motors.turnAhead(_port_speed, _stbd_speed)

        # TURN_TO_PORT            ..............................................
        # TURN_ASTERN_PORT        ..............................................

        # SPIN_PORT               ..............................................
        # 4 spin counter-clockwise .............................................
        elif event is Event.SPIN_PORT:
            self._log.info('event: spinPort.')
            self._motors.spinPort(Speed.THREE_QUARTER.value)

        # # starboard turns ....................................................

        # SPIN_STBD          ..............................................
        # 6 spin clockwise .....................................................
        elif event is Event.SPIN_STBD:
            self._log.info('event: spinStarboard.')
            self._motors.spinStarboard(Speed.THREE_QUARTER.value)

        # TURN_ASTERN_STBD   ..............................................
        # TURN_TO_STBD       ..............................................

        # TURN_AHEAD_STBD    ..............................................
        # 7 turn ahead starboard ...............................................
        elif event is Event.TURN_AHEAD_STBD:
            self._log.critical('event: turn ahead to starboard.')
            _port_speed += step_value
            _port_speed = min(Speed.MAXIMUM.value, _port_speed)
            self._log.info('Turn ahead to starboard: {:6.1f}, {:6.1f}'.format(
                _port_speed, _stbd_speed))
            self._motors.turnAhead(_port_speed, _stbd_speed)

        # ROAM                    ..............................................
        elif event is Event.ROAM:
            self._log.critical('event: roam.')
            self._lidar.enable()
            self._rgbmatrix.disable()
            self._rgbmatrix.clear()
            values = self._lidar.scan()

            #           time.sleep(2.0)
            #           self._infrared_trio.disable()
            #           self._motors.spinPort(Speed.THREE_QUARTER.value)
            #           time.sleep(0.20)
            #           self._motors.halt()
            #           self._motors.ahead(Speed.HALF.value)
            #           self._infrared_trio.enable()
            #           time.sleep(2.3)
            #           self._motors.spinStarboard(Speed.THREE_QUARTER.value)
            #           time.sleep(0.4)
            #           self._motors.ahead(Speed.HALF.value)
            #           time.sleep(1.4)
            #           self._motors.halt()

            #           self._motors.spinPort(Speed.THREE_QUARTER.value)
            #           time.sleep(2.0)
            #           self._motors.halt()
            #           for i in range(5):
            #               self._rgbmatrix.set_color(Color.GREEN)
            #               time.sleep(0.5)
            #               self._rgbmatrix.set_color(Color.BLACK)
            #               time.sleep(0.5)
            #           self._rgbmatrix.set_color(Color.BLACK)

            self._log.critical('scan complete.')

        # non-ballistic behaviours .......................................................

        else:
            self._log.error('unrecognised event: {}'.format(event))
            pass

        callback(self._current_message,
                 self._motors.get_current_power_levels())
        self._clear_current_message()