MQTT in BGE Python?

Hello!

Is it possible to use MQTT inside the bge?
is use the ‘paho’ broker from eclipse
I am using an Raspberry PI as an mosquitto server

but did not got it working inside blender yet!
When I run my code blender freezes.

Got it working (Partly)
I can now send and receive messages
but the GE is still frozen


import paho.mqtt.client as mqtt
import bge

def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("playerdata/")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    #client.publish("playerdata/", "lolled")

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

cont = bge.logic.getCurrentController()
own = cont.owner

if not "connection" in own:
    own["connection"] = mqtt.Client()
    own["connection"].on_connect = on_connect
    own["connection"].on_message = on_message
    own["connection"].on_publish = on_publish

    own["connection"].connect("xxx.xxx.xxx.xxx", 1883, 60)

own["connection"].loop_forever()

Loop forever is blocking. You need to run it non blocking or, thread the blocking IO and pass data in safely

Sent from my SM-G920F using Tapatalk

Thanks agoose77 i got it working using threads :slight_smile:

Hi, could you show me te code working with threads? thanks!

here’s one I found

I would use the weakref module to watch for the logic module destruction when the game engine ends.

import threading
import weakref

from bge import logic

class Thread(threading.Thread):
    def __init__(self, *args, **kargs):
        super().__init__(self, *args, **kargs)
        weakref.finalize(logic, self.kill)
        self.alive = True

    def kill(self):
        self.alive = False

    def run(self):
        '''Your code here...'''
        while self.alive:
            print('AM ALIVE !')

Will this code works for blender Cycles ( non BGE ) ?

MQTT is an standalone module that could be used with Python, so theoretically it could work.