Ok that mostly makes sense. I tried a different approach this morning. Rather than having a python script start TNG I wrote it so that it can be started using a custom M code. The python script starts a thread and exits, but the thread it creates survives and does everything correctly. So what I have is an M code files and a py file.
Code:
M990.gcode
(print,Start M990)
(py,scripts/mqtt.py)
(print,End M990)
Code:
mqtt.py
import sys
import time
import ctypes
import threading
import paho.mqtt.client as mqtt
import planetcnc
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
client.connected_flag = rc
if rc==0:
client.subscribe("+/stat/POWER")
def on_message(client, userdata, message):
print(message.topic + " " + str(message.qos) + " " + str(message.payload.decode("utf-8")))
print(message.payload.decode("utf-8"))
if message.topic=="garage_compressor/stat/POWER":
if message.payload.decode("utf-8")=="ON":
v = 1
else:
v = 0
print("Setting _compressor")
planetcnc.setParam("_compressor", v)
def main():
try:
mqtt.Client.connected_flag = -1
client = mqtt.Client("cnc")
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("username", "password")
client.connect_async("x.x.x.x")
client.loop_forever()
except Exception as e:
print("Exception: ", str(e))
t = threading.Thread(target=main)
t.start()
With this as long as I remember to execute M990 once after starting TNG everything works perfectly. I may as well removed the print statements though as they don't get output anywhere visible.
I know somewhere you mentioned you where going to add more event type at a later date, could you please think about including one for "TNG Start" and maybe "TNG End". Then I could have this code run automatically at TNG startup.