Esempio n. 1
0
  def connected(self, msg):
    res = []
    #once connected, subscribe
    res.append(stomper.subscribe(destinations.CONN_DESTINATION))
    res.append(stomper.subscribe(destinations.CMD_RES_DESTINATION))

    return tuple(res)
Esempio n. 2
0
def Connect(server):
    Log2("Connecting SmartAccess: "+ server['server_websocket'] + "....")
    ws = create_connection("ws://"+server['server_websocket'])
    sub = stomper.subscribe(server['topic1'], str(random.randint(0, 1000)), ack='auto')
    ws.send(sub)
    sub = stomper.subscribe(server['topic2'], str(random.randint(0, 1000)), ack='auto')
    ws.send(sub)
    Log2("--------------- Connect Successfully!")
    return ws
Esempio n. 3
0
    def testSubscribe(self):
        dest, ack = '/queue/all', 'client'
        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest, ack), correct)

        dest, ack = '/queue/all', 'auto'
        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest, ack), correct)

        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest), correct)
Esempio n. 4
0
    def testSubscribe(self):
        dest, ack = '/queue/all', 'client'
        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest, ack), correct)

        dest, ack = '/queue/all', 'auto'
        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest, ack), correct)

        correct = "SUBSCRIBE\ndestination: %s\nack: %s\n\n\x00\n" % (dest, ack)
        self.assertEquals(stomper.subscribe(dest), correct)
    def test_connection(self):
        self.stompProtocol.makeConnection(self.fakeTransport)
        #ignore the connection request sent. We aren't testing that here
        self.fakeTransport.clear()

        #pretend we've received successful ack of our connection request.
        #check that the host engine subscribes to the topics upon connection
        connectedMsg = """CONNECTED
session:ID:snorky.local-49191-1185461799654-3:18"""
        self.stompProtocol.dataReceived(connectedMsg)

        msg1 = stomper.subscribe(destinations.CONN_DESTINATION)
        msg2 = stomper.subscribe(destinations.CMD_RES_DESTINATION)

        self.assertTrue(msg1 in self.fakeTransport.value())
        self.assertTrue(msg2 in self.fakeTransport.value())
Esempio n. 6
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue.
        """
        stomper.Engine.connected(self, msg)

        self.log.info("senderID:%s Connected: session %s." % (
            self.senderID, 
            msg['headers']['session'])
        )

        # I originally called loopingCall(self.send) directly, however it turns
        # out that we had not fully subscribed. This meant we did not receive 
        # out our first send message. I fixed this by using reactor.callLater
        # 
        #
        def setup_looping_call():
            lc = LoopingCall(self.send)
            lc.start(2)
            
        reactor.callLater(1, setup_looping_call)

        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))

        # ActiveMQ specific headers:
        #
        # prevent the messages we send comming back to us.
        f.headers['activemq.noLocal'] = 'true'
        
        return f.pack()
Esempio n. 7
0
    def login(self):
        credentials = self.credentials
        self.instanceId = credentials['username']
        host = self.locust.host
        """Create random credentials"""
        user_pass = credentials['username'] + ":" + credentials['password']
        encoded_user_pass = b64encode(
            user_pass.encode('ascii')).decode("utf-8")
        """Create connection"""
        init_time = time.time()
        ws_url = "ws://" + host + "/device-management-service/websocket"
        ws = create_connection(
            ws_url,
            header={"Authorization": "Basic " + str(encoded_user_pass)})

        con = stomper.connect(credentials["username"],
                              credentials["password"],
                              host=ws_url,
                              heartbeats=(30000, 30000))
        ws.send(con)

        res = ws.recv()
        self.handle_message(str(res), init_time=init_time)
        """subscribe"""
        init_time = time.time()
        sub = stomper.subscribe("/user/queue/device", 0, ack='auto')
        ws.send(sub)

        res = ws.recv()
        self.handle_message(str(res), init_time=init_time)

        return ws
Esempio n. 8
0
    async def ws_auth(self) -> Dict[Any, Any]:
        """ws private (user account balance request)"""
        listen_key = (
            await self.rest_auth(CONSTANTS.USER_ID_PATH_URL)
        )["id"]  # this is the getUserId from the github latoken api client library
        client: WSAssistant = await self.api_factory.get_ws_assistant()
        await client.connect(ws_url=web_utils.ws_url(self.domain),
                             ping_timeout=CONSTANTS.WS_HEARTBEAT_TIME_INTERVAL)

        msg_out = stomper.Frame()
        msg_out.cmd = "CONNECT"
        msg_out.headers.update({"accept-version": "1.1", "heart-beat": "0,0"})
        connect_request: WSRequest = WSRequest(payload=msg_out.pack(),
                                               is_auth_required=True)
        await client.send(connect_request)
        await client.receive()
        path_params = {'user': listen_key}
        msg_subscribe_account = stomper.subscribe(
            CONSTANTS.ACCOUNT_STREAM.format(**path_params),
            CONSTANTS.SUBSCRIPTION_ID_ACCOUNT,
            ack="auto")
        _ = await client.subscribe(request=WSRequest(
            payload=msg_subscribe_account))

        response = []
        async for ws_response in client.iter_messages():
            msg_in = stomper.Frame()
            data = msg_in.unpack(ws_response.data.decode())
            event_type = int(data['headers']['subscription'].split('_')[0])
            if event_type == CONSTANTS.SUBSCRIPTION_ID_ACCOUNT:
                response.append(ujson.loads(data["body"])["payload"])
                break
        await client.disconnect()
        return response[0]
    def sendDataWithDataId(self,id, data):

        

        dataObject = {"sensorId": id,"data":data}
        threading.Timer(self.timeInterval, self.sendData).start()
        websocket.enableTrace(True)

          # Connecting to websocket
        ws = websocket.create_connection("ws://websocketapi-env.eba-gxghbmt3.us-east-1.elasticbeanstalk.com//sensor-data")

          # Subscribing to topic
        client_id = str(random.randint(0, 1000))
        sub = stomper.subscribe("/topic/collect", client_id, ack='auto')
        ws.send(sub)

          # Sending some message
          #print(dataObject)
        ws.send(stomper.send("/app/API/data", dataObject))

        while True:
            print("Receiving data: ")
            d = ws.recv()
            print(d)
            return
Esempio n. 10
0
 def subscribe(self):  
     u = uuid.uuid1()    
     idx = str(u)
     cmd = stomper.subscribe(self.destination, idx=idx,ack='client') 
     self._send(cmd) 
     self.state['subscribed'] = True    
     self.state['receiving'] = True 
     self.log("Stomp Socket Subscribing to: %s"%(self.destination))
  def connected(self, msg):
    res = []
    #once connected, subscribe
    res.append(stomper.subscribe(destinations.CMD_REQ_DESTINATION))

    #announce ourselves
    res.append( self.words['HELLO']().howToSay() )
 
    return tuple(res)
Esempio n. 12
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue.
        """
        super(MyStomp, self).connected(msg)

        self.log.info("connected: session %s" % msg['headers']['session'])
        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))
        return f.pack()
Esempio n. 13
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue.
        """
        super(MyStomp, self).connected(msg)

        self.log.info("receiverId <%s> connected: session %s" % (self.receiverId, msg['headers']['session']))
        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))
        return f.pack()
Esempio n. 14
0
    def connected(self, msg):
        res = []
        #once connected, subscribe
        res.append(stomper.subscribe(destinations.CMD_REQ_DESTINATION))

        #announce ourselves
        res.append(self.words['HELLO']().howToSay())

        return tuple(res)
Esempio n. 15
0
  def connected(self, msg):
    res = []
    #once connected, subscribe
    res.append(stomper.subscribe(destinations.CMD_REQ_DESTINATION))

    #announce ourselves
    res.append( words.HELLO().howToSay(self) )
 
    #FIXME: even better whould be to wait for the HELLO back from the host
    self._startSendingBeacons()

    return tuple(res)
Esempio n. 16
0
	def connected(self, msg):
		"""Once I've connected I want to subscribe to my the message queue."""
		super(StompMessageProcessor, self).connected(msg)
		
		self.pygo_mp.logger.info("=> PyGoWave RPC Server ready <=")
		
		f = stomper.Frame()
		f.unpack(stomper.subscribe("wavelet_rpc_singlethread"))
		f.headers["exchange"] = "wavelet.topic"
		f.headers["routing_key"] = "#.#.clientop"
		f.headers["exchange_type"] = "topic"
		return f.pack()
Esempio n. 17
0
    def connect(self, clientId):
        try:
            self.ws = create_connection(self.rcServerUri)
            self.receiver = ReceiveThread(self)
            self.receiver.start()

            self.ws.send("CONNECT\naccept-version:1.0,1.1,2.0\n\n\x00\n")
            sub = stomper.subscribe("/user/rc/client-ack",
                                    clientId,
                                    ack='auto')
            self.ws.send(sub)
            sub = stomper.subscribe("/rc/" + str(clientId) + "/replayposition",
                                    clientId,
                                    ack='auto')
            self.ws.send(sub)

            send_message = stomper.send("/app/rcclient", str(clientId))
            self.ws.send(send_message)

            self.heartbeat = HeartbeatThread(self, clientId)
            self.heartbeat.start()
        except Exception as e:
            self.frame.SetStatusText(self.rcServerUri + ': ' + str(e), 2)
Esempio n. 18
0
def on_open(ws, c=config):
    print('on_open:', 'Connection opened!')
    connDATA = c.getConf()
    """
    stomp connect()
    lo interesante de marcar aqui son los parametos de conexion.
    Como podemos ver mandar fruta e igualmente se conecta.
    Funciona xq websockets ya tiene la conexion abierta.
    El connect del stomp es puramente formal 
    """
    msg = stomper.connect('DUMMY_USER', 'DUMMY_PW', 'DUMMY_HOST', (0,0))
    print('stomp connect:', msg)
    ws.send(msg)

    f = stomper.Frame()
    f.unpack(stomper.subscribe(connDATA['endpoint']['bymaMD'], 'bymaMD', ack='auto'))
    fMsg = f.pack()
    ws.send(fMsg)
Esempio n. 19
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue.
        """
        stomper.Engine.connected(self, msg)

        self.log.info("Connected: session %s. Begining say hello." % msg['headers']['session'])
        lc = LoopingCall(self.send)
        lc.start(1)

        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))

        # ActiveMQ specific headers:
        #
        # prevent the messages we send comming back to us.
        f.headers['activemq.noLocal'] = 'true'
        
        return f.pack()
Esempio n. 20
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue.
        """
        stomper.Engine.connected(self, msg)

        self.log.info("Connected: session %s. Begining say hello." % msg['headers']['session'])
        lc = LoopingCall(self.send)
        lc.start(1)

        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))

        # ActiveMQ specific headers:
        #
        # prevent the messages we send comming back to us.
        f.headers['activemq.noLocal'] = 'true'
        
        return f.pack()
Esempio n. 21
0
    async def respond_using_ws(command: DittoCommand, count, delay_in_sec, request_id, response_url):
        logging.info("Responding over url= %s; delay= %s ms", response_url, delay_in_sec)
        ws = create_connection(response_url)

        idx = str(random.randint(0, 1000))
        sub = stomper.subscribe("/data", idx, ack='auto')
        ws.send(sub)
        for i in range(count):
            post_data = MeasurementData(request_id, count, i)
            time.sleep(delay_in_sec)
            msg = stomper.send(dest="/app/data", msg=post_data.to_json(), content_type="application/json")
            logging.debug("Going to send stomp message: %s", msg)
            ws.send(msg)
            # ws.send("some trash")
            # await ws.send(post_data.to_json())
            # await ws.recv()

        ws.send(stomper.unsubscribe(idx))
Esempio n. 22
0
    def connected(self, msg):
        stomper.Engine.connected(self, msg)

        self.log.info("Nickname:{} Connected: session {}.".format(
            self.nickname,
            msg['headers']['session'])
        )
        print "\rWelcome to chat!"

        def setup_looping_call():
            lc = LoopingCall(self.send)
            lc.start(0.3)

        reactor.callLater(0, setup_looping_call)

        f = stomper.Frame()
        f.unpack(stomper.subscribe(DESTINATION))
        f.headers['activemq.noLocal'] = 'true'
        return f.pack()
Esempio n. 23
0
	def connected(self, msg):
		"""Once I've connected I want to subscribe to my the message queue(s)."""
		super(StompMessageProcessor, self).connected(msg)
		
		self.proto.factory.protocolConnected(self.proto)
		
		mqis = self.proto.service.messageQueueInfo()
		
		if not isinstance(mqis, list):
			mqis = [mqis]
		
		out = ""
		for mqi in mqis:
			f = stomper.Frame()
			f.unpack(stomper.subscribe(mqi["queue_name"]))
			f.headers["exchange"] = mqi["exchange"]
			f.headers["routing_key"] = mqi["routing_key"]
			f.headers["exchange_type"] = mqi["exchange_type"]
			out += f.pack()
		return out
Esempio n. 24
0
    def connected(self, msg):
        """Once I've connected I want to subscribe to my the message queue(s)."""
        super(StompMessageProcessor, self).connected(msg)

        self.proto.factory.protocolConnected(self.proto)

        mqis = self.proto.service.messageQueueInfo()

        if not isinstance(mqis, list):
            mqis = [mqis]

        out = ""
        for mqi in mqis:
            f = stomper.Frame()
            f.unpack(stomper.subscribe(mqi["queue_name"]))
            f.headers["exchange"] = mqi["exchange"]
            f.headers["routing_key"] = mqi["routing_key"]
            f.headers["exchange_type"] = mqi["exchange_type"]
            out += f.pack()
        return out
    def subscribe_person_update(self):
        try:
            ws = create_connection(config.get('websocket-endpoint'))
            ws.send(self.WS_HEADER)
            sub = stomper.subscribe('/topic/person-update', 1)
            ws.send(sub)

            print(Messages.AN_CONNECTOR_CONNECTION_SUCCESSFUL)

            while True:
                try:
                    payload = stomper.unpack_frame(ws.recv())['body']
                    person = Person(payload)
                    self.last_interacting_person = person
                except json.decoder.JSONDecodeError:
                    print(Messages.AN_CONNECTOR_PAYLOAD_ERROR)
                except WebSocketConnectionClosedException:
                    print(Messages.AN_CONNECTOR_CONNECTION_CLOSED)
                    self.subscribe_person_update()
                    break

        except ConnectionRefusedError:
            self.subscribe_person_update()
Esempio n. 26
0
 def subscribe(self, qname):
     self.transport.write(stomper.subscribe(qname))
 def connected(self, msg):
   #once connected, subscribe
   return ( stomper.subscribe(destinations.CONN_DESTINATION), 
            stomper.subscribe(destinations.CMD_RES_DESTINATION) )
Esempio n. 28
0

# pose_close_button = False

if __name__ == '__main__':
    # Connecting to websocket
    print("START FUNCTION")
    ws = websocket.create_connection("ws://j4a404.p.ssafy.io:8000/itda/python")
    print("CONNECTION OK")

    # Subscribing to topic
    client_id = str(random.randint(0, 1000))
    ip = get("https://api.ipify.org").text
    hash_ip = hashlib.sha256(ip.encode())
    hash_ip = hash_ip.hexdigest()
    sub = stomper.subscribe(f"/socket/{hash_ip}/send", client_id, ack='auto')
    ws.send(sub)

    # 초음파
    GPIO.setmode(GPIO.BCM)

    trig = 2
    echo = 3

    GPIO.setup(trig, GPIO.OUT)
    GPIO.setup(echo, GPIO.IN)

    while True:
        distance = sensor()

        if distance < 20:
"""
This module is a websocket client with stomp protocol.
"""
import websocket
import stomper

DEST = "/topic/greetings"

if __name__ == "__main__":
    URI = "ws://localhost:8080/hello"
    websocket.enableTrace(True)
    ws = websocket.create_connection(URI)
    print(ws)

    print("create sub protocol")
    sub = stomper.subscribe(DEST, 2, ack='auto')
    print(sub)
    print("send protocol")
    ws.send(sub)
    while True:
        result = ws.recv()
        print(result)

    ws.close()
Esempio n. 30
0
 def subscribe(self, dest, **headers):
     f = stomper.Frame()
     f.unpack(stomper.subscribe(dest))
     f.headers.update(headers)
     self.transport.write(f.pack())
Esempio n. 31
0
 def subscribe(self, dest, **headers):
     f = stomper.Frame()
     f.unpack(stomper.subscribe(dest))
     f.headers.update(headers)
     self.transport.write(f.pack())
Esempio n. 32
0
#
pprint.pprint(stomper.unpack_frame(response))

resp = responder.react(stomper.unpack_frame(response))

# The engine will store the session id from the CONNECTED
# response. It doesn't generate a message response. It
# just returns an empty string.


# After a successful connect you might want to subscribe
# for messages from a destination and tell the server you'll
# acknowledge all messages.
#
DESTINATION='/queue/inbox'
sub = stomper.subscribe(DESTINATION, ack='client')

# Send the message to the server...
#


# At some point in the future you'll get messages
# from the server. An example message might be:
#
server_msg = """MESSAGE
destination: /queue/a
message-id: some-message-id

hello queue a

\x00
Esempio n. 33
0
 def subscribe(self, qname):
     self.transport.write(stomper.subscribe(qname))
Esempio n. 34
0
 def connected(self, msg):
     #once connected, subscribe
     return (stomper.subscribe(destinations.CONN_DESTINATION),
             stomper.subscribe(destinations.CMD_RES_DESTINATION))
Esempio n. 35
0
    def suscribir(self, c=config):
        connDATA = c.getConf()

        f = stomper.Frame()
        f.unpack(stomper.subscribe(connDATA['endpoint']['bymaMD'], 'bymaMD', ack='auto'))
        return f.pack()