def __init__(self):
        r'''Create a new simulator interface.
        '''
        # Simulator ID.
        self.sid = None

        # DBW activation status.
        self.dbw_enable = False

        # Message buffer.
        self.msgs = {}

        # Bridge object between ROS and simulator.
        self.bridge = Bridge(conf, self.send)

        # Enforce use of eventlet for asynchronous operations.
        self.sio = socketio.Server(async_mode='eventlet')

        # Register event handlers
        self.sio.on('connect', self.connect)
        self.sio.on('telemetry', self.telemetry)
        self.sio.on('control', self.control)
        self.sio.on('obstacle', self.obstacle)
        self.sio.on('lidar', self.lidar)
        self.sio.on('trafficlights', self.trafficlights)
        self.sio.on('image', self.image)
Exemple #2
0
   def __init__(self, socket_map, mav_iface, send_interval, dispatcher):
      Bridge.__init__(self, socket_map, mav_iface, send_interval)
      self.dead = False
      recv_thread = Thread(target = self._receive)
      recv_thread.daemon = True
      send_thread = Thread(target = self._send)
      send_thread.daemon = True
      self.dispatcher = dispatcher
      self.auto_mode_flags = MAV_MODE_FLAG_SAFETY_ARMED \
         | MAV_MODE_FLAG_MANUAL_INPUT_ENABLED \
         | MAV_MODE_FLAG_STABILIZE_ENABLED \
         | MAV_MODE_FLAG_GUIDED_ENABLED \
         | MAV_MODE_FLAG_AUTO_ENABLED

      Bridge.__init__(self, socket_map, mav_iface, send_interval)
      self.csb = ControlSensorBits()
      self.sensors_present = self.csb.bits(['GYRO_3D', 'ACC_3D', 'MAG_3D',
         'PRESSURE_ABS', 'GPS', 'ANGLE_RATE_CONTROL', 'ATTITUDE_CTRL',
         'YAW_CTRL', 'ALTITUDE_CTRL', 'XY_CTRL', 'MOTOR_CTRL'])
      self.sensors_enabled = self.sensors_present
      self.sensors_health = self.sensors_present
      self._load_reader = LoadReader()
      self._power_reader = PowerReader(socket_map['power_mon'])
      recv_thread.start()
      send_thread.start()
      self._load_reader.start()
      self._power_reader.start()
      self._power_reader.wait_data()
Exemple #3
0
    def __init__(self, socket_map, mav_iface, send_interval, dispatcher):
        Bridge.__init__(self, socket_map, mav_iface, send_interval)
        self.dead = False
        recv_thread = Thread(target=self._receive)
        recv_thread.daemon = True
        send_thread = Thread(target=self._send)
        send_thread.daemon = True
        self.dispatcher = dispatcher
        self.auto_mode_flags = MAV_MODE_FLAG_SAFETY_ARMED \
           | MAV_MODE_FLAG_MANUAL_INPUT_ENABLED \
           | MAV_MODE_FLAG_STABILIZE_ENABLED \
           | MAV_MODE_FLAG_GUIDED_ENABLED \
           | MAV_MODE_FLAG_AUTO_ENABLED

        Bridge.__init__(self, socket_map, mav_iface, send_interval)
        self.csb = ControlSensorBits()
        self.sensors_present = self.csb.bits([
            'GYRO_3D', 'ACC_3D', 'MAG_3D', 'PRESSURE_ABS', 'GPS',
            'ANGLE_RATE_CONTROL', 'ATTITUDE_CTRL', 'YAW_CTRL', 'ALTITUDE_CTRL',
            'XY_CTRL', 'MOTOR_CTRL'
        ])
        self.sensors_enabled = self.sensors_present
        self.sensors_health = self.sensors_present
        self._load_reader = LoadReader()
        self._power_reader = PowerReader(socket_map['power_mon'])
        recv_thread.start()
        send_thread.start()
        self._load_reader.start()
        self._power_reader.start()
        self._power_reader.wait_data()
Exemple #4
0
class Adapter:
    base_url = 'https://hcaptcha.com/siteverify'
    token = None
    secret_key = None

    def __init__(self, input, secret_key: str = None):
        self.id = input.get('id', '1')
        self.secret_key = secret_key
        self.request_data = input.get('data')
        if self.validate_request_data() and self.secret_key:
            self.bridge = Bridge()
            self.set_params()
            self.create_request()
        else:
            self.result_error(
                'No data or API secret key provided for the adapter')

    def validate_request_data(self):
        if self.request_data is None:
            return False
        if self.request_data == {}:
            return False
        return True

    def set_params(self):
        self.token = self.request_data.get('token')

    def create_request(self):
        try:
            data = f'response={self.token}&secret={self.secret_key}'
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            response = self.bridge.post_request(self.base_url,
                                                data=data,
                                                headers=headers)
            data = response.json()
            print('Response: ', data)
            self.result = data['success']
            data['result'] = self.result
            self.result_success(data)
        except Exception as e:
            self.result_error(e)
        finally:
            self.bridge.close()

    def result_success(self, data):
        self.result = {
            'jobRunID': self.id,
            'data': data,
            'result': self.result,
            'statusCode': 200,
        }

    def result_error(self, error):
        self.result = {
            'jobRunID': self.id,
            'status': 'errored',
            'error': f'There was an error: {error}',
            'statusCode': 500,
        }
Exemple #5
0
    def __init__(self, name, tg):
        Bridge.__init__(self, name, tg)

        self.api = vk.API(vk.Session(access_token=self.cfg['token']), v='5.74', lang='ru', timeout=10)
        self.user = self.api.users.get()[0]

        thr = threading.Thread(target=self.poll)
        thr.daemon = True
        thr.start()
Exemple #6
0
 def __init__(self, input):
     self.id = input.get('id', '1')
     self.request_data = input.get('data')
     if self.validate_request_data():
         self.bridge = Bridge()
         self.hashtag = self.request_data.get('hashtag', '')
         self.username = self.request_data.get('username', '')
         self.create_request()
     else:
         self.result_error('No data provided')
Exemple #7
0
 def __init__(self, input, secret_key: str = None):
     self.id = input.get('id', '1')
     self.secret_key = secret_key
     self.request_data = input.get('data')
     if self.validate_request_data() and self.secret_key:
         self.bridge = Bridge()
         self.set_params()
         self.create_request()
     else:
         self.result_error(
             'No data or API secret key provided for the adapter')
Exemple #8
0
 def __init__(self, input, image_checker, image_manager):
     self.image_cheker = image_checker
     self.image_manager = image_manager
     self.id = input.get('id', '1')
     self.result = ""  #kostil
     self.request_data = input.get('data')
     if self.validate_request_data():
         self.bridge = Bridge()
         self.set_params()
         self.create_request()
     else:
         self.result_error('No data provided')
Exemple #9
0
    def __main__(self, running, socket=None):
        if socket is not None:
            manager = Manager()
            bridge = Bridge(manager, socket=socket)
            self.register(manager)
            manager.start()

        try:
            self.run()
        finally:
            if socket is not None:
                while bridge or manager: pass
                manager.stop()
                bridge.stop()
Exemple #10
0
def main():
    config = dict(
        sharedmem_path="config/sharedmem.json",
        accel_offset_x=1.01112,
        accel_offset_y=1.00765,
        accel_offset_z=0.96534,
        gyro_offset_x=2.843,
        gyro_offset_y=-6.056,
        gyro_offset_z=-1.603,
        wheel_diameter_m=0.0545,
    )

    bridge = Bridge(**config)

    bridge.run()
def main():
	pygame.init()
	screen_size = [SCREEN_WIDTH, SCREEN_HEIGHT]
	screen = pygame.display.set_mode(screen_size)
	pygame.display.set_caption(GAME_NAME)

	done = False
	clock = pygame.time.Clock()

	#TEST
	db.create_connection(DB_PATH)
	c = db.connect(DB_PATH)
	b = Bridge("b1", 1, 1, 1, 1, 1, 1, 1, 1)
	db.add_bridge(c, b)
	#/TEST
	
	while not done:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				done = True

		screen.fill((0, 0, 0))

		clock.tick(60)
		pygame.display.flip()

	pygame.quit()
Exemple #12
0
    def __init__(self,screen):
        self.screen = screen
        # get everything set up
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 18) # font object
        #self.canvas = olpcgames.canvas
        self.joystickobject = None 
        self.debug = True

        # create the name --> instance map for components
	self.tb_rects = {}
        self.toolList = {}
        for c in tools.allTools:
             self.toolList[c.name] = c(self)
        self.currentTool = self.toolList[tools.allTools[0].name]
        
        # set up the world (instance of Elements)
        self.world = elements.Elements(self.screen.get_size())
        self.world.renderer.set_surface(self.screen)
        
        # set up static environment
        #self.world.add.ground()
        self.world.run_physics = False

        self.bridge = Bridge(self)
        self.bridge.create_world()
Exemple #13
0
 def parsing(self, value):
     if 'vertices' in value:
         for i in value['vertices']:
             tmpVertex = Vertex()
             tmpVertex.parsing(i)
             self.verticesList.append(tmpVertex)
     if 'streets' in value:
         for i in value['streets']:
             tmpStreet = Street()
             tmpStreet.parsing(i)
             self.streetsList.append(tmpStreet)
     if 'bridges' in value:
         for i in value['bridges']:
             tmpBridge = Bridge()
             tmpBridge.parsing(i)
             self.bridgesList.append(tmpBridge)
     if 'weight' in value:
         self.weight.parsing(value['weight'])
Exemple #14
0
 def parsing (self,value):
     if 'vertices' in value:
         for i in value['vertices']:
             tmpVertex = Vertex()
             tmpVertex.parsing(i)
             self.verticesList.append(tmpVertex)
     if 'streets' in value:
         for i in value['streets']:
             tmpStreet = Street()
             tmpStreet.parsing(i)
             self.streetsList.append(tmpStreet)
     if 'bridges' in value:
         for i in value['bridges']:
             tmpBridge = Bridge()
             tmpBridge.parsing(i)
             self.bridgesList.append(tmpBridge)
     if 'weight' in value:
         self.weight.parsing(value['weight'])
Exemple #15
0
 def create_bridge(self, tg_group_id, irc_server_description, channel, token, validated=False, save_to_db=False,
                   only_add_channel=False):
     irc_connection = self.irc_connections.get_or_create_irc_server_by_description(irc_server_description)
     irc_channel = irc_connection.join_channel(channel, only_add=only_add_channel)
     bridge = Bridge(irc_channel, tg_group_id, validated, self, token)
     self.bridges[tg_group_id] = bridge
     if save_to_db:
         dbc = DatabaseConnection()
         dbc.add_bridge(bridge)
     return True
Exemple #16
0
def main():
    parser = ArgumentParser()
    parser.add_argument('-c', '--config-file', default='config.yml')
    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('-Q', '--query')

    args = parser.parse_args()

    if args.debug:
        configure_logger(logging.DEBUG)
    else:
        configure_logger(logging.INFO)

    with open(args.config_file) as fp:
        config = yaml.load(fp)

    jira_client = JIRA(server=config['jira_url'],
                       basic_auth=(config['jira_username'],
                                   config['jira_password']))

    sfdc_oauth2 = OAuth2(client_id=config['sfdc_client_id'],
                         client_secret=config['sfdc_client_secret'],
                         username=config['sfdc_username'],
                         password=config['sfdc_password'],
                         auth_url=config['sfdc_auth_url'])
    
    sfdc_client = Client(sfdc_oauth2)

    storage_path = os.path.join(config['storage_dir'], 'state_cftest.yml')
    tmp_path = os.path.join(config['storage_dir'], 'tmp_state_cftest.yml')

    store = Store(FileBackend(storage_path, tmp_path))

    bridge = Bridge(sfdc_client, jira_client, store, config)

    if args.query:
        bridge.issue_jql = args.query

    bridge.sync_issues()
Exemple #17
0
    def start(self):
        args = (self._running,)

        if self._manager is not None:
            root = findroot(self._manager)
            parent, child = Pipe()
            self._bridge = Bridge(root, socket=parent)
            self._bridge.start()

            args = (self._running, child,)

        self._process = _Process(target=self.__main__, args=args)
        self._process.daemon = True
        if HAS_MULTIPROCESSING == 2:
            setattr(self._process, "isAlive", self._process.is_alive)

        self._running.acquire()
        self._running.value = True
        self._running.release()
        self._process.start()
Exemple #18
0
#!/usr/bin/env python

import json
from pyswip.prolog import PrologError

from bridge import Bridge
from agent import Agent
from world import World

# Bridge is the Python-Prolog bridge
bridge = Bridge()

# World is a container for the map and its items
world = World(open('map.txt'), open('items.txt'))

# These are the actions taken by Prolog
action_list = []

# The agent will use the bridge to communicate from and to Prolog.
# It will store taken actions on action_list, and use the world as a support.
agent = Agent(bridge, action_list, world)

# This is the main loop.
while True:

  action = bridge.best_action()
  # print action
  if action:
    agent.execute(action)
  else:
    # print 'STUCK'
Exemple #19
0
class Process(_BaseComponent):

    def __init__(self, manager=None, **kwargs):
        channel = kwargs.get("channel", Process.channel)
        super(Process, self).__init__(channel=channel)

        self._manager = manager

        self._bridge = None

        self._running = _Value("b", False)

    def __main__(self, running, socket=None):
        if socket is not None:
            manager = Manager()
            bridge = Bridge(manager, socket=socket)
            self.register(manager)
            manager.start()

        try:
            self.run()
        finally:
            if socket is not None:
                while bridge or manager: pass
                manager.stop()
                bridge.stop()

    def start(self):
        args = (self._running,)

        if self._manager is not None:
            root = findroot(self._manager)
            parent, child = Pipe()
            self._bridge = Bridge(root, socket=parent)
            self._bridge.start()

            args = (self._running, child,)

        self._process = _Process(target=self.__main__, args=args)
        self._process.daemon = True
        if HAS_MULTIPROCESSING == 2:
            setattr(self._process, "isAlive", self._process.is_alive)

        self._running.acquire()
        self._running.value = True
        self._running.release()
        self._process.start()

    def run(self):
        """To be implemented by subclasses"""

    def stop(self):
        self._running.acquire()
        self._running.value = False
        self._running.release()

    def join(self):
        return hasattr(self, "_process") and self._process.join()

    @property
    def alive(self):
        if type(self._running) is _Synchronized:
            return self._running.value and self._process.isAlive()
Exemple #20
0
class PhysicsGame:
    def __init__(self,screen):
        self.screen = screen
        # get everything set up
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 18) # font object
        #self.canvas = olpcgames.canvas
        self.joystickobject = None 
        self.debug = True

        # create the name --> instance map for components
	self.tb_rects = {}
        self.toolList = {}
        for c in tools.allTools:
             self.toolList[c.name] = c(self)
        self.currentTool = self.toolList[tools.allTools[0].name]
        
        # set up the world (instance of Elements)
        self.world = elements.Elements(self.screen.get_size())
        self.world.renderer.set_surface(self.screen)
        
        # set up static environment
        #self.world.add.ground()
        self.world.run_physics = False

        self.bridge = Bridge(self)
        self.bridge.create_world()
        
    def run(self):
        self.running = True
        t = pygame.time.get_ticks()
        while self.running:
            if (pygame.time.get_ticks() - t) > 1500:
#                bridge.create_train(self)
                t = pygame.time.get_ticks()
               
            # Clear Display
            self.screen.fill((80,160,240)) #255 for white

            #draw toolbar for tools
            tb_x = 0
	    menubg = pygame.image.load('images/menubg.png').convert_alpha()
	    self.screen.blit(menubg, (0, 0))
	    menubg_rect = menubg.get_rect()
	        
            keyinput = pygame.key.get_pressed()

            if keyinput[pygame.K_ESCAPE]:
                raise SystemExit

            for event in pygame.fastevent.get():
                self.currentTool.handleEvents(event)
		if event.type == pygame.MOUSEBUTTONDOWN:
		    if event.button == 1:
			#print 'mouse pressed'
			if menubg_rect.collidepoint(event.pos):
			    print 'yeah'
			for k,v in self.tb_rects.items():
			    if v.collidepoint(event.pos):
				#print k
				self.currentTool = self.toolList[k]
		    if event.button == 3:
			self.currentTool.cancel()
	    
            for c in tools.allTools:
                tb_icon_name = c.name+'_icon'
                tb_icon_name = pygame.image.load('images/icons/'+c.icon+'.png').convert_alpha()
                self.screen.blit(tb_icon_name, (tb_x, 0))
		
		self.tb_rects[c.name] = tb_icon_name.get_rect().move(tb_x, 0)
		
                tb_x = tb_x+50
		
            # Update & Draw World
            self.world.update()
            self.world.draw()
            if self.world.run_physics:
                self.bridge.for_each_frame()

            #event = pygame.event.poll()
#                for c in tools.allTools:
#                    tb_icon_name = c.name+'_icon'
#
#                    print tb_icon_name
#                    srect = tb_icon_name.get_rect()
#                    print srect.collidepoint(event.pos)
            
            # draw output from tools
            self.currentTool.draw()

            #Print all the text on the screen
            text = self.font.render(_("Total Cost: %d") % self.bridge.cost, True, (0,0,0))
            textpos = text.get_rect(top=64)
            self.screen.blit(text,textpos)
            ratio = self.bridge.stress*100/self.bridge.capacity
            text = self.font.render(_("Stress: %d%%") % ratio, True, (0,0,0))
            textpos = text.get_rect(top=75)
            self.screen.blit(text,textpos)

            if self.bridge.train_off_screen:
                text = self.font.render(_("Train fell off the screen, press R to try again!"), True, (0,0,0))
            elif self.bridge.level_completed:
                text = self.font.render(_("Level completed, well done!!  Press T to send another train."), True, (0,0,0))
            else:
                text = self.font.render(_("Press the Spacebar to start/pause."), True, (0,0,0))
            textpos = text.get_rect(top=93)
            self.screen.blit(text,textpos)

            # Flip Display
            pygame.display.flip()  
            
            # Try to stay at 30 FPS
            self.clock.tick(40) # originally 50    

    def setTool(self,tool):
        self.currentTool.cancel()
        self.currentTool = self.toolList[tool] 
Exemple #21
0
    def run(self):
        pygame.init()
        self.screen = pygame.display.get_surface()
        # get everything set up
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 42) # font object
        #self.canvas = olpcgames.ACTIVITY.canvas
        self.joystickobject = None 
        self.debug = True

        # create the name --> instance map for components
        self.toolList = {}
        for c in tools.allTools:
             self.toolList[c.name] = c(self)
        self.currentTool = self.toolList[tools.allTools[0].name]
        
        # set up the world (instance of Elements)
        self.world = elements.Elements(self.screen.get_size())
        self.world.renderer.set_surface(self.screen)
        
        # set up static environment
        #self.world.add.ground()
        self.world.run_physics = False

        self.bridge = Bridge(self)
        self.bridge.create_world()


        self.running = True
        t = pygame.time.get_ticks()
        while self.running:
            if (pygame.time.get_ticks() - t) > 1500:
#                bridge.create_train(self)
                t = pygame.time.get_ticks()

            while gtk.events_pending():
                gtk.main_iteration()
                
            for event in pygame.event.get():
                self.currentTool.handleEvents(event, self.bridge)
            # Clear Display
            self.screen.fill((80, 160, 240)) #255 for white

            # Update & Draw World
            self.world.update()
            self.world.draw()
            if self.world.run_physics:
                self.bridge.for_each_frame()           

            # draw output from tools
            self.currentTool.draw()

            #Print all the text on the screen
            text = self.font.render(_("Total Cost: %d") % self.bridge.cost, True, (0, 0, 0))
            textpos = text.get_rect(left=12, top=12)
            self.screen.blit(text,textpos)
            ratio = self.bridge.stress * 100 / self.bridge.capacity
            text = self.font.render(_("Stress: %d%%") % ratio, True, (0, 0, 0))
            textpos = text.get_rect(left=12, top=53)
            self.screen.blit(text,textpos)

            if self.bridge.train_off_screen:
                text = self.font.render(_("Train fell off the screen, press R to try again!"), True, (0, 0, 0))
            elif self.bridge.level_completed:
                text = self.font.render(_("Level completed, well done!!  Press T to send another train."), True, (0, 0, 0))
            else:
                text = self.font.render(_("Press the Spacebar to start/pause."), True, (0, 0, 0))
            textpos = text.get_rect(left=12, top=94)
            self.screen.blit(text,textpos)

            # Flip Display
            pygame.display.flip()  
            
            # Try to stay at 30 FPS
            self.clock.tick(30) # originally 50    
Exemple #22
0
 def __init__(self, socket_map, mav_iface, send_interval):
     Bridge.__init__(self, socket_map, mav_iface, send_interval)
     recv_thread = Thread(target=self._receive)
     send_thread = Thread(target=self._send)
     recv_thread.start()
     send_thread.start()
Exemple #23
0
class Interface(object):
    '''
    Provide similar interfaces to iMacros
    
    >>> imacros = Interface()

    # >>> imacros.iimInit('-ie')
    # 1
    # >>> imacros.iimPlay('Z:/iMacrosDemo/FillForm.iim')
    # 1

    >>> imacros.iimInit('-fx')
    1
    >>> imacros.iimPlay('/home/yuntao/Downloads/iMacrosDemo/FillForm.iim')
    1

    # >>> imacros.iimExit()
    # 1

    '''

    RE_INIT_COMMAND = re.compile(r'^-(\w+)(?:\s+(.*))?$')

    def __init__(self):
        self.bridge = Bridge()

    @handle_retcode
    def iimInit(self, command, openNewBrowser=True, timeout=False):
        '''
        Setup new browser driver.
        See http://wiki.imacros.net/iimInit%28%29 for more info.
        '''
        # openNewBrowser is ignored, since we always open new window
        if not command:
            command = '-ie'
        match = re.match(self.RE_INIT_COMMAND, command)
        if not match:
            raise ValueError('Wrong command for iimInit')
        self.bridge.set_browser(match.group(1))
        self.bridge.start_driver()
        if timeout > 0:
            self.bridge.set_builtin_variables({'!TIMEOUT_MACRO': int(timeout)})

    @handle_retcode
    def iimPlay(self, macro, timeout=False):
        '''
        Start browser process if it is not started yet.  Replay macro.
        See http://wiki.imacros.net/iimPlay%28%29 for more info.
        '''
        if timeout > 0:
            self.bridge.set_builtin_variables({'!TIMEOUT': int(timeout)})
        return self.bridge.execute_script(macro)

    @handle_retcode
    def iimSet(self, name, value):
        '''
        Set user variable for next macro replay.
        Should be called before each iimPlay() call to take effect.
        See http://wiki.imacros.net/iimSet%28%29 for more info.
        '''
        self.bridge.set_variables({name: value})

    @handle_retcode
    def iimDisplay(self, message, timeout=0):
        '''
        Displays a message in the browser
        See http://wiki.imacros.net/iimDisplay%28%29 for more info.
        '''
        # This feature is not supported yet
        logger.warn('Not supported yet')

    @handle_retcode
    def iimExit(self, timeout=0):
        '''
        Closes browser instance.
        See http://wiki.imacros.net/iimExit%28%29 for more info.
        '''
        self.bridge.reset()

    def iimGetLastError(self, index=-1):
        '''
        Returns the text associated with the last error.
        See http://wiki.imacros.net/iimGetLastError%28%29 for more info.
        '''
        return self.bridge.errors[index]

    def iimGetLastExtract(self, index=-1):
        '''
        Returns the contents of the !EXTRACT variable.
        See http://wiki.imacros.net/iimGetLastExtract%28%29 for more info.
        '''
        return self.bridge.extracts[index]

    @handle_retcode
    def iimTakeBrowserScreenshot(self, path, img_type, timeout=0):
        '''
        Takes screenshot of browser or web page
        See http://wiki.imacros.net/iimTakeBrowserScreenshot%28%29 for more info.
        '''
        raise NotImplementedError, 'Not implemented yet'

    @handle_retcode
    def iimGetLastPerformance(self, index=0):
        '''
        Returns the total runtime and STOPWATCH data for the most recent macro run.
        Returned object is tuple where first value indicates data presence,
        second value is STOPWATCH name, third is STOPWATCH value.
        If index equals 1 then total runtime is returned.

        See http://wiki.imacros.net/iimGetLastPerformance for more info.
        '''
        raise NotImplementedError, 'Not implemented yet'
Exemple #24
0
 def __init__(self):
     self.bridge = Bridge()