Ejemplo n.º 1
0
class SmartSpeaker():
    def __init__(self):
        self.interrupted = False
        self.model = "snowboy.pmdl"
        signal.signal(signal.SIGINT, self.signal_handler)
        self.detector = snowboydecoder.HotwordDetector(self.model,
                                                       sensitivity=0.42)
        print('Listening... Press Ctrl+C to exit')
        self.robot = Robot()
        self.music_player = self.robot.get_music_player()
        self.player = Player()

    def signal_handler(self, signal, frame):
        self.interrupted = True

    def interrupt_callback(self):
        return self.interrupted

    def detected_callback(self):
        self.music_player.pause()
        self.player.play_ding()

    def speeched_callback(self, fname):
        self.player.play_dong()
        self.robot.process(fname)
        sleep(1)
        self.music_player.cont()

    def run(self):
        self.detector.start(detected_callback=self.detected_callback,
                            speeched_callback=self.speeched_callback,
                            interrupt_check=self.interrupt_callback,
                            sleep_time=0.03)
Ejemplo n.º 2
0
class SmartSpeaker():
    # 初始化
    def __init__(self):
        self.interrupted = False
        self.model = "嘿小二.pmdl"  # 使用的语音模型
        signal.signal(signal.SIGINT, self.signal_handler)  # 捕获ctrl+c
        self.detector = snowboydecoder.HotwordDetector(
            self.model, sensitivity=0.5)  # 设置语音模型与敏感度
        print('Listening... Press Ctrl+Z to exit')
        self.robot = Robot()  # 创建应用模块
        self.music_player = self.robot.get_music_player()  # 创建音乐播放模块
        self.player = Player()  # 触发响应词叮咚播放

    def signal_handler(self, signal, frame):
        self.interrupted = True

    def interrupt_callback(self):
        return self.interrupted

    def detected_callback(self):
        self.music_player.pause()  # 检测到人声时音乐暂停
        self.player.play_ding()  # 触发 叮

    def speeched_callback(self, fname):
        self.player.play_dong()  # 检测时间到后触发 咚
        self.robot.process(fname)  # 将收到的语音传给应用模块执行相应的操作
        sleep(1)  # 等待片刻
        self.music_player.cont()  # 继续播放音乐

    # 启动机器人
    def run(self):
        self.detector.start(detected_callback=self.detected_callback,
                            speeched_callback=self.speeched_callback,
                            interrupt_check=self.interrupt_callback,
                            sleep_time=0.03)
Ejemplo n.º 3
0
    def __init__(self):
        self.interrupted = False
        # 读取配置
        config_file = 'config.yaml'
        if os.path.exists(config_file) == False:
            print('【警告】配置文件不存在')
            return
        f = open('config.yaml')
        config = yaml.load(f)
        model_name = config.get('name', 'snowboy')
        if ['snowboy','alexa'].count(model_name) > 0:
            model_name = model_name + '.umdl'
        else:
            model_name = model_name + '.pmdl'

        self.model = "唤醒词/" + model_name # 使用的语音模型
        print('【唤醒词文件】' + self.model)
        if os.path.exists(self.model) == False:
            print('【警告】唤醒词文件不存在')
            return
        signal.signal(signal.SIGINT, self.signal_handler) # 捕获ctrl+c
        self.detector = snowboydecoder.HotwordDetector(self.model, sensitivity=0.5) # 设置语音模型与敏感度
        print('Listening... Press Ctrl+Z to exit')
        self.robot = Robot(config) # 创建应用模块
        self.player = Player() # 触发响应词叮咚播放
Ejemplo n.º 4
0
    def test_invalid_input(self):

        with captured_output() as (out, err):
            robot = Robot()
            robot.place(100, 100, "nowhere")

        output = out.getvalue().strip()
        self.assertEqual(output, "Invalid input.")
Ejemplo n.º 5
0
    def __init__(self, sim=False):
        # super(Core, self).__init__(sim)
        Robot.__init__(self, sim)
        # Qga.__init__(self, sim)
        print("f**k end")
        self.initialPoint = self.loc

        dsrv = DynamicReconfigureServer(RobotConfig, self.Callback)
Ejemplo n.º 6
0
    def test_falling_from_board(self):

        with captured_output() as (out, err):
            robot = Robot(4, 4, "east")
            robot.move()

        output = out.getvalue().strip()
        self.assertEqual(output,
                         "Safety warning - I am about to fall to oblivion!")
Ejemplo n.º 7
0
 def __init__(self):
     self.interrupted = False
     self.model = "嘿小二.pmdl"  # 使用的语音模型
     signal.signal(signal.SIGINT, self.signal_handler)  # 捕获ctrl+c
     self.detector = snowboydecoder.HotwordDetector(
         self.model, sensitivity=0.5)  # 设置语音模型与敏感度
     print('Listening... Press Ctrl+Z to exit')
     self.robot = Robot()  # 创建应用模块
     self.music_player = self.robot.get_music_player()  # 创建音乐播放模块
     self.player = Player()  # 触发响应词叮咚播放
Ejemplo n.º 8
0
    def __init__(self, map_filename, robot_filename):
        self.robot = Robot()
        self.world = FeatureBasedWorld()
        self.tick = 0.0
        self.pose_history = []  # ground truth trajectory

        self.robot.LoadFromFile(robot_filename)
        self.world.LoadFromFile(map_filename)

        self.pose_history.append(self.robot.GetPose())  # initial pose
Ejemplo n.º 9
0
 def __init__(self):
     self.interrupted = False
     self.model = "snowboy.pmdl"
     signal.signal(signal.SIGINT, self.signal_handler)
     self.detector = snowboydecoder.HotwordDetector(self.model,
                                                    sensitivity=0.42)
     print('Listening... Press Ctrl+C to exit')
     self.robot = Robot()
     self.music_player = self.robot.get_music_player()
     self.player = Player()
Ejemplo n.º 10
0
 def setUp(self):
     mock = self.create_mock_robotd()
     mock.new_powerboard()
     time.sleep(0.2)
     self.mock = mock
     self.robot = Robot(robotd_path=mock.root_dir,
                        wait_for_start_button=False)
Ejemplo n.º 11
0
    def test_implicit_wait_start_competition_mode(self):
        self.set_competition_mode()

        with self.mock_kill_after_delay() as mock_kill_after_delay:
            Robot(robotd_path=self.mock.root_dir)

            mock_kill_after_delay.assert_called_once_with(
                game_specific.GAME_DURATION_SECONDS, )
Ejemplo n.º 12
0
 def setUp(self):
     mock = self.create_mock_robotd()
     # Insert a power board to let the robot start up
     self.power_board = mock.new_powerboard()
     time.sleep(0.2)
     self.mock = mock
     self.robot = Robot(robotd_path=mock.root_dir,
                        wait_for_start_button=False)
Ejemplo n.º 13
0
    def test_explicit_wait_start_development_mode(self):
        robot = Robot(
            robotd_path=self.mock.root_dir,
            wait_for_start_button=False,
        )

        with self.mock_kill_after_delay() as mock_kill_after_delay:
            robot.power_board.wait_start()

            # default is development mode, which doesn't have a timeout
            mock_kill_after_delay.assert_not_called()
Ejemplo n.º 14
0
class Simulator:
    # This class simulates a robot moving in a world. It updates the robot's
    # state and measurements every tick.
    def __init__(self, map_filename, robot_filename):
        self.robot = Robot()
        self.world = FeatureBasedWorld()
        self.tick = 0.0
        self.pose_history = []  # ground truth trajectory

        self.robot.LoadFromFile(robot_filename)
        self.world.LoadFromFile(map_filename)

        self.pose_history.append(self.robot.GetPose())  # initial pose

    def Update(self, t, action):
        '''
        Update the simulator.
        ===INPUT===
        t: the time of update.
        action: the active action from last Update() to t.
        ===OUTPUT===
        A list of Measurement, which the robot observes at tick t.
        '''
        dt = t - self.tick
        self.tick = t
        rp = self.robot.ApplyAction(action, dt)
        self.pose_history.append(rp)
        return self.robot.MeasureWorld(self.world)

    def GetTrajectory(self):
        '''
        Get the ground truth trajectory.
        '''
        return self.pose_history

    def GetMap(self):
        '''
        Get the ground truth map.
        '''
        return self.world
Ejemplo n.º 15
0
def main():
	robot = Robot((18,1), True)
	#robot.set_speed(100)
	
	#_real_map = Arena(robot)
	#ArenaUtils.load_arena_from_file(_real_map, 'map/SampleWeek11.txt')
	_explore_map = Arena(robot)
	_explore_map.set_allunexplored()

	CommMgr.connect()
	_explore = Exploration(_explore_map, robot, 300, 3600)
	_explore.run()
	CommMgr.close()
Ejemplo n.º 16
0
 def test_two_clients(self):
     """ Checks you can interface a motor board multiple times"""
     # TODO make this test generic to the board, so it runs on all boards.
     self.mock.new_motorboard('ABC')
     # Set up robot 2!
     robot2 = Robot(robotd_path=self.mock.root_dir,
                    wait_for_start_button=False)
     # Give it a tiny bit to init the boards
     time.sleep(0.2)
     self.robot.motor_boards[0].m0 = 1
     self.robot.motor_boards[0].m0 = -1
     robot2.motor_boards[0].m0 = 1
     robot2.motor_boards[0].m0 = -1
Ejemplo n.º 17
0
    def run(self):
        """
        Server start
        """
        while True:
            stacks = self.get_stacks()
            if not stacks:
                sleep(60)
                continue

            for stack in stacks:
                result = Robot.run(stack)
                self.send_result({'stack': stack, 'result': result})
Ejemplo n.º 18
0
    def test_explicit_wait_start_competition_mode(self):
        robot = Robot(
            robotd_path=self.mock.root_dir,
            wait_for_start_button=False,
        )

        self.set_competition_mode()

        with self.mock_kill_after_delay() as mock_kill_after_delay:
            robot.power_board.wait_start()

            mock_kill_after_delay.assert_called_once_with(
                game_specific.GAME_DURATION_SECONDS, )
Ejemplo n.º 19
0
def fp():
    robot = Robot((18, 1), True)
    _real_map = Arena(robot)
    ArenaUtils.load_arena_from_file(_real_map, 'map/17_week10.txt')
    print('Awaiting FP_START')
    while True:
        _command = CommMgr.recv()
        if _command == 'FP_START':
            CommMgr.send('X', CommMgr.ARDUINO)
            break

    _go_to_wp_goal = FastestPath(_real_map, robot)
    _status = _go_to_wp_goal.do_fastest_path_wp_goal(
        (7, 10), ArenaConstant.GOAL_POS.value)
def initialize_bots(gt, generator):
	global config
	bots = []
	for i in range(config['num_bots']):
		sim = gt.get_hardware_instance(guid=i)
		bot = Robot(guid=i,
					ip=config['bots']['ip'],
					port=config['bots']['s_port']+i,
					hardware=sim,
					generator=generator,
					connect=config['bots']['connect'],
					image_size=config['sim']['image_size']
			  )
		bots.append(bot)
	return bots
Ejemplo n.º 21
0
def main():
    with tempfile.TemporaryDirectory(prefix="robot-api-test-") as root_dir:
        mock = MockRobotD(root_dir=root_dir)

        mock.new_powerboard()
        time.sleep(0.2)

        mock.new_motorboard()
        time.sleep(0.2)

        from robot.robot import Robot
        robot = Robot(robotd_path=root_dir)
        robot.power_board.power_off()
        robot.motor_boards[0].m0 = 1

        time.sleep(0.2)
        mock.stop()
Ejemplo n.º 22
0
class SmartSpeaker():
    # 初始化
    def __init__(self):
        self.interrupted = False
        # 读取配置
        config_file = 'config.yaml'
        if os.path.exists(config_file) == False:
            print('【警告】配置文件不存在')
            return
        f = open('config.yaml')
        config = yaml.load(f)
        model_name = config.get('name', 'snowboy')
        if ['snowboy','alexa'].count(model_name) > 0:
            model_name = model_name + '.umdl'
        else:
            model_name = model_name + '.pmdl'

        self.model = "唤醒词/" + model_name # 使用的语音模型
        print('【唤醒词文件】' + self.model)
        if os.path.exists(self.model) == False:
            print('【警告】唤醒词文件不存在')
            return
        signal.signal(signal.SIGINT, self.signal_handler) # 捕获ctrl+c
        self.detector = snowboydecoder.HotwordDetector(self.model, sensitivity=0.5) # 设置语音模型与敏感度
        print('Listening... Press Ctrl+Z to exit')
        self.robot = Robot(config) # 创建应用模块
        self.player = Player() # 触发响应词叮咚播放
        
    def signal_handler(self, signal, frame):
        self.interrupted = True

    def interrupt_callback(self):
        return self.interrupted

    def detected_callback(self):
        self.robot.hass_api('events/voice_assistant', {'type': 'ding'})
        self.player.play_ding() # 触发 叮

    def speeched_callback(self, fname):
        self.player.play_dong() # 检测时间到后触发 咚
        self.robot.process(fname) # 将收到的语音传给应用模块执行相应的操作
        # sleep(1) # 等待片刻
        self.robot.hass_api('events/voice_assistant', {'type': 'dong'})

    # 启动机器人
    def run(self):
        self.detector.start(detected_callback=self.detected_callback, speeched_callback=self.speeched_callback,
               interrupt_check=self.interrupt_callback,
               sleep_time=0.03)
Ejemplo n.º 23
0
async def main():
    opts = Options(sys.argv)

    r = Robot(**opts.args())
    try:
        if opts.id is None:
            """Create new game if id was not specified"""

            opts.id = await r.newgame()
        else:
            """Check if game exists"""

            if opts.id != await r.checkgame(opts.id):
                print('Game id miss-matched', file=sys.stderr)
                sys.exit(2)

    except Exception as e:
        print(f'Failed to acquire game: {e}')
        sys.exit(3)

    if opts.robots:
        rbs = [r]
        wrk = [ensure_future(r.run(pnum=opts.autoplay))]

        await sleep(0.2)  # Leader process should be able to reset game

        for i in range(1, opts.robots):
            r = Robot(uri=opts.site, idx=i, id=opts.id)
            rbs.append(r)
            wrk.append(ensure_future(r.run()))

        await gather(*wrk)
        results(wrk[0].result(), [r.pname for r in rbs],
                [r.id_prefix for r in rbs])
    else:
        res = await r.run(pnum=opts.autoplay)
        results(res)
Ejemplo n.º 24
0
from math import pi
import robot.api as api
import asyncio

config = ''


def load_config():
    with open('config.yml') as f:
        global config
        config = yaml.load(f, Loader=yaml.FullLoader)


if __name__ == '__main__':
    load_config()
    robot = Robot(config['robot']['ip'])
    asyncio.get_event_loop().run_until_complete(
        robot.cmd_via_ws(api.CMD_START_SYS))

    # 1. send cmd via http
    print("========================================")
    print("The following cmd was sent via http")
    print("current robot mode: {}".format(robot.get_robot_mode()))
    print(robot.get_target_joints())
    print(robot.get_actual_joints())
    print(robot.get_target_tcp_pose())
    print(robot.get_actual_tcp_pose())
    robot.move_check()
    print(robot.movej([0, 0, 0, 0, 0, 0], True, 1, 1, 0))
    print(robot.movej([0, -pi / 4, pi / 2, -pi / 4, pi / 2, 0], True, 1, 1, 0))
    print(robot.movel([-0.3, -0.1, 0.2, -pi / 2, 0, pi / 2], False, 1, 1, 0))
Ejemplo n.º 25
0
    def execute_path(self, path, goal_pos):
        _output_string = []

        _temp_block = path.pop()

        _ori_target = None

        _actions = []

        _temp_robot = Robot(self._robot.get_pos(), False)
        _temp_robot.set_ori(self._robot.get_ori())
        _temp_robot.set_speed(0)

        while _temp_robot.get_pos()[0] != goal_pos[0] or _temp_robot.get_pos(
        )[1] != goal_pos[1]:
            if _temp_robot.get_pos()[0] == _temp_block.get_pos(
            )[0] and _temp_robot.get_pos()[1] == _temp_block.get_pos()[1]:
                _temp_block = path.pop()

            _ori_target = self.get_target_ori(_temp_robot.get_pos(),
                                              _temp_robot.get_ori(),
                                              _temp_block)

            _action = None
            if _temp_robot.get_ori() != _ori_target:
                _action = self.get_target_move(_temp_robot.get_ori(),
                                               _ori_target)
            else:
                _action = Action.FORWARD

            print('Action {} from {} to {}'.format(_action.value,
                                                   _temp_robot.get_pos(),
                                                   _temp_block.get_pos()))
            _temp_robot.move(_action)
            _actions.append(_action)
            _output_string.append(_action.value)

        if not self._robot.is_actual_robot():
            for _act in _actions:
                if _act == Action.FORWARD:
                    if not self.can_move_forward():
                        print("Fastest Path Execution terminated!")
                        return "T"

                self._robot.move(_act)
                self._robot.notify(_act, self._map, True)

                if self._exploration_mode:
                    self._robot.set_sensor()
                    self._robot.sense(self._map)  #, self._real_map)
                    if self._surface is not None:
                        self._map.draw(self._surface)
        else:
            _fCount = 0
            for _act in _actions:
                if _act == Action.FORWARD:
                    _fCount += 1
                    if _fCount == 9:
                        self._robot.move_multiple(_fCount)
                        _fCount == 0
                        _command = 'F' + str(_fCount)
                        self._robot.notify(_command, self._map, True)
                elif _act == Action.RIGHT or _act == Action.LEFT:
                    if _fCount > 0:
                        self._robot.move_multiple(_fCount)
                        _fCount == 0
                        _command = 'F' + str(_fCount)
                        self._robot.notify(_command, self._map, True)

                    self._robot.move(_act)
                    self._robot.notify(_act, self._map, True)

            if _fCount > 0:
                self._robot.move_multiple(_fCount)
                _fCount == 0
                _command = 'F' + str(_fCount)
                self._robot.notify(_command, self._map, True)

        print('Actions: {}'.format(''.join(_output_string)))
        return ''.join(_output_string)
Ejemplo n.º 26
0
    def test_implicit_wait_start_development_mode(self):
        with self.mock_kill_after_delay() as mock_kill_after_delay:
            Robot(robotd_path=self.mock.root_dir)

            # default is development mode, which doesn't have a timeout
            mock_kill_after_delay.assert_not_called()
Ejemplo n.º 27
0
config = toml.load(open("physics.toml", 'r'))

ppi = 2
height = config["field"]["height"]
width = config["field"]["width"]
field = np.zeros((width * ppi, height * ppi, 3))

robot_width = config["drivetrain"]["width"]
robot_length = config["drivetrain"]["length"]
robot_rot = config["robot"]["rot"]
robot_x = config["robot"]["x"]
robot_y = config["robot"]["y"]

drivetrain = DifferentialDrive(robot_width)
robot = Robot(drivetrain, robot_width * ppi, robot_length * ppi, position=[robot_x, robot_y], rotation=robot_rot)
dt = 0
last_time = datetime.now().microsecond / 1000000

while True:
    simfield = np.copy(field)

    robot.update(dt)
    pts = np.array(robot.points, np.int32)
    pts = pts.reshape((-1, 1, 2))
    cv2.fillPoly(simfield, [pts], (0, 255, 255))

    
    cv2.putText(simfield, f"L: {drivetrain.l_speed:.2f}", (15, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
    cv2.putText(simfield, f"R: {drivetrain.r_speed:.2f}", (15, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
    cv2.putText(simfield, f"F: {robot.forward:.2f}", (200, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
Ejemplo n.º 28
0
from robot.robot import Robot
from util.json_generator import generate_sample_obstacles
from util.json_parser import JSONParser
import numpy as np

# Generate the JSON file needed for obstacles
generate_sample_obstacles()

map_axis_size = 50
map_plane = np.zeros([map_axis_size, map_axis_size])
starting_location = [map_axis_size / 2, map_axis_size / 2]

robot = Robot(map_plane, JSONParser.get_obstacles(), starting_location)

# Human input movement
while (True):

    user_input = input('Enter a movement command')
    if user_input.lower() not in Robot.ALLOWED_MOVEMENTS:
        print("Error: {} is not a recognized movement".format(user_input))
        print("The allowed movements are {}.".format(Robot.ALLOWED_MOVEMENTS))
        continue

    robot.update_position(user_input)
Ejemplo n.º 29
0
import sys
from robot.robot import Robot

if __name__ == "__main__":
    robot = Robot()

    instruction_file = None
    if len(sys.argv) > 1:
        instruction_file = sys.argv[1]

    result = robot.operate(instruction_file, debug=False)
    distance = robot.nav.distance
Ejemplo n.º 30
0
def explore():
    robot = Robot((18, 1), True)
    _explore_map = Arena(robot)
    _explore_map.set_allunexplored()
    _explore = Exploration(_explore_map, robot, 300, 3600)
    _explore.run()