示例#1
0
def _create_database():
    """Create database from Resources/SQL/create.sql script"""
    connection = sql.connect(res('sql\\connection'))
    with open(res('sql\\create'), 'r') as script:
        create = script.read().replace('\n', ' ').split(';')
        for table in create:
            connection.execute(table)
    connection.commit()
    connection.close()
示例#2
0
def _insert_combined_object(cursor, obj):
    parts = []
    for part in obj.parts:
        part_id = _insert_basic_object(cursor, part)
        parts.append(part_id)

    cursor.execute(res('sql\\insert\\combined_object'),
                   [None, obj.type.value, obj.width.value, obj.height.value])
    combined_id = cursor.lastrowid
    for part_id in parts:
        cursor.execute(res('sql\\insert\\combined_object_parts'),
                       [combined_id, part_id])
    cursor.execute(res('sql\\insert\\object'), [None, None, combined_id])
    return combined_id
示例#3
0
    def run(self):
        """Main loop of server. Never start server using run, use start instead

        Establish communication with agent on new port and start listening for messages
        """
        self.receive_socket.bind(self.address)
        self.send_socket.connect(self.send_address)
        self.address = (res('tcp_server\\ip'), self.receive_socket.getsockname()[1])
        self._send('REGISTER|%s:%s' % (self.address[0], self.address[1]))
        self.receive_socket.settimeout(0.5)
        self.receive_socket.listen(1)
        print 'agent server started'
        while not self._stop:
            try:
                connection, client_address = self.receive_socket.accept()
            except socket.timeout:
                sleep(1)
            except socket.error:
                print 'agent server error'
                self.stop()
            else:
                while not self._stop:
                    try:
                        message = self._receive(connection)
                    except socket.timeout:
                        print 'agent server timeout'
                    except socket.error:
                        print 'agent server error'
                        self.stop()
                    else:
                        self.process_request(message)
        self.send_socket.close()
        self.receive_socket.close()
        print 'agent server stopped'
示例#4
0
 def _receive(self, connection):
     """Receive message from connected server"""
     chunks = ''
     command = ''
     if self._overflow is not None:
         chunks = self._overflow
         self._overflow = None
     buffer_size = res('tcp_server\\buffer_size')
     timeouts = 0
     connection.settimeout(0.1)
     while True:
         try:
             chunk = connection.recv(buffer_size)
         except socket.timeout:
             timeouts += 1
             if timeouts == 5:
                 break
         except socket.error, e:
             if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
                 break
             else:
                 break
         else:
             if not chunk:
                 break
             chunks += chunk
             timeouts = 0
示例#5
0
    def run(self):
        """Main loop of server. Never start server using run, use start instead

        Connect to server, register self and start listening for messages
        """
        self.receive_socket.bind(self.address)
        self.receive_socket.settimeout(2)
        self.receive_socket.listen(1)
        self.address = (ares('agent_info\\ip'),
                        self.receive_socket.getsockname()[1])
        self.send_socket.connect(
            (res('tcp_server\\ip'), res('tcp_server\\server_port')))
        self._send(
            'REGISTER|%s:%d|%s' %
            (self.address[0], self.address[1], ares('agent_info\\name')))
        timeouts = 0
        if main_loop.Main.debug_tcp:
            print '[TCP] Server started'
        while not self._stop:
            try:
                connection, client_address = self.receive_socket.accept()
            except socket.timeout:
                sleep(0.5)
                timeouts += 1
                if timeouts == 5:
                    self.stop()
            except socket.error:
                if main_loop.Main.debug_tcp:
                    print '[TCP] Socket error'
                self.stop()
            else:
                while not self._stop:
                    try:
                        message = self._receive(connection)
                    except socket.timeout:
                        if main_loop.Main.debug_tcp:
                            print '[TCP] Socket timeout'
                    except socket.error:
                        if main_loop.Main.debug_tcp:
                            print '[TCP] Socket error'
                        self.stop()
                    else:
                        self.process_request(message)
        if main_loop.Main.debug_tcp:
            print '[TCP] Server stopped'
        self.send_socket.close()
        self.receive_socket.close()
示例#6
0
def _insert_basic_object(cursor, obj):
    symbols = []
    for symbol in obj.symbols:
        cursor.execute(res('sql\\insert\\shape'), [
            None, symbol.type.value, symbol.width.value, symbol.height.value,
            symbol.color.value, symbol.pattern.value,
            symbol.pattern_color.value
        ])
        symbols.append(cursor.lastrowid)
    cursor.execute(res('sql\\insert\\shape'), [
        None, obj.type.value, obj.width.value, obj.height.value,
        obj.color.value, obj.pattern.value, obj.pattern_color.value
    ])
    shape = cursor.lastrowid
    for symbol in symbols:
        cursor.execute(res('sql\\insert\\symbol'), [shape, symbol])
    cursor.execute(res('sql\\insert\\object'), [None, shape, None])
    return shape
示例#7
0
def select():
    """Retrieve objects from database"""
    connection = _connect()
    cursor = connection.cursor()
    with open(res('sql\\select')) as script:
        script = script.read().replace('\n', ' ').split(';')
        cursor.execute(script[0])
        objects = cursor.fetchall()
        cursor.execute(script[1])
        symbols = cursor.fetchall()
        cursor.close()
        connection.close()
    list = []
    for obj in objects:
        syms = []
        for sym in [s for s in symbols if s[0] == obj[1]]:
            syms.append(
                Shape(enums.Shape(sym[3]), enums.Size(sym[4]),
                      enums.Size(sym[5]), enums.Color(sym[6])))
        list.append(
            Shape(enums.Shape(obj[3]), enums.Size(obj[4]), enums.Size(obj[5]),
                  enums.Color(obj[6]), syms, obj[0]))
    return list
示例#8
0
def feature_registration(feature_name, protocol=None, request_type=None, language="SL", action_receiver_id=None,
                         action_sender_id=None):
    json = _feature_registration_json(feature_name, protocol, request_type, language, action_receiver_id,
                                      action_sender_id)
    return _send_json_to_server(res('logger\\url\\features'), json)
示例#9
0
def object_registration(object_name, object_description, protocol=None, request_type=None, language="SL",
                        action_receiver_id=None, action_sender_id=None):
    json = _object_registration_json(object_name, object_description, protocol, request_type, language,
                                     action_receiver_id, action_sender_id)
    return _send_json_to_server(res('logger\\url\\objects'), json)
示例#10
0
def presence_request(agent, presence_type, protocol=None, request_type=None, language="SL", action_receiver_id=None,
                     action_sender_id=None):
    json = _presence_request_json(agent, presence_type, protocol, request_type, language, action_receiver_id,
                                  action_sender_id)
    return _send_json_to_server(res('logger\\url\\presence_requests'), json)
示例#11
0
 def turn(self, angle):
     """Turn agent right if angle is positive or left if angle is negative"""
     self._send(res('serial\\arduino\\turn').replace('?', str(angle * 1.6)))
示例#12
0
def location_inform(x_position, y_position, protocol=None, request_type=None, language="SL", action_receiver_id=None,
                    action_sender_id=None):
    json = _location_inform_json(x_position, y_position, protocol, request_type, language, action_receiver_id,
                                 action_sender_id)
    return _send_json_to_server(res('logger\\url\\locations'), json)
示例#13
0
def _connect():
    """Connect to database or create and connect to database if one doesn't exist"""
    if not isfile(res('sql\\connection')):
        _create_database()
    return sql.connect(res('sql\\connection'))
示例#14
0
 def __init__(self, context):
     super(TCPServerManager, self).__init__((res('tcp_server\\ip'), res('tcp_server\\server_port')))
     self.agents = []
     self.name = 'Manager'
     self.context = context
示例#15
0
 def distance(self):
     """arduino will return distance to obstacle from detectors"""
     self._send(res('serial\\arduino\\distance'))
示例#16
0
 def go_distance(self, distance):
     """Agent drives specified number of centimeters"""
     self._send(res('serial\\arduino\\run_distance').replace('?', str(distance)))
示例#17
0
def assessment_creation(assessment_value, object, feature, protocol=None, request_type=None, language="SL",
                        action_receiver_id=None, action_sender_id=None):
    json = _assessment_creation_json(assessment_value, object, feature, protocol, request_type, language,
                                     action_receiver_id, action_sender_id)
    return _send_json_to_server(res('logger\\url\\assessments'), json)
示例#18
0
def _send_json_to_server(relative_address, json):
    connection = httplib.HTTPConnection(res('logger\\url\\base'))
    headers = {'content-type': 'application/json'}
    connection.request("POST", relative_address, json, headers)
    return connection.getresponse()
示例#19
0
def communication_action_passing(protocol=None, request_type=None, language="SL", action_receiver_id=None,
                                 action_sender_id=None):
    json = _communication_action_passing_json(protocol, request_type, language, action_receiver_id, action_sender_id)
    return _send_json_to_server(res('logger\\url\\communicative_actions'), json)
示例#20
0
 def go(self, time=0):
     """Agent drives forward for specified number of seconds. If time not specified agent drives until stopped"""
     self._send(res('serial\\arduino\\run'))
     if time > 0:
         Timer(time, self.stop).start()
示例#21
0
def graphical_readout(image, sensor, protocol=None, request_type=None, language="SL", action_receiver_id=None,
                      action_sender_id=None):
    json = _graphical_readout_json(image, sensor, protocol, request_type, language, action_receiver_id, action_sender_id)
    return _send_json_to_server(res('logger\\url\\graphical_readouts'), json)
示例#22
0
 def stop(self):
     """Stop agent"""
     self._send(res('serial\\arduino\\stop'))
示例#23
0
def agent_registration(agent, protocol=None, request_type=None, language="SL", action_receiver_id=None,
                       action_sender_id=None):
    json = _agent_registration_json(agent, protocol, request_type, language, action_receiver_id, action_sender_id)
    return _send_json_to_server(res('logger\\url\\agents'), json)
示例#24
0
 def __init__(self):
     self._thread = Thread(target=self.run)
     self._stop = False
     self._serial = serial.Serial(res('serial\\port'), res('serial\\speed'))
     self.queue = []