示例#1
0
    def send_command(self, name, args=None, callback=None):
        promise = Promise()

        msg = {
            "name": name,
            "id": str(self.seq),
            "args": args or []
        }

        msg_enc = json.dumps(msg, separators=(',', ':'))

        try:
            with self.ws_lock:
                if self.ws is None or self.state == SpotifyAPI.DISCONNECTED:
                    return Promise.rejected(SpotifyDisconnectedError())

                pid = self.seq

                if callback:
                    promise.addCallback(callback)

                self.cmd_promises[pid] = promise
                self.seq += 1

                self.ws.send(msg_enc)

                logger.debug("Sent PID({}) with msg: {}".format(pid, msg_enc))
        except (SSLError, StreamClosed) as e:
            logger.error("SSL error ({}), attempting to continue".format(e))
            promise.rejected(SpotifyDisconnectedError())

        return promise
示例#2
0
    def send_onem2m_request(self, request):
        """
        :param openmtc_onem2m.transport.OneM2MRequest request:
        :return Promise:
        """
        p = Promise()

        try:
            client_id = request.originator.split('/')[-1]
        except (KeyError, AttributeError):
            # TODO: make this configurable
            client_id = 'ae0'

        request.op = 1 + OneM2MOperation._member_map_.keys().index(
            OneM2MOperation[request.op].name)
        if request.pc:
            request.pc = self._decode(
                encode_onem2m_content(request.pc,
                                      'application/json',
                                      path=request.to)[1])
        try:
            if request.to.startswith('//'):  # abs CSE
                request.to = '/_' + request.to[1:]
            elif request.to.startswith('/'):  # sp rel CSE
                request.to = '/~' + request.to
        except AttributeError:
            self.logger.error(
                'Could not resolve target id; defaulting to preset')
            request.to = '/' + self._target_id

        if request.ty:
            request.ty = ResourceTypeE[request.resource_type.typename].value

        self.logger.debug('Preparing request for transit: %s' % (request, ))

        promises_key = (self._target_id, request.rqi)

        def cleanup(_):
            self.logger.debug('Clearing request id %s ...' % (promises_key, ))
            del self._request_promises[promises_key]

        p.addCallback(cleanup)
        p.addErrback(cleanup)

        self._request_promises[promises_key] = p

        self._publish_message(
            self._encode({
                str(k): getattr(request, k)
                for k in self.__request_fields
                if getattr(request, k) is not None
            }),
            self._build_topic(client_id, self._target_id) + '/json',
        )

        return p
def test_exceptions():
    def throws(v):
        assert False

    p1 = Promise()
    p1.addCallback(throws)
    p1.fulfill(5)

    p2 = Promise()
    p2.addErrback(throws)
    p2.reject("Error")
示例#4
0
def test_exceptions():
    def throws(v):
        assert False

    p1 = Promise()
    p1.addCallback(throws)
    p1.fulfill(5)

    p2 = Promise()
    p2.addErrback(throws)
    p2.reject(Exception())

    assert_raises(Exception, p2.get)
示例#5
0
    def send_onem2m_request(self, request):
        """
        :param openmtc_onem2m.transport.OneM2MRequest request:
        :return Promise:
        """
        p = Promise()

        client_id = self._get_client_id_from_originator(request.originator)

        if request.ty and request.op == OneM2MOperation.create:
            request.ty = ResourceTypeE[request.resource_type.typename].value
        else:
            request.ty = None

        request.op = 1 + OneM2MOperation._member_map_.keys().index(
            OneM2MOperation[request.op].name)
        if request.pc:
            request.pc = self._decode(
                encode_onem2m_content(request.pc,
                                      'application/json',
                                      path=request.to)[1])
        if request.fc:
            request.fc = encode_onem2m_content(request.fc,
                                               'application/json',
                                               path=request.to)[1]

        if self._default_target_id:
            target_id = self._default_target_id
        else:
            _, cse_id, suffix = split_onem2m_address(request.to)
            if cse_id:
                target_id = cse_id[1:] + ('/' + suffix
                                          if request.ae_notifying else '')
            else:
                raise CSETargetNotReachable()

        self.logger.debug('Preparing request for transit: %s' % (request, ))

        promises_key = (OneM2MMQTTClient._mqtt_mask(target_id), request.rqi)

        def cleanup(_):
            self.logger.debug('Clearing request id %s ...' % (promises_key, ))
            del self._request_promises[promises_key]

        p.addCallback(cleanup)
        p.addErrback(cleanup)

        self._request_promises[promises_key] = p
        gevent.spawn_later(MQTT_RESPONSE_TIMEOUT, self._cancel_request,
                           promises_key)

        self._publish_message(
            self._encode({
                str(k): getattr(request, k)
                for k in self.__request_fields
                if getattr(request, k) is not None
            }),
            self._build_topic(client_id, target_id) + '/json',
        )

        return p