Ejemplo n.º 1
0
def msg_size_test(broker, url, psize):
    if( broker == 'mqtt' or broker == 'amqp' ):
        p_client = None
        s_client = None
        if( broker == 'mqtt' ):
            p_client = mqttClient(1, url)
            s_client = mqttClient(2, url)
            topic = {'topic': 'x', 'psize': psize, 'qos':0 }
            kwargs_p = {'nr':10, 'ival':1}
            msg_s = {'topic':'x', 'qos':0, 'cb':on_message}
            kwargs_s = {'timeout' : 20}
        else:
            p_client = amqpClient(1, url)
            s_client = amqpClient(2, url)
            topic = [ {'exchange': 'x', 'routing_key': '', 'psize': psize } ]
            kwargs_p = {'nr': 10, 'ival': 1}
            msg_s = {'exchange': 'x', 'cb': callback, 'no_ack': True}
            kwargs_s = {'timeout' : 20}
            
        p_client.connect()
        s_client.connect()

        s_client.subscribe(msg_s, kwargs_s)
        s_client.start_subscribe_timeout(topic, kwargs_s)
        
        time.sleep(1)
        
        p_client.publish(topic, kwargs_p)

        ## wait until they are terminated, make sure to disconnect so that connections at the host are freed
        p_client.waitForClient()
        s_client.waitForClient()
        
    return np.median(timevals), np.mean(timevals), np.var(timevals)
Ejemplo n.º 2
0
def var_sub_test(broker, url, nr_pub, nr_con):
    if (broker == 'mqtt' or broker == 'amqp'):
        p_clients = []
        s_clients = []
        for c in range(0, nr_pub + nr_con):
            client = None
            topic = None
            kwargs = None

            if (broker == 'mqtt'):
                client = mqttClient(c, url)
                topic = {'topic': 'x', 'psize': 1, 'qos': 0}
                kwargs_p = {'nr': 1, 'ival': 1}
                msg_s = {'topic': 'x', 'qos': 0, 'cb': on_message}
                kwargs_s = {'timeout': 10}
            else:
                client = amqpClient(c, url)
                topic = [{'exchange': 'x', 'routing_key': '', 'psize': 1}]
                kwargs_p = {'nr': 1, 'ival': 1}
                msg_s = {'exchange': 'x', 'cb': callback, 'no_ack': True}
                kwargs_s = {'timeout': 10}

            if (c < nr_pub):
                p_clients.append(client)
            else:
                s_clients.append(client)
            client.connect()

        for s in s_clients:
            s.subscribe(msg_s, kwargs_s)

        for s in s_clients:
            s.start_subscribe_timeout(topic, kwargs_s)

        time.sleep(1)

        for p in p_clients:
            p.publish(topic, kwargs_p)

        ## wait until they are terminated, make sure to disconnect so that connections at the host are freed
        for p in p_clients:
            p.waitForClient()

        for s in s_clients:
            s.waitForClient()

    return np.median(timevals), np.mean(timevals), np.var(timevals), len(
        timevals)
Ejemplo n.º 3
0
def publishEncodedImage(encoded, hostname, port=1883):

    id = "id_%s" % (datetime.utcnow().strftime('%H_%M_%S'))
    # --- Create instance of mqtt client
    publisher = mqttClient(hostname, port, id)
    publisher.connect()

    try:
        # --- Divides enconded image into several packets
        end = packet_size
        start = 0
        length = len(encoded)
        picId = randomword(8)
        pos = 0
        no_of_packets = math.ceil(length / packet_size)

        # --- Loop to send each
        while start <= len(encoded):
            # --- Creates message to be published
            data = {
                "data": encoded[start:end],
                "pic_id": picId,
                "pos": pos,
                "size": no_of_packets
            }
            message = json.JSONEncoder().encode(data)

            # --- Publishes the message
            publisher.sendMessage("image", message)

            # --- Sleep and continues the loop
            time.sleep(0.05)
            end += packet_size
            start += packet_size
            pos = pos + 1
        pass
    finally:
        print("sent successfully to broker " + str(hostname))
    s_clients = []
    subs = 0
    pubs = 0
    timeout = 90

    nr_pub = 339
    nr_con = 1

    if (broker == 'mqtt' or broker == 'amqp'):
        for c in range(0, nr_pub + nr_con):
            client = None
            topic = None
            kwargs = None

            if (broker == 'mqtt'):
                client = mqttClient(c, url)
                topic = {'topic': 'x', 'psize': 1, 'qos': 0}
                kwargs_p = {'nr': 1, 'ival': 1}
                msg_s = {'topic': 'x', 'qos': 0, 'cb': on_message}
                kwargs_s = {'timeout': timeout}
            else:
                client = amqpClient(c, url)
                topic = [{'exchange': 'x', 'routing_key': '', 'psize': 1}]
                kwargs_p = {'nr': 1, 'ival': 1}
                msg_s = {'exchange': 'x', 'cb': callback, 'no_ack': True}
                kwargs_s = {'timeout': timeout}

            if (c < nr_pub):
                p_clients.append(client)
                pubs += 1
            else:
Ejemplo n.º 5
0
def main():
    generator = UsernameGenerator(OUTPUT)
    USERNAME = generator.getUsername()
    
    client = mqttClient(USERNAME)

    while True:
        client.reset()
        game = selectGame(GAMES)
        game.__init__()
        #enter match-making lobby
        client.joinLobby(client.client, game)
        while client.lobby == []:
            pass
        #choose opponent from lobby, then wait for acceptance of request
        opponent = 0
        while not opponent:
            opponents = client.findOpponents(client.lobby)
            opponent = client.selectOpponent(opponents)
            if opponent != 0:
                break
            else:
                while client.requested:
                    pass
        OUTPUT.show(f"SELECTED OPPONENT {opponent}")
        OUTPUT.show("Sending match request...")
        client.client.publish(f"ledGames/{client.opponent}/requests", f"{client.username}, 1")
        
        while not client.start:
            pass

        #loop responsible for gameplay
        while not game.done:
            #sequence for very first turn of game, only runs once
            if client.initiator == 1:
                game.busy = 1
                game.color = 1
                game.main()
                print("sending your turn")
                client.client.publish(f"ledGames/{client.opponent}/play", f"{game.BOARD}")
                client.initiator = 0
            
            #where a player waits to recieve a turn from the opponent
            while game.busy == 0:
                if len(client.boardStr) > 0:
                    game.busy = 1
                    print(client.boardStr)
                    game.beginTurn(client.boardStr) #update the game board
                    client.boardStr = ""
                else:
                    pass
            
            #players turn begins, and is sent
            game.main()
            print("sending your turn")
            print(client.opponent)
            client.client.publish(f"ledGames/{client.opponent}/play", f"{game.BOARD}")
        
        # ending sequence
        time.sleep(1)
        print("Your game with " + client.opponent + "has ended.")
        client.opponent = ""
        client.start = 0
        client.lobby = []
        prompt = "Would you like to play again? y/n"
        options = ["y", "n"]
        menu = inputs.Menu(OUTPUT, prompt, options)
        selection = menu.select()
        del menu
        if selection == 'y':
            print("returning to lobby")
        else:
            info = client.client.publish("ledGames/users/status", f'{client.username}, 0')
            info.wait_for_publish()
            #time.sleep(2)
            break
Ejemplo n.º 6
0
def pub_sub_run(broker, url, nr_pub, nr_con, interval=1):
    global timevals
    timevals = []
    if (broker == 'mqtt' or broker == 'amqp'):
        p_clients = []
        s_clients = []
        pubs = 0
        subs = 0
        timeout = 170

        for c in range(0, nr_pub + nr_con):
            client = None
            topic = None
            kwargs = None

            if (broker == 'mqtt'):
                client = mqttClient(c, url)
                topic = {'topic': 'my/topic', 'psize': 1, 'qos': 0}
                kwargs_p = {'nr': 1, 'ival': interval}
                msg_s = {
                    'topic': 'my/topic',
                    'qos': 0,
                    'cb': callback_pub_sub_test_mqtt
                }
                kwargs_s = {'timeout': timeout}
            else:
                client = amqpClient(c, 'amqp://{0}'.format(url))
                topic = [{'exchange': 'x', 'routing_key': '', 'psize': 1}]
                kwargs_p = {'nr': 1, 'ival': interval}
                msg_s = {
                    'exchange': 'x',
                    'cb': callback_pub_sub_test,
                    'no_ack': True,
                    'auto_delete': True
                }
                kwargs_s = {'timeout': timeout}
            if (c < nr_pub):
                p_clients.append(client)
                pubs += 1
            else:
                s_clients.append(client)
                subs += 1
            client.connect()

        print('Publishers: {0} Subscribers: {1}'.format(pubs, subs))

        for s in s_clients:
            s.subscribe(msg_s, kwargs_s)

        time.sleep(5)

        for s in s_clients:
            s.start_subscribe_timeout(topic, kwargs_s)

        for p in p_clients:
            p.publish(topic, kwargs_p)

        ## wait until they are terminated, make sure to disconnect so that connections at the host are freed
        for p in p_clients:
            p.waitForClient()

        for s in s_clients:
            s.waitForClient()

        print('Total msgs received: {}'.format(len(timevals)))
    return np.median(timevals), nr_pub - nr_con
Ejemplo n.º 7
0
def msg_interval_test(broker,
                      url,
                      fileName,
                      iterations=1,
                      stepsize=1,
                      interval=0.01):
    y_packetloss = []
    x_msg_s = []

    y_times = []
    for i in range(stepsize, iterations + 1, stepsize):
        global recv_msgs, timevals
        recv_msgs = 0
        timevals = []
        p_clients = []
        s_client = None
        msgs_pr_publisher = 600
        timeout = 170

        if (broker == 'mqtt' or broker == 'amqp'):
            client = None
            topic = None
            kwargs = None

            subs = 0
            pubs = 0
            for j in range(i + 1):
                if (broker == 'mqtt'):
                    client = mqttClient(j, url)
                    topic = {'topic': 'x', 'psize': 1, 'qos': 0}
                    kwargs_p = {'nr': msgs_pr_publisher, 'ival': interval}
                    msg_s = {
                        'topic': 'x',
                        'qos': 0,
                        'cb': callback_msg_interval_mqtt
                    }
                    kwargs_s = {'timeout': timeout}
                else:
                    client = amqpClient(j, 'amqp://{0}'.format(url))
                    topic = [{'exchange': 'x', 'routing_key': '', 'psize': 1}]
                    kwargs_p = {'nr': msgs_pr_publisher, 'ival': interval}
                    msg_s = {
                        'exchange': 'x',
                        'cb': callback_msg_interval,
                        'no_ack': True,
                        'auto_delete': True
                    }
                    kwargs_s = {'timeout': timeout}

                if (j < i):
                    p_clients.append(client)
                    pubs += 1
                else:
                    s_client = client
                    subs += 1

                client.connect()

            print('Publishers: {0} Subscribers: {1}'.format(pubs, subs))
            if (not s_client.isConnected()):
                s_client.connect()

            s_client.subscribe(msg_s, kwargs_s)
            s_client.start_subscribe_timeout(topic, kwargs_s)

            time.sleep(1)

            for p in p_clients:
                p.publish(topic, kwargs_p)

            ## wait until they are terminated, make sure to disconnect so that connections at the host are freed
            s_client.waitForClient()

            for p in p_clients:
                p.waitForClient()

            sent_msgs = i / interval

            x_msg_s.append(i * interval)

            if (sent_msgs > 0):
                y_packetloss.append(recv_msgs / sent_msgs)
            else:
                y_packetloss.append(0)

            y_times.append(np.median(timevals))
        print('Total msgs received: {}'.format(len(timevals)))

    write_to_csv(x_msg_s, y_packetloss,
                 '../csv/finalresults/{0}'.format(fileName[0]),
                 'Packet loss test')
    write_to_csv(x_msg_s, y_times,
                 '../csv/finalresults/{0}'.format(fileName[1]),
                 'Median receive time single consumer')
Ejemplo n.º 8
0
                                             min_speed=0,
                                             max_speed=200,
                                             wheelDiameter=WHEEL_DIAMETER,
                                             axeDiameter=AXE_DIAMETER),
    driver_component=basicDriver(
        steering_component=basicPIDComponent(kp=0.31, ki=0.25, kd=0.00225),
        speed_component=basicOnePointComponent(acceleration=2.1,
                                               max_speed=150),
        color_sensor_component=colorSensor(sensor_input=INPUT_1),
        distance_sensor_component=distanceSensor(sensor_input=INPUT_2),
        desired_obstacle_distance=30,
        desired_speed=100),
    id=ID)

mqttClient_1 = mqttClient(id=ID,
                          ip=IP,
                          topic_sub="TR54/g3/listFIFO",
                          robot=robot)
#subscriber = subscriber(ip=IP,id=ID,topic=b"TR54/g3/listFIFO",robot=robot)

start_time = time.time()
last_time = start_time
last_delta_time = MIN_DELTA_TIME
count = 0

#publisher_speed.start()
#publisher_position.start()
#publisher_action.start()
#publisher_fifo.start()
mqttClient_1.start()
#subscriber.start()
Ejemplo n.º 9
0
url_local = 'mqtt://localhost:1883'
x = []
y = []


def on_message(client, userdata, msg):
    timestamp = time.time()
    print("Topic: " + msg.topic + " DeviceId: " +
          str(getDeviceId(msg.payload)) + " MsgId: " +
          str(getMsgId(msg.payload)) + " Time: " +
          str(gettimediff(msg.payload, timestamp)))
    x + [gettimediff(msg.payload, timestamp)]
    y + [getMsgId(msg.payload)]


local_client_1 = mqttClient('1', url)
local_client_2 = mqttClient('2', url)

local_client_1.connect()
local_client_2.connect()

local_client_1.subscribe(topic={
    'topic': topic,
    'qos': 0,
    'cb': on_message
},
                         kwargs={'timeout': 15})

local_client_2.publish(topic={
    'topic': topic,
    'psize': 1000000,
Ejemplo n.º 10
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Initalize python script to start the main programm
You have to configure the settings.json before and execute the beforeStart.sh -Shell Script
(sudo ./beforeStart.sh)
"""
import RPi.GPIO as GPIO
import json
from mqttClient import mqttClient
import paho.mqtt.client as mqtt

GPIO.setmode(GPIO.BOARD)

with open('settings.json') as data_file:
    settingsdata = json.load(data_file)

brokerAddress = str(settingsdata["ip"])
brokerPort = str(settingsdata["port"])
systemID = settingsdata["systemid"]

client = mqttClient()
clientInstance = client.initalize(systemID)
client.connect(clientInstance, brokerAddress, brokerPort)
client.subscribe(clientInstance)

client.react(clientInstance)