示例#1
0
    def receive(self):
        ping_timeout = timedelta(seconds=self.activity_timeout)
        connection_timeout = timedelta(seconds=ping_timeout.seconds * 2)
        ping_sent = False
        last_heartbeat = datetime.now()

        while True:
            try:
                if datetime.now() - last_heartbeat > ping_timeout and \
                       not ping_sent:
                    self.queue.put(BusinessObject({'event': 'ping'}, None))
                    ping_sent = True
                elif datetime.now() - last_heartbeat > connection_timeout and \
                     ping_sent is True:
                    raise ConnectionTimeout(
                        "Timeout! Last object received at %s (is the server responding to ping?)"
                        % last_heartbeat)

                if not self.queue.empty():
                    rlist, wlist, xlist = select.select([self.socket],
                                                        [self.socket], [], 0.2)
                    if len(wlist) > 0:
                        obj = self.queue.get()
                        obj.serialize(socket=self.socket)
                else:
                    rlist, wlist, xlist = select.select([self.socket], [], [],
                                                        0.2)
                    if len(rlist) > 0:
                        obj = BusinessObject.read_from_socket(self.socket)
                        if obj is None:
                            raise InvalidObject

                        last_heartbeat = datetime.now()
                        ping_sent = False

                        if obj.event == 'services/discovery':
                            response = self.handle_discovery(obj)
                            if response is not None:
                                self.queue.put(response)
                        elif self.should_handle(obj):
                            response = self.handle(obj)
                            if response is not None:
                                self.queue.put(response)
                # TODO: implement functionality for other than pure stimuli induced behavior
            except InvalidObject, ivo:
                self.socket.close()
                break
            except KeyboardInterrupt, kbi:
                self.socket.close()
                raise kbi
def make_list_request():
    return BusinessObject(
        {
            'event': 'services/request',
            'name': 'clients',
            'request': 'list'
        }, None)
示例#3
0
 def register(self):
     BusinessObject(
         {
             'event': "services/register",
             'name': self.__class__.__service__
         }, None).serialize(socket=self.socket)
     self.logger.info("Registered to server as service '%s'" %
                      self.__class__.__service__)
示例#4
0
 def subscribe(self):
     BusinessObject(
         {
             'event': "routing/subscribe",
             'echo': False,
             'subscriptions': ['@*']
         }, None).serialize(socket=self.socket)
     self.logger.info("Subscribed to server")
示例#5
0
def make_legacy_subscription_object():
    metadata = {
        'event': 'routing/subscribe',
        'receive-mode': 'all',
        'types': 'all'
        }
    result = BusinessObject(metadata, None)
    logger.info("Subscription object: " + str(result.metadata))
    return result
def make_join_request():
    return BusinessObject(
        {
            'event': 'services/request',
            'name': 'clients',
            'request': 'join',
            'client': "ROBOT",
            'user': env['USER']
        }, None)
示例#7
0
    def handle_discovery(self, obj):
        metadata = {
            'event': "services/discovery/reply",
            'name': self.__class__.__service__,
            'in-reply-to': obj.id
        }

        if 'route' in obj.metadata:
            metadata['to'] = obj.metadata['route'][0]

        return BusinessObject(metadata, None)
示例#8
0
    def receive(self):
        ping_timeout = timedelta(seconds=self.activity_timeout)
        connection_timeout = timedelta(seconds=ping_timeout.seconds * 2)
        ping_sent = False
        last_heartbeat = datetime.now()

        while True:
            try:
                if datetime.now() - last_heartbeat > ping_timeout and \
                       not ping_sent:
                    self.queue.put(BusinessObject({'event': 'ping'}, None))
                    ping_sent = True
                elif datetime.now() - last_heartbeat > connection_timeout and \
                     ping_sent is True:
                    raise ConnectionTimeout("Timeout! Last object received at %s (is the server responding to ping?)" % last_heartbeat)

                if not self.queue.empty():
                    rlist, wlist, xlist = select.select([self.socket], [self.socket], [], 0.2)
                    if len(wlist) > 0:
                        obj = self.queue.get()
                        obj.serialize(socket=self.socket)
                else:
                    rlist, wlist, xlist = select.select([self.socket], [], [], 0.2)
                    if len(rlist) > 0:
                        obj = BusinessObject.read_from_socket(self.socket)
                        if obj is None:
                            raise InvalidObject

                        last_heartbeat = datetime.now()
                        ping_sent = False

                        if obj.event == 'services/discovery':
                            response = self.handle_discovery(obj)
                            if response is not None:
                                self.queue.put(response)
                        elif self.should_handle(obj):
                            response = self.handle(obj)
                            if response is not None:
                                self.queue.put(response)
                # TODO: implement functionality for other than pure stimuli induced behavior
            except InvalidObject, ivo:
                self.socket.close()
                break
            except KeyboardInterrupt, kbi:
                self.socket.close()
                raise kbi
    def add_client(self, obj):
        new_client = Client(obj)
        removable = None
        for client in self.clients:
            if client.routing_id == new_client.routing_id:
                removable = client
        if removable:
            self.clients.remove(removable)

        self.clients.append(new_client)
        self.logger.info(u"{0} registered!".format(repr(new_client)))

        metadata = {
            'event': 'services/reply',
            'in-reply-to': obj.id,
            'to': new_client.routing_id,
            'message': 'Succesfully registered!'
        }
        return BusinessObject(metadata, None)
示例#10
0
    def handle(self, obj):
        self.logger.debug(u"Request {0}".format(obj.metadata))

        try:
            with timeout(5):
                out = urllib2.urlopen('http://biomine.cs.helsinki.fi/oberstdorf/?plain=true')
                reader = getreader('utf-8')(out)
                title = reader.read()

            metadata = {'event': 'services/reply',
                        'in-reply-to': obj.id,
                        'size': len(title),
                        'type': 'text/plain; charset=utf-8'}

            if 'route' in obj.metadata:
                metadata['to'] = obj.metadata['route'][0]

            reply = BusinessObject(metadata, bytearray(title, encoding='utf-8'))
            self.logger.debug(u"Reply {0}".format(reply.metadata))
            return reply
        except Exception, e:
            self.logger.error(u"{0}".format(e))
示例#11
0
    def handle_list(self, obj):
        requesting_client = self.client_for_sender(obj)

        if requesting_client is not None:
            routing_id = requesting_client.routing_id
        else:

            if 'route' in obj.metadata:
                routing_id = obj.metadata['route'][0]
            else:
                self.logger.warning(
                    u"List request {0} with no and no route!".format(
                        obj.metadata))
                return

        clients = []
        for client in self.clients:
            clients.append({
                'user': client.user,
                'client': client.client,
                'routing-id': client.routing_id,
                'server': client.server
            })

        metadata = {
            'event': 'services/reply',
            'in-reply-to': obj.id,
            'clients': clients,
            'to': routing_id
        }

        reply = {'clients': clients}
        payload = bytearray(json.dumps(reply, ensure_ascii=False),
                            encoding='utf-8')
        metadata['size'] = len(payload)

        return BusinessObject(metadata, payload)
示例#12
0
def make_object_with_natures(natures):
    return BusinessObject({'natures': natures[0]}, None)
示例#13
0
def make_application_object(payload):
    metadata_dict = {
        'size': len(payload),
        'type': "application/octet-stream"
    }
    return BusinessObject(metadata_dict, bytearray(payload, encoding='utf-8'))
示例#14
0
def make_text_object(text, natures=[]):
    result = BusinessObject.from_string(text)
    result.metadata['natures'] = natures
    return result
示例#15
0
def make_event(event, natures=[]):
    return BusinessObject({'event': event, 'natures': natures}, None)
示例#16
0
            'event': 'services/reply',
            'in-reply-to': obj.id,
            'type': 'text/json'
        }

        if 'route' in obj.metadata:
            metadata['to'] = obj.metadata['route'][0]

        if error:
            reply = {'error': str(error)}

        payload = bytearray(json.dumps(reply, ensure_ascii=False),
                            encoding='utf-8')
        metadata['size'] = len(payload)

        return BusinessObject(metadata, payload)

    def insert(self, obj):
        payload = json.loads(obj.payload.decode('utf-8'))

        readings = []

        for item in payload:
            readings.append(TemperatureReading(item['sensor'], item['value']))

        for reading in readings:
            self.session.add(reading)

        self.session.commit()
        return {u'status': 'Success!'}