Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
Hi

Sorry if I haven't stated my requirements clearly.

I just wanted a way to import at least two python files in parallel and I 
wanted to know how this can be done or a reason why its bad as stated in 
another post.

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
Why is importing modules in parallel bad?

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
On Tuesday, 5 November 2019 19:44:46 UTC+1, Rhodri James  wrote:
> On 05/11/2019 18:33, Spencer Du wrote:
> > I want to execute at least two python files at once when imported but
> > I dont know how to do this. Currently I can only import each file one
> > after another but what i want is each file to be imported at the same
> > time.
> 
> That is a very odd requirement.  Why would you want to do this?  What 
> exactly does "at the same time" mean here?
> 
> -- 
> Rhodri James *-* Kynesim Ltd

These are modules/files which are independent of each other and have no 
dependencies with one another. Because of this I want to run modules all at 
once.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
On Tuesday, 5 November 2019 19:41:59 UTC+1, Bob Gailer  wrote:
> On Nov 5, 2019 1:35 PM, "Spencer Du"  wrote:
> >
> > Hi
> >
> > I want to execute at least two python files at once when imported but I
> dont know how to do this. Currently I can only import each file one after
> another but what i want is each file to be imported at the same time. Can
> you help me write the code for this?
> 
> Please explain what you mean by "imported at the same time". As far as I
> know that is physically impossible.

These are modules/files which are independent of each other and have no 
dependencies with one another. Because of this I want to run modules all at 
once.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
On Tuesday, 5 November 2019 21:05:02 UTC+1, Terry Reedy  wrote:
> On 11/5/2019 1:33 PM, Spencer Du wrote:
> 
> > I want to execute at least two python files at once when imported but I 
> > dont know how to do this. Currently I can only import each file one after 
> > another but what i want is each file to be imported at the same time. Can 
> > you help me write the code for this? embedded.py is the main file to 
> > execute.
> 
> [snip about 150 lines of example code]
> 
> We don't understand what you mean other than something impossible.  Your 
> example code iswa   ytoo long.  It should be the minimum 
> needed to illustrate the idea.
> 
> -- 
> Terry Jan Reedy

These are modules/files which are independent of each other and have no 
dependencies with one another. Because of this I want to run modules all at 
once.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
On Tuesday, 5 November 2019 19:37:32 UTC+1, Karsten Hilbert  wrote:
> > I want to execute at least two python files at once when imported but I 
> > dont know how to do this.
> > Currently I can only import each file one after another but what i want is 
> > each file to be imported
> > at the same time.
> 
> Can you explain why that seems necessary ?
> 
> Karsten

These are modules/files which are independent of each other and have no 
dependencies with one another. Because of this I want to run modules all at 
once.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How execute at least two python files at once when imported?

2019-11-06 Thread Spencer Du
On Wednesday, 6 November 2019 09:05:42 UTC+1, Christian Gollwitzer  wrote:
> Am 06.11.19 um 03:59 schrieb Dennis Lee Bieber:
> > On Tue, 5 Nov 2019 10:33:20 -0800 (PST), Spencer Du
> >  declaimed the following:
> > 
> >> Hi
> >>
> >> I want to execute at least two python files at once when imported but I 
> >> dont know how to do this. Currently I can only import each file one after 
> >> another but what i want is each file to be imported at the same time. Can 
> >> you help me write the code for this? embedded.py is the main file to 
> >> execute.
> > 
> > 
> > Short answer: you don't.
> > 
> > When you import a module, the code for that module is parsed and
> > anything that is module level executable statement is done (note: "def" is
> > an executable statement -- it creates a function object contained the
> > parsed body and binds it to the provided name). When the parser gets to the
> > end of the module, it returns to the parent level and the next statement is
> > executed.
> > 
> > Unless you use 1) threads; 2) subprocesses; or 3) multiprocess a Python
> > program only has one line of control, and that control is sequential.
> 
> Since some of these example programs use asyncio, there is a 4th method. 
> You convert all the programs to use asyncio, remove the event loop from 
> these programs, i.e. remove the
> 
> asyncio.get_event_loop().run_until_complete(main())
> 
> from the individual programs, and then you run a single event loop in 
> your main program. Something like
> 
>loop = asyncio.get_event_loop()
>loop.run_until_complete(asyncio.gather(laserembeded.main(),
> camerasembedded.main()))
> 
> 
>   Christian

Ok I am interested in knowing how i can do it via either 1) threads; 2) 
subprocesses; or 3) multiprocess; depending on what you think is the best 
method.

Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


How execute at least two python files at once when imported?

2019-11-05 Thread Spencer Du
Hi

I want to execute at least two python files at once when imported but I dont 
know how to do this. Currently I can only import each file one after another 
but what i want is each file to be imported at the same time. Can you help me 
write the code for this? embedded.py is the main file to execute.

embedded.py
import paho.mqtt.client as mqtt
from mqtt2 import *
import os
import time
import json
import configparser
from threading import Thread

def start():
try:
os.remove("list_of_device(s)_currently_active.txt")
os.remove("laser.ini")
print("Awaiting device(s) to be activated")
except:
print("Awaiting device(s) to be activated")
start()

devices = list(map(str,input("Device(s) to be activated: ").split(",")))

client = embedded()
client.run()

client.loop_start()
print("Connected to broker")
time.sleep(1)
print("Subscribing to topic", "microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", "microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": 
"system", "payload":{"name": devices, "cmd": "activating device(s)"}}, 
indent=2))
time.sleep(1)

def active_devices():
for item in devices:
device = (item + "Embedded")
deviceImport = __import__(device)

with open("list_of_device(s)_currently_active.txt", "a+") as myfile:
for item in devices:
myfile.write(item + "\n")
active_devices()

def readFile(fname):
print("List of device(s) currently active:")
try:
with open(fname, "r") as f:
for item in f:
print(item.rstrip("\n"))
except:
print("No device(s) added yet")
readFile("list_of_device(s)_currently_active.txt")

# print("Connected to broker")
# time.sleep(1)
# client.subscribe("microscope/light_sheet_microscope/UI/laser/#")
# if os.path.exists:
# parser = configparser.ConfigParser()
# parser.read("laser.ini")

# try:
# subscriptions = dict(parser.items("Subscriptions"))
# print("Subscribing to topics", subscriptions)
# client.subscribe(subscriptions)
# except:
# pass
# else:
# pass

client.loop_forever()

laserEmbedded.py
import random
import asyncio
from actorio import Actor, Message, DataMessage, ask, EndMainLoop, Reference
from mqtt2 import *

class Laser(Actor):
async def handle_message(self, message: Message):
print("Laser")
await asyncio.sleep(2)
print("Unitialised")
await asyncio.sleep(2)
print("Initialising")
await asyncio.sleep(2)
print("Initialised")
await asyncio.sleep(2)
print("Configuring")
await asyncio.sleep(2)
print("Configured")
await asyncio.sleep(2)
await message.sender.tell(DataMessage(data="Hello World Im a laser!" + 
"\n", sender=self))
async def main():
# Let's create an instance of a Greeter actor and start it. 
async with Laser() as laser:
# Then we'll just send it an empty message and wait for a response
reply : DataMessage = await ask(laser, Message())
print(reply.data)
asyncio.get_event_loop().run_until_complete(main())

def subscribe(): 
client = embedded()
client.run()

client.loop_start()
client.subscribe("microscope/light_sheet_microscope/UI/laser/#")
subscribe()

camerasEmbedded.py
import random
import asyncio
from actorio import Actor, Message, DataMessage, ask, EndMainLoop, Reference

class Cameras(Actor):
async def handle_message(self, message: Message):
print("Cameras")
await asyncio.sleep(2)
print("Unitialised")
await asyncio.sleep(2)
print("Initialising")
await asyncio.sleep(2)
print("Initialised")
await asyncio.sleep(2)
print("Configuring")
await asyncio.sleep(2)
print("Configured")
await asyncio.sleep(2)
await message.sender.tell(DataMessage(data="Hello World Im a camera!" + 
"\n", sender=self))
async def main():
# Let's create an instance of a Greeter actor and start it. 
async with Cameras() as cameras:
# Then we'll just send it an empty message and wait for a response
reply : DataMessage = await ask(cameras, Message())
print(reply.data)
asyncio.get_event_loop().run_until_complete(main())

filterwheelEmbedded.py
import random
import asyncio
from actorio import Actor, Message, DataMessage, ask, EndMainLoop, Reference

class FW(Actor):
async def handle_message(self, message: Message):
print("Filter wheel")
await asyncio.sleep(2)
print("Unitialised")
await asyncio.sleep(2)
print("Initialising")
await asyncio.sleep(2)
print("Initialised")
await asyncio.sleep(2)
print("Configuring")
await asyncio.sleep(2)
print("Configured")
await asyncio.sleep(2)

How can I set the value of the textedit box and slider of ui with the value from a config file when it has been created?

2019-10-01 Thread Spencer Du
Hi
How can I set the value of the textedit box and slider of ui with the value 
from a config file when it has been created meaning if a configuration file 
exists then set the UI with value from the config file otherwise load ui with 
nothing set to any value.
ui.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSlider, QLineEdit, 
QPushButton
from PyQt5.QtCore import Qt
import myconfig
config=myconfig.Config()
import os
import configparser

ui.py

class Example(QMainWindow):

def __init__(self):
super().__init__()

self.textbox = QLineEdit(self)
self.textbox.move(20, 25)
self.textbox.resize(60,30)

button = QPushButton('Button', self)
button.setToolTip('This is an example button')
button.clicked.connect(self.printValue)
button.move(100,25)

self.mySlider = QSlider(Qt.Horizontal, self)
self.mySlider.setGeometry(30, 140, 200, 30)
self.mySlider.setMinimum(0)
self.mySlider.setMaximum(100)

# self.textbox.setText(str(config.getminValue()))
# textboxValue = self.textbox.text()
# self.mySlider.setValue(int(textboxValue) + 30)
   
self.setGeometry(50,50,320,200)
self.setWindowTitle("Checkbox Example")
self.show()

#def changeValue(self, value):
#print(value)

def printValue(self):
if not os.path.exists('445nm.ini'):
textboxValue = self.textbox.text()
print(textboxValue) 
f = open('445nm.ini', 'w+')
config = configparser.RawConfigParser()
config.add_section('445nm')
config.set('445nm', 'intensity', textboxValue)
config.write(f)
if self.textbox.text() == "":
self.mySlider.setValue(0)
else:
self.mySlider.setValue(int(textboxValue))
else:
self.mySlider.setValue(config.get('445nm', 'intensity'))

# if self.textbox.text() == "":
# self.mySlider.setValue(0)
# else:
# self.mySlider.setValue(config.get('445nm', 'intensity'))

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

config.py

[445nm]
intensity = 4

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


How to publish a message of the qspinbox value when the qspinbox sets the slider with corresponding value.

2019-09-27 Thread Spencer Du



Hi 

When the values of the spinboxes is set a message should be published from the 
GUI containing the value from the spinbox which then sets the qlabel with the 
value. After this if I close and reload the gui the widgets should be set with 
the values set from the previous time. When the embedded.py file closes/stops 
running the gui is reset to its default state when no spinbox and qlabel are 
set with values. 

First execute the embedded.py file. Enter 'laser' when 'devices to be 
activated' appears. Once this executed a publish and subscribe should happen 
and a laser actor python file starts which launches the laser device on the 
embedded.py file. Once this is complete launch GUI.py in a separate command 
line and click add device for the device in the combo box. 

Here are the files needed. 

embedded.py 

import paho.mqtt.client as mqtt 
from mqtt import * 
import os 
import time 
import json 

def start(): 
try: 
os.remove("list_of_devices_currently_active.txt") 
print("Awaiting devices to be activated") 
except: 
print("Awaiting devices to be activated") 
start() 
 
devices = list(map(str,input("Devices to be activated: ").split(","))) 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", "microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": 
"system", "payload":{"name": devices, "cmd": "activating devices"}}, indent=2)) 
time.sleep(1) 

def active_devices(): 
for item in devices: 
device = (item + "Embedded") 
deviceImport = __import__(device) 

with open("list_of_devices_currently_active.txt", "a+") as myfile: 
for item in devices: 
myfile.write(item + "\n") 

active_devices() 

def readFile(fname): 
print("List of devices currently active:") 
try: 
with open(fname, "r") as f: 
for item in f: 
print(item.rstrip("\n")) 
except: 
print("No devices added yet") 
readFile("list_of_devices_currently_active.txt") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI/states") 
client.subscribe("microscope/light_sheet_microscope/UI/states") 
client.loop_forever() 

mqtt.py 

import logging 
import paho.mqtt.client as mqtt 
import json 

class device(mqtt.Client): 
def on_connect(self, mqtt, obj, flags, rc): 
pass 

def on_message(self, mqtt, userdata, message): 
m_decode = str(message.payload.decode("utf-8")) 
print("message recieved= " + m_decode) 
# print("File which you want to import(with .py extension)") 
print("message topic=", message.topic) 
print("message qos=", message.qos) 
print("message retain flag=", message.retain) 
m_in = json.loads(m_decode) 

def run(self): 
self.connect("localhost", 1883, 60) 

GUI.py 

import paho.mqtt.client as mqtt 
import os 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 
from mqtt import * 
import json 
import time 

class MainWindow(QtWidgets.QMainWindow): 
def __init__(self,parent = None): 
QMainWindow.__init__(self) 
super(MainWindow, self).__init__(parent) 
self.mdi = QMdiArea() 
self.setCentralWidget(self.mdi) 

self.setMinimumSize(QSize(800, 600)) 
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.subscribe("microscope/light_sheet_microscope/UI/devices") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.publish("microscope/light_sheet_microscope/UI/devices", 
json.dumps({"type": "system", "payload":{"cmd": "get all devices"}}, indent=2)) 
time.sleep(1) 

pybutton = QPushButton('Add device', self) 

pybutton.clicked.connect(self.importbutton) 

pybutton.move(100, 400) 
pybutton.resize(150, 32) 

self.combo = QComboBox(self) 
self.combo.move(100,350) 
self.combo.resize(100, 32) 

def readFile(fname): 
try: 
with open(fname, "r") as f: 
for item in f: 
self.combo.addItem(item) 
except: 
print("No devices active") 
readFile("list_of_devices_currently_active.txt") 

def importbutton(self): 
client = 

How to publish a message of the qspinbox value when the qspinbox sets the slider with corresponding value.

2019-09-27 Thread Spencer Du
Hi 

When the values of the spinboxes is set a message should be published from the 
GUI containing the value from the spinbox which then sets the qlabel with the 
value. After this if I close and reload the gui the widgets should be set with 
the values set from the previous time. When the embedded.py file closes/stops 
running the gui is reset to its default state when no spinbox and qlabel are 
set with values. 

First execute the embedded.py file. Enter 'laser' when 'devices to be 
activated' appears. Once this executed a publish and subscribe should happen 
and a laser actor python file starts which launches the laser device on the 
embedded.py file. Once this is complete launch GUI.py in a separate command 
line and click add device for the device in the combo box. 

Here are the files needed. 

embedded.py 

import paho.mqtt.client as mqtt 
from mqtt import * 
import os 
import time 
import json 

def start(): 
try: 
os.remove("list_of_devices_currently_active.txt") 
print("Awaiting devices to be activated") 
except: 
print("Awaiting devices to be activated") 
start() 
 
devices = list(map(str,input("Devices to be activated: ").split(","))) 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", "microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": 
"system", "payload":{"name": devices, "cmd": "activating devices"}}, indent=2)) 
time.sleep(1) 

def active_devices(): 
for item in devices: 
device = (item + "Embedded") 
deviceImport = __import__(device) 

with open("list_of_devices_currently_active.txt", "a+") as myfile: 
for item in devices: 
myfile.write(item + "\n") 

active_devices() 

def readFile(fname): 
print("List of devices currently active:") 
try: 
with open(fname, "r") as f: 
for item in f: 
print(item.rstrip("\n")) 
except: 
print("No devices added yet") 
readFile("list_of_devices_currently_active.txt") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI/states") 
client.subscribe("microscope/light_sheet_microscope/UI/states") 
client.loop_forever() 

mqtt.py 

import logging 
import paho.mqtt.client as mqtt 
import json 

class device(mqtt.Client): 
def on_connect(self, mqtt, obj, flags, rc): 
pass 

def on_message(self, mqtt, userdata, message): 
m_decode = str(message.payload.decode("utf-8")) 
print("message recieved= " + m_decode) 
# print("File which you want to import(with .py extension)") 
print("message topic=", message.topic) 
print("message qos=", message.qos) 
print("message retain flag=", message.retain) 
m_in = json.loads(m_decode) 

def run(self): 
self.connect("localhost", 1883, 60) 

GUI.py 

import paho.mqtt.client as mqtt 
import os 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 
from mqtt import * 
import json 
import time 

class MainWindow(QtWidgets.QMainWindow): 
def __init__(self,parent = None): 
QMainWindow.__init__(self) 
super(MainWindow, self).__init__(parent) 
self.mdi = QMdiArea() 
self.setCentralWidget(self.mdi) 

self.setMinimumSize(QSize(800, 600)) 
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.subscribe("microscope/light_sheet_microscope/UI/devices") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.publish("microscope/light_sheet_microscope/UI/devices", 
json.dumps({"type": "system", "payload":{"cmd": "get all devices"}}, indent=2)) 
time.sleep(1) 

pybutton = QPushButton('Add device', self) 

pybutton.clicked.connect(self.importbutton) 

pybutton.move(100, 400) 
pybutton.resize(150, 32) 

self.combo = QComboBox(self) 
self.combo.move(100,350) 
self.combo.resize(100, 32) 

def readFile(fname): 
try: 
with open(fname, "r") as f: 
for item in f: 
self.combo.addItem(item) 
except: 
print("No devices active") 
readFile("list_of_devices_currently_active.txt") 

def importbutton(self): 
client = device() 
 

How to publish a message of the qspinbox value when the qspinbox sets the slider with corresponding value.

2019-09-27 Thread Spencer Du
Hi 

When the values of the spinboxes is set a message should be published from the 
GUI containing the value from the spinbox which then sets the qlabel with the 
value. After this if I close and reload the gui the widgets should be set with 
the values set from the previous time. When the embedded.py file closes/stops 
running the gui is reset to its default state when no spinbox and qlabel are 
set with values. 

First execute the embedded.py file. Enter 'laser' when 'devices to be 
activated' appears. Once this executed a publish and subscribe should happen 
and a laser actor python file starts which launches the laser device on the 
embedded.py file. Once this is complete launch GUI.py in a separate command 
line and click add device for the device in the combo box. 

Here are the files needed. 

embedded.py 

import paho.mqtt.client as mqtt 
from mqtt import * 
import os 
import time 
import json 

def start(): 
try: 
os.remove("list_of_devices_currently_active.txt") 
print("Awaiting devices to be activated") 
except: 
print("Awaiting devices to be activated") 
start() 
 
devices = list(map(str,input("Devices to be activated: ").split(","))) 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", "microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": 
"system", "payload":{"name": devices, "cmd": "activating devices"}}, indent=2)) 
time.sleep(1) 

def active_devices(): 
for item in devices: 
device = (item + "Embedded") 
deviceImport = __import__(device) 

with open("list_of_devices_currently_active.txt", "a+") as myfile: 
for item in devices: 
myfile.write(item + "\n") 

active_devices() 

def readFile(fname): 
print("List of devices currently active:") 
try: 
with open(fname, "r") as f: 
for item in f: 
print(item.rstrip("\n")) 
except: 
print("No devices added yet") 
readFile("list_of_devices_currently_active.txt") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", "microscope/light_sheet_microscope/UI/states") 
client.subscribe("microscope/light_sheet_microscope/UI/states") 
client.loop_forever() 

mqtt.py 

import logging 
import paho.mqtt.client as mqtt 
import json 

class device(mqtt.Client): 
def on_connect(self, mqtt, obj, flags, rc): 
pass 

def on_message(self, mqtt, userdata, message): 
m_decode = str(message.payload.decode("utf-8")) 
print("message recieved= " + m_decode) 
# print("File which you want to import(with .py extension)") 
print("message topic=", message.topic) 
print("message qos=", message.qos) 
print("message retain flag=", message.retain) 
m_in = json.loads(m_decode) 

def run(self): 
self.connect("localhost", 1883, 60) 

GUI.py 

import paho.mqtt.client as mqtt 
import os 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 
from mqtt import * 
import json 
import time 

class MainWindow(QtWidgets.QMainWindow): 
def __init__(self,parent = None): 
QMainWindow.__init__(self) 
super(MainWindow, self).__init__(parent) 
self.mdi = QMdiArea() 
self.setCentralWidget(self.mdi) 

self.setMinimumSize(QSize(800, 600)) 
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com") 

client = device() 
client.run() 

client.loop_start() 
print("Connected to broker") 
time.sleep(1) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.subscribe("microscope/light_sheet_microscope/UI/devices") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/devices") 
client.publish("microscope/light_sheet_microscope/UI/devices", 
json.dumps({"type": "system", "payload":{"cmd": "get all devices"}}, indent=2)) 
time.sleep(1) 

pybutton = QPushButton('Add device', self) 

pybutton.clicked.connect(self.importbutton) 

pybutton.move(100, 400) 
pybutton.resize(150, 32) 

self.combo = QComboBox(self) 
self.combo.move(100,350) 
self.combo.resize(100, 32) 

def readFile(fname): 
try: 
with open(fname, "r") as f: 
for item in f: 
self.combo.addItem(item) 
except: 
print("No devices active") 
readFile("list_of_devices_currently_active.txt") 

def importbutton(self): 
client = device() 
 

How to publish a message of the qspinbox value when the qspinbox sets the slider with corresponding value.

2019-09-27 Thread Spencer Du
Hi

When the values of the spinboxes is set a message should be published from the 
GUI containing the value from the spinbox which then sets the qlabel with the 
value. After this if I close and reload the gui the widgets should be set with 
the values set from the previous time. When the embedded.py file closes/stops 
running the gui is reset to its default state when no spinbox and qlabel are 
set with values. 

First execute the embedded.py file. Enter 'laser' when 'devices to be 
activated' appears. Once this executed a publish and subscribe should happen 
and a laser actor python file starts which launches the laser device on the 
embedded.py file. Once this is complete launch GUI.py in a separate command 
line and click add device for the device in the combo box.

Here are the files needed.

embedded.py

import paho.mqtt.client as mqtt
from mqtt import *
import os
import time
import json

def start():
try:
os.remove("list_of_devices_currently_active.txt")
print("Awaiting devices to be activated")
except:
print("Awaiting devices to be activated")
start()

devices = list(map(str,input("Devices to be activated: ").split(",")))

client = device()
client.run()

client.loop_start()
print("Connected to broker")
time.sleep(1)
print("Subscribing to topic", "microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", "microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI", json.dumps({"type": 
"system", "payload":{"name": devices, "cmd": "activating devices"}}, indent=2))
time.sleep(1)

def active_devices():
for item in devices:
device = (item + "Embedded")
deviceImport = __import__(device)

with open("list_of_devices_currently_active.txt", "a+") as myfile:
for item in devices:
myfile.write(item + "\n")

active_devices()

def readFile(fname):
print("List of devices currently active:")
try:
with open(fname, "r") as f:
for item in f:
print(item.rstrip("\n"))
except:
print("No devices added yet")
readFile("list_of_devices_currently_active.txt")

client = device()
client.run()

client.loop_start()
print("Connected to broker")
time.sleep(1)
print("Subscribing to topic", "microscope/light_sheet_microscope/UI/states")
client.subscribe("microscope/light_sheet_microscope/UI/states")
client.loop_forever()

mqtt.py

import logging
import paho.mqtt.client as mqtt
import json

class device(mqtt.Client):
def on_connect(self, mqtt, obj, flags, rc):
pass

def on_message(self, mqtt, userdata, message):
m_decode = str(message.payload.decode("utf-8"))
print("message recieved= " + m_decode)
# print("File which you want to import(with .py extension)")
print("message topic=", message.topic)
print("message qos=", message.qos)
print("message retain flag=", message.retain)
m_in = json.loads(m_decode)

def run(self):
self.connect("localhost", 1883, 60)

GUI.py

import paho.mqtt.client as mqtt
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from mqtt import *
import json
import time

class MainWindow(QtWidgets.QMainWindow):
def __init__(self,parent = None):
QMainWindow.__init__(self)
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)

self.setMinimumSize(QSize(800, 600))
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com")

client = device()
client.run()

client.loop_start()
print("Connected to broker")
time.sleep(1)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/devices")
client.subscribe("microscope/light_sheet_microscope/UI/devices")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/devices")
client.publish("microscope/light_sheet_microscope/UI/devices", 
json.dumps({"type": "system", "payload":{"cmd": "get all devices"}}, indent=2))
time.sleep(1)

pybutton = QPushButton('Add device', self)

pybutton.clicked.connect(self.importbutton)

pybutton.move(100, 400)
pybutton.resize(150, 32)

self.combo = QComboBox(self)
self.combo.move(100,350)
self.combo.resize(100, 32)

def readFile(fname):
try:
with open(fname, "r") as f:
for item in f:
self.combo.addItem(item)
except:
print("No devices active")
readFile("list_of_devices_currently_active.txt") 

def importbutton(self):
client = device()
client.run()

client.loop_start()
print("Connected to broker")
time.sleep(1)
  

How to publish a message of the qspinbox value when the qspinbox sets the slider with corresponding value.

2019-09-26 Thread Spencer Du
Hi

How do I publish a message of the qspinbox value when the qspinbox sets the 
slider with corresponding value.

Thanks

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'laser.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from pyqtconfig import ConfigManager

class Ui_Laser(object):
def setupUi(self, Laser):
self.config = ConfigManager()
Laser.setObjectName("Laser")
Laser.resize(379, 274)
Laser.setMinimumSize(QtCore.QSize(379, 268))
self.config.set_defaults({
'number': 13,
'number2': 0,
'number3': 0,
'number4': 0,
'number5': 0,
'number6': 0,
'on': True,
})
self.centralwidget = QtWidgets.QWidget(Laser)
self.centralwidget.setObjectName("centralwidget")
self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 70, 371, 181))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.spinBox_6 = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox_6.setMaximum(100)
self.spinBox_6.setObjectName("spinBox_6")
self.gridLayout.addWidget(self.spinBox_6, 1, 5, 1, 1)
self.config.add_handler('number', self.spinBox_6)
self.verticalSlider_2 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_2.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_2.setObjectName("verticalSlider_2")
self.gridLayout.addWidget(self.verticalSlider_2, 0, 1, 1, 1)
self.verticalSlider_5 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_5.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_5.setObjectName("verticalSlider_5")
self.gridLayout.addWidget(self.verticalSlider_5, 0, 4, 1, 1)
self.spinBox = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox.setMaximum(100)
self.spinBox.setObjectName("spinBox")
self.gridLayout.addWidget(self.spinBox, 1, 0, 1, 1)
self.verticalSlider = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider.setObjectName("verticalSlider")
self.gridLayout.addWidget(self.verticalSlider, 0, 0, 1, 1)
self.spinBox_2 = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox_2.setMaximum(100)
self.spinBox_2.setObjectName("spinBox_2")
self.gridLayout.addWidget(self.spinBox_2, 1, 1, 1, 1)
self.verticalSlider_3 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_3.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_3.setObjectName("verticalSlider_3")
self.gridLayout.addWidget(self.verticalSlider_3, 0, 2, 1, 1)
self.spinBox_5 = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox_5.setMaximum(100)
self.spinBox_5.setObjectName("spinBox_5")
self.gridLayout.addWidget(self.spinBox_5, 1, 4, 1, 1)
self.verticalSlider_6 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_6.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_6.setObjectName("verticalSlider_6")
self.gridLayout.addWidget(self.verticalSlider_6, 0, 5, 1, 1)
self.spinBox_4 = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox_4.setMaximum(100)
self.spinBox_4.setObjectName("spinBox_4")
self.gridLayout.addWidget(self.spinBox_4, 1, 3, 1, 1)
self.verticalSlider_4 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_4.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_4.setObjectName("verticalSlider_4")
self.gridLayout.addWidget(self.verticalSlider_4, 0, 3, 1, 1)
self.verticalSlider_7 = QtWidgets.QSlider(self.gridLayoutWidget)
self.verticalSlider_7.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider_7.setObjectName("verticalSlider_7")
self.gridLayout.addWidget(self.verticalSlider_7, 0, 6, 1, 1)
self.spinBox_3 = QtWidgets.QSpinBox(self.gridLayoutWidget)
self.spinBox_3.setMaximum(100)
self.spinBox_3.setObjectName("spinBox_3")
self.gridLayout.addWidget(self.spinBox_3, 1, 2, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(0, 50, 41, 19))
self.pushButton.setCheckable(True)
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(50, 50, 41, 19))
self.pushButton_2.setCheckable(True)

Why is "Subscribing to topic topic/test" printed in console log before connect message?

2019-09-10 Thread Spencer Du
Hi 

I have code for publish and subscribe over mqtt. In the console log I have 
"Subscribing to topic topic/test" printed before connect message why is this? I 
want to this to be printed after the connect message. How do I fix this 
problem. Please run gui.py to test.

gui.py

import paho.mqtt.client as mqtt
from mqtt import *
import json
import time

client = mqtt.Client()
client.connect("broker.hivemq.com",1883,60)
client.on_connect = on_connect
client.on_message = on_message

client.loop_start()
print("Subscribing to topic", "topic/test")
client.subscribe("topic/test")
client.publish("topic/test", "Hello world!")
time.sleep(1)
client.loop_stop()

mqtt.py

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))

def on_message(client, userdata, msg):
if msg.payload.decode() == "Hello world!":
print("Yes!")

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")

"name" is part of {"name": "Hello world!"} which is a key value pair dictionary 
and json.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")


{"name": "Hello world!"} is a key value pair.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")
"name" is part of {"name": "Hello world!"} which is a key value pair dictionary 
json.
-- 
https://mail.python.org/mailman/listinfo/python-list


Help me fix a problem

2019-09-06 Thread Spencer Du
Hi 

I want to print yes in gui.py but it does not get printed because of the json. 
How do I fix this. Execute embedded.py and then gui.py to test.

embedded.py

import paho.mqtt.client as mqtt
from mqtt import *

client = mqtt.Client()
client.connect("broker.hivemq.com",1883,60)

client.on_connect = on_connect
client.subscribe("topic/test")
client.on_subscribe = on_subscribe
print("Subscribing to topic", "topic/test")
client.on_message = on_message

client.loop_forever()

gui.py

import paho.mqtt.client as mqtt
from mqtt import *
import json

# This is the Publisher

client = mqtt.Client()
client.connect("broker.hivemq.com",1883,60)
print("Publishing message (name: Hello world!) to topic", "topic/test")
client.publish("topic/test",json.dumps({"name": "Hello world!"}));
client.loop_forever();

mqtt.py

import logging
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
print("Connecting to broker")
# client.subscribe("topic/test")

def on_subscribe(client, userdata, mid, granted_qos):
print("I've subscribed to topic")

def on_message(client, userdata, msg):
print("message recieved= " + msg.payload.decode())
# print("File which you want to import(with .py extension)")
print("message topic=", msg.topic)
print("message qos=", msg.qos)
print("message retain flag=", msg.retain)

if msg.payload[name] == "Hello world!":
print("Yes!")

Regards 
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


How to remove a string from a txt file?

2019-09-04 Thread Spencer Du
Hi

I want to remove a string from a txt file and then print out what I have 
removed. How do I do this.

The txt file is in this format and should be kept in this format.

txt.txt:
laser,cameras,

Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Help needed to run some code!!!!

2019-09-02 Thread Spencer Du
Hi

How can I execute "from devicesEmbedded import *" after this: "print("Device 
added to list")" in GUI.py because currently if I have the import added at the 
top of GUI.py file it always executes first before the GUI.py file is executed. 
I want the devicesEmbedded.py to execute after GUI.py has executed first.

Thanks
Spencer

GUI.py 

import logging 
from datetime import timedelta 
import time 
from thespian.actors import * 
from transitions import Machine 
import paho.mqtt.client as mqtt 
import importlib 
import os 
import os.path 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 
from mqtt import * 
# from devicesEmbedded import * 
import json 

class MainWindow(QtWidgets.QMainWindow): 
def __init__(self,parent = None): 
QMainWindow.__init__(self) 
super(MainWindow, self).__init__(parent) 
self.mdi = QMdiArea() 
self.setCentralWidget(self.mdi) 

self.setMinimumSize(QSize(800, 600)) 
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com") 

pybutton = QPushButton('Add device', self) 

pybutton.clicked.connect(self.importbutton) 

pybutton.move(100, 400) 
pybutton.resize(150, 32) 

self.textbox = QLineEdit(self) 
self.textbox.move(100,350) 
self.textbox.resize(100, 32) 

self.fileName_UI = "" 

def importbutton(self): 
self.fileName_UI = self.textbox.text() 
self.loadGUI() 

def getGUIFilename(self): 
return self.fileName_UI 

def loadGUI(self): 
print("Searching file", self.fileName_UI)   
try: 
module = __import__(self.fileName_UI) 
my_class = getattr(module, "SubWindow") 

sub = QMdiSubWindow() 

sub.setWidget(my_class()) 
sub.setWindowTitle("New GUI:  " + self.fileName_UI) 
self.mdi.addSubWindow(sub) 
sub.show() 

print("creating new instance " + self.fileName_UI) 
client = device("Device") 
client.run() 

client.loop_start()  # start the loop 
# device_message = self.fileName_UI 
time.sleep(2) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices") 

client.publish("microscope/light_sheet_microscope/UI/list_of_devices", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI, "cmd": 
"adding device"}}, indent=2)) 
time.sleep(1)  # wait 
client.loop_stop()  # stop the loop 
print("Device added" + "\n") 

client.run() 
client.loop_start() 
time.sleep(2) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices") 

client.subscribe("microscope/light_sheet_microscope/UI/list_of_devices") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices") 

client.publish("microscope/light_sheet_microscope/UI/list_of_devices", 
self.fileName_UI + " added to device list") 
time.sleep(1) 
client.loop_stop() 

listofdevices = [] 
listofdevices.append(self.fileName_UI) 
with open("list_of_devices.txt", "a+") as myfile: 
for item in listofdevices: 
myfile.write(item + ",") 


print(item) 
print(listofdevices) 
print("Device added to list") 
except: 
print("creating new instance " + self.fileName_UI) 
client = device("Device") 
client.run() 

client.loop_start()  # start the loop 
device_message = self.fileName_UI 
time.sleep(2) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI}}, indent=2)) 
time.sleep(2)  # wait 
client.loop_stop()  # stop the loop 
print(device_message + ".py " + "file doesn't exist") 
print("Device not added") 
if __name__ == "__main__": 
app = QApplication(sys.argv) 
mainWin = MainWindow() 
a = mainWin.show() 
try: 
mainWin.show() 
os.remove("list_of_devices.txt") 
print("Awaiting devices to be launched") 
except: 
print("Awaiting devices to be launched") 
publishedMessage = mainWin.getGUIFilename() 

Help needed urgently for running some code!!!!

2019-09-02 Thread Spencer Du
Hi

I want to execute 

"from devicesEmbedded import *": in GUI.py after all code in GUI.py is run. 
Also how do I make the devicesEmbedded.py reload and run when a txt file is 
created in the name of "list_of_devices.txt" in the GUI.py python program.


GUI.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from mqtt import *
# from devicesEmbedded import *
import json

class MainWindow(QtWidgets.QMainWindow):
def __init__(self,parent = None):
QMainWindow.__init__(self)
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)

self.setMinimumSize(QSize(800, 600))
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com")

pybutton = QPushButton('Add device', self)

pybutton.clicked.connect(self.importbutton)

pybutton.move(100, 400)
pybutton.resize(150, 32)

self.textbox = QLineEdit(self)
self.textbox.move(100,350)
self.textbox.resize(100, 32)

self.fileName_UI = ""

def importbutton(self):
self.fileName_UI = self.textbox.text()
self.loadGUI()

def getGUIFilename(self):
return self.fileName_UI

def loadGUI(self):
print("Searching file", self.fileName_UI)   
try:
module = __import__(self.fileName_UI)
my_class = getattr(module, "SubWindow")

sub = QMdiSubWindow()

sub.setWidget(my_class())
sub.setWindowTitle("New GUI:  " + self.fileName_UI)
self.mdi.addSubWindow(sub)
sub.show()

print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
# device_message = self.fileName_UI
time.sleep(2)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices")

client.publish("microscope/light_sheet_microscope/UI/list_of_devices", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI, "cmd": 
"adding device"}}, indent=2))
time.sleep(1)  # wait
client.loop_stop()  # stop the loop
print("Device added" + "\n")

client.run()
client.loop_start()
time.sleep(2)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices")

client.subscribe("microscope/light_sheet_microscope/UI/list_of_devices")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI/list_of_devices")

client.publish("microscope/light_sheet_microscope/UI/list_of_devices", 
self.fileName_UI + " added to device list")
time.sleep(1)
client.loop_stop()

listofdevices = []
listofdevices.append(self.fileName_UI)
with open("list_of_devices.txt", "a+") as myfile:
for item in listofdevices:
myfile.write(item + ",")


print(item)
print(listofdevices)
print("Device added to list")
except:
print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
device_message = self.fileName_UI
time.sleep(2)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI}}, indent=2))
time.sleep(2)  # wait
client.loop_stop()  # stop the loop
print(device_message + ".py " + "file doesn't exist")
print("Device not added")
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWin = MainWindow()
a = mainWin.show()
try:
mainWin.show()
os.remove("list_of_devices.txt")
print("Awaiting devices to be launched")
except:
print("Awaiting devices to be launched")
publishedMessage = mainWin.getGUIFilename()
sys.exit(app.exec_())

devicesEmbedded.py:

import random
import asyncio
from actorio import Actor, Message, DataMessage, ask, EndMainLoop, Reference
from mqtt import *
# from GUI 

Re: Hi how do I import files inside a txt file?

2019-09-02 Thread Spencer Du
On Monday, 2 September 2019 15:29:07 UTC+2, Joel Goldstick  wrote:
> On Mon, Sep 2, 2019 at 9:21 AM Spencer Du  wrote:
> >
> > On Monday, 2 September 2019 15:03:52 UTC+2, Joel Goldstick  wrote:
> > > On Mon, Sep 2, 2019 at 8:46 AM Spencer Du  wrote:
> > > >
> > > > On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
> > > > > Spencer Du  writes:
> > > > >
> > > > > > How do i import files inside a txt file if they exist in the 
> > > > > > current directory?
> > > > > >
> > > > > > Here is the current code but I dont know how to do it correctly.
> > > > > >
> > > > > > import paho.mqtt.client as mqtt
> > > > > > from mqtt import *
> > > > > > import importlib
> > > > > > import os
> > > > > > import os.path
> > > > > > # from stateMachine import *
> > > > > >
> > > > > > with open("list_of_devices.txt", "r") as reader:
> > > > > > for item in reader:
> > > > > > try:
> > > > > > os.getcwd()
> > > > > > print("hi")
> > > > > > except:
> > > > > > print("error")
> > > > > >
> > > > > > This is "list_of_devices.txt":
> > > > > > test1,test2
> > > > > >
> > > > > > Each name refers to a python file.
> > > > > >
> > > > > My interpretation is that you want to read a file 
> > > > > (list_of_devices.txt)
> > > > > and this file contains names of other files and you want to read those
> > > > > files as well and do something with them (read or print or whatever).
> > > > >
> > > > > You can approach it like this: write a function to read a file and 
> > > > > work
> > > > > on it. Like this,
> > > > >
> > > > > def fn(fname):
> > > > > with open(fname, "r") as f:
> > > > >  try:
> > > > > # work with f
> > > > >  except:
> > > > > print("error")
> > > > >
> > > > > Then use this function in your code that you have writen. Like this
> > > > >
> > > > > with open("list_of_devices.txt", "r") as reader:
> > > > >  for item in reader:
> > > > >  try:
> > > > > fn(item)
> > > > >  except:
> > > > > print("error")
> > > > >
> > > > > In the example that you gave, you have written contents of
> > > > > "list_of_devices.txt" as
> > > > >
> > > > > test1,test2
> > > > >
> > > > > Take care to read them as comma separated. Or if you have control then
> > > > > write them on separate lines.
> > > > >
> > > > > Regards.
> > > > > --
> > > > > Pankaj Jangid
> > > >
> > > > Hi Pankaj
> > > >
> > > > I dont understand so what is complete code then?
> > > >
> > > > Thanks
> > > > Spencer
> > > > --
> > > > https://mail.python.org/mailman/listinfo/python-list
> > >
> > > Pardon me for guessing, but your question seems to imply that you know
> > > how you want to do something .. but I'm not sure you have tackled your
> > > problem correctly.
> > >
> > > My guess is:  Depending upon the names listed in a text file, you want
> > > to do different imports into your program.   You don't yet know how to
> > > read a file with python.
> > >
> > > First, when you run your program, python compiles it in order.  Since
> > > you don't know what you want to import until after you run your
> > > program, you can't import those modules.  You may be able to run a
> > > program to read the module list, then have it output to a new file the
> > > code you eventually want to run based on the modules you discovered.
> > > That sounds cute in a way, but probably not in a good way.  You could
> > > also surround import statements with try/e

Re: Hi how do I import files inside a txt file?

2019-09-02 Thread Spencer Du
On Monday, 2 September 2019 15:03:52 UTC+2, Joel Goldstick  wrote:
> On Mon, Sep 2, 2019 at 8:46 AM Spencer Du  wrote:
> >
> > On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
> > > Spencer Du  writes:
> > >
> > > > How do i import files inside a txt file if they exist in the current 
> > > > directory?
> > > >
> > > > Here is the current code but I dont know how to do it correctly.
> > > >
> > > > import paho.mqtt.client as mqtt
> > > > from mqtt import *
> > > > import importlib
> > > > import os
> > > > import os.path
> > > > # from stateMachine import *
> > > >
> > > > with open("list_of_devices.txt", "r") as reader:
> > > > for item in reader:
> > > > try:
> > > > os.getcwd()
> > > > print("hi")
> > > > except:
> > > > print("error")
> > > >
> > > > This is "list_of_devices.txt":
> > > > test1,test2
> > > >
> > > > Each name refers to a python file.
> > > >
> > > My interpretation is that you want to read a file (list_of_devices.txt)
> > > and this file contains names of other files and you want to read those
> > > files as well and do something with them (read or print or whatever).
> > >
> > > You can approach it like this: write a function to read a file and work
> > > on it. Like this,
> > >
> > > def fn(fname):
> > > with open(fname, "r") as f:
> > >  try:
> > > # work with f
> > >  except:
> > > print("error")
> > >
> > > Then use this function in your code that you have writen. Like this
> > >
> > > with open("list_of_devices.txt", "r") as reader:
> > >  for item in reader:
> > >  try:
> > > fn(item)
> > >  except:
> > > print("error")
> > >
> > > In the example that you gave, you have written contents of
> > > "list_of_devices.txt" as
> > >
> > > test1,test2
> > >
> > > Take care to read them as comma separated. Or if you have control then
> > > write them on separate lines.
> > >
> > > Regards.
> > > --
> > > Pankaj Jangid
> >
> > Hi Pankaj
> >
> > I dont understand so what is complete code then?
> >
> > Thanks
> > Spencer
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> 
> Pardon me for guessing, but your question seems to imply that you know
> how you want to do something .. but I'm not sure you have tackled your
> problem correctly.
> 
> My guess is:  Depending upon the names listed in a text file, you want
> to do different imports into your program.   You don't yet know how to
> read a file with python.
> 
> First, when you run your program, python compiles it in order.  Since
> you don't know what you want to import until after you run your
> program, you can't import those modules.  You may be able to run a
> program to read the module list, then have it output to a new file the
> code you eventually want to run based on the modules you discovered.
> That sounds cute in a way, but probably not in a good way.  You could
> also surround import statements with try/except code that will import
> what it can, and alert you when it can't
> 
> Can you give us the bigger picture of what you want to accomplish?
> This might lead to a better solution than the one you are thinking of
> now
> 
> -- 
> Joel Goldstick
> http://joelgoldstick.com/blog
> http://cc-baseballstats.info/stats/birthdays

Hi

I have a txt file which contains the names of files. They are .py files. I want 
to import them into a python file if they exists in current directory and if 
the name of file does not exist then print out error and not import. How do I 
do this?

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hi how do I import files inside a txt file?

2019-09-02 Thread Spencer Du
On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
> Spencer Du  writes:
> 
> > How do i import files inside a txt file if they exist in the current 
> > directory?
> >
> > Here is the current code but I dont know how to do it correctly.
> >
> > import paho.mqtt.client as mqtt
> > from mqtt import *
> > import importlib
> > import os
> > import os.path
> > # from stateMachine import *
> >
> > with open("list_of_devices.txt", "r") as reader:
> > for item in reader:
> > try:
> > os.getcwd()
> > print("hi")
> > except:
> > print("error")
> >
> > This is "list_of_devices.txt":
> > test1,test2
> >
> > Each name refers to a python file.
> >
> My interpretation is that you want to read a file (list_of_devices.txt)
> and this file contains names of other files and you want to read those
> files as well and do something with them (read or print or whatever).
> 
> You can approach it like this: write a function to read a file and work
> on it. Like this,
> 
> def fn(fname):
> with open(fname, "r") as f:
>  try:
> # work with f
>  except:
> print("error")
> 
> Then use this function in your code that you have writen. Like this
> 
> with open("list_of_devices.txt", "r") as reader:
>  for item in reader:
>  try:
> fn(item)
>  except:
> print("error")
> 
> In the example that you gave, you have written contents of
> "list_of_devices.txt" as
> 
> test1,test2
> 
> Take care to read them as comma separated. Or if you have control then
> write them on separate lines.
> 
> Regards.
> -- 
> Pankaj Jangid

Hi I dont really understand this. So what would be the complete code? Also I 
want to import files if it exists based on what is in the txt file.

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hi how do I import files inside a txt file?

2019-09-02 Thread Spencer Du
On Monday, 2 September 2019 13:36:06 UTC+2, Pankaj Jangid  wrote:
> Spencer Du  writes:
> 
> > How do i import files inside a txt file if they exist in the current 
> > directory?
> >
> > Here is the current code but I dont know how to do it correctly.
> >
> > import paho.mqtt.client as mqtt
> > from mqtt import *
> > import importlib
> > import os
> > import os.path
> > # from stateMachine import *
> >
> > with open("list_of_devices.txt", "r") as reader:
> > for item in reader:
> > try:
> > os.getcwd()
> > print("hi")
> > except:
> > print("error")
> >
> > This is "list_of_devices.txt":
> > test1,test2
> >
> > Each name refers to a python file.
> >
> My interpretation is that you want to read a file (list_of_devices.txt)
> and this file contains names of other files and you want to read those
> files as well and do something with them (read or print or whatever).
> 
> You can approach it like this: write a function to read a file and work
> on it. Like this,
> 
> def fn(fname):
> with open(fname, "r") as f:
>  try:
> # work with f
>  except:
> print("error")
> 
> Then use this function in your code that you have writen. Like this
> 
> with open("list_of_devices.txt", "r") as reader:
>  for item in reader:
>  try:
> fn(item)
>  except:
> print("error")
> 
> In the example that you gave, you have written contents of
> "list_of_devices.txt" as
> 
> test1,test2
> 
> Take care to read them as comma separated. Or if you have control then
> write them on separate lines.
> 
> Regards.
> -- 
> Pankaj Jangid

Hi Pankaj

I dont understand so what is complete code then?

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Hi how do I import files inside a txt file?

2019-09-02 Thread Spencer Du
Hi

How do i import files inside a txt file if they exist in the current directory?

Here is the current code but I dont know how to do it correctly.

import paho.mqtt.client as mqtt
from mqtt import *
import importlib
import os
import os.path
# from stateMachine import *

with open("list_of_devices.txt", "r") as reader:
for item in reader:
try:
os.getcwd()
print("hi")
except:
print("error")

This is "list_of_devices.txt":
test1,test2

Each name refers to a python file.

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


How to create a list and append to list inside a mqtt and GUI program?

2019-09-01 Thread Spencer Du
Hi 

I have code for GUI and MQTT. In GUI.py I have "def loadGUI" which loads up a 
GUI file if the file exists in current directory. I want to add the file name 
to a list when a file is imported and for each subsequent file that is imported 
I want the file name to be imported to the same list and print the list or 
create a new list but with the imported file named added to list which has the 
existing file names that have already been imported. I was wondering how I do 
this. By the way run GUI.py to test this and test1.py and test2.py are the 
files which can be used to import GUI . 

GUI.py 

import logging 
from datetime import timedelta 
import time 
from thespian.actors import * 
from transitions import Machine 
import paho.mqtt.client as mqtt 
import importlib 
import os.path 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 
from mqtt import * 
import json 

class MainWindow(QtWidgets.QMainWindow): 
def __init__(self,parent = None): 
QMainWindow.__init__(self) 
super(MainWindow, self).__init__(parent) 
self.mdi = QMdiArea() 
self.setCentralWidget(self.mdi) 

self.setMinimumSize(QSize(800, 600)) 
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com") 

pybutton = QPushButton('Add device', self) 

pybutton.clicked.connect(self.importbutton) 

pybutton.move(100, 400) 
pybutton.resize(150, 32) 

self.textbox = QLineEdit(self) 
self.textbox.move(100,350) 
self.textbox.resize(100, 32) 

self.fileName_UI = "" 

def importbutton(self): 
self.fileName_UI = self.textbox.text() 
self.loadGUI() 

def getGUIFilename(self): 
return self.fileName_UI 

def loadGUI(self): 
print("Searching file", self.fileName_UI)   
try: 
module = __import__(self.fileName_UI) 
my_class = getattr(module, "SubWindow") 

sub = QMdiSubWindow() 

sub.setWidget(my_class()) 
sub.setWindowTitle("New GUI:  " + self.fileName_UI) 
self.mdi.addSubWindow(sub) 
sub.show() 

print("creating new instance " + self.fileName_UI) 
client = device("Device") 
client.run() 

client.loop_start()  # start the loop 
device_message = self.fileName_UI 
time.sleep(2) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI, "cmd": 
"adding device"}}, indent=2)) 
time.sleep(1)  # wait 
client.loop_stop()  # stop the loop 
print("Device added" + "\n") 
listofdevice = [] 
listofdevice.append(self.fileName_UI) 
print(listofdevice) 
except: 
print("creating new instance " + self.fileName_UI) 
client = device("Device") 
client.run() 

client.loop_start()  # start the loop 
device_message = self.fileName_UI 
time.sleep(2) 
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI") 
client.subscribe("microscope/light_sheet_microscope/UI") 
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI") 
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI}}, indent=2)) 
time.sleep(2)  # wait 
client.loop_stop()  # stop the loop 
print(device_message + ".py " + "file doesn't exist") 
print("Device not added") 
if __name__ == "__main__": 
app = QApplication(sys.argv) 
mainWin = MainWindow() 
mainWin.show() 
publishedMessage = mainWin.getGUIFilename() 
sys.exit(app.exec_()) 

MQTT.py 
import logging 
from datetime import timedelta 
import time 
from thespian.actors import * 
from transitions import Machine 
import paho.mqtt.client as mqtt 
import importlib 
import os.path 
import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from PyQt5 import QtWidgets, uic 

class device(mqtt.Client): 
def on_connect(self, mqttc, obj, flags, rc): 
if rc == 0: 
print("Connected to broker") 
else: 
print("Connection failed") 

# mqttc.subscribe("microscope/light_sheet_microscope/UI") 

def on_message(self, mqttc, userdata, message): 
msg = str(message.payload.decode("utf-8")) 
print("message recieved= " + msg) 
# print("File which you want to import(with .py extension)") 
print("message topic=", 

How to create list for stuff inside mqtt and GUI?.

2019-09-01 Thread Spencer Du via Python-list
Hi 

I have code for GUI and MQTT. In GUI.py I have "def loadGUI" which loads up a 
GUI file if the file exists in current directory. I want to add the file name 
to a list when a file is imported and for each subsequent file that is imported 
I want the file name to be imported to the same list and print the list or 
create a new list but with the imported file named added to list which has the 
existing file names that have already been imported. I was wondering how I do 
this. By the way run GUI.py to test this.

GUI.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from mqtt import *
import json

class MainWindow(QtWidgets.QMainWindow):
def __init__(self,parent = None):
QMainWindow.__init__(self)
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)

self.setMinimumSize(QSize(800, 600))
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com")

pybutton = QPushButton('Add device', self)

pybutton.clicked.connect(self.importbutton)

pybutton.move(100, 400)
pybutton.resize(150, 32)

self.textbox = QLineEdit(self)
self.textbox.move(100,350)
self.textbox.resize(100, 32)

self.fileName_UI = ""

def importbutton(self):
self.fileName_UI = self.textbox.text()
self.loadGUI()

def getGUIFilename(self):
return self.fileName_UI

def loadGUI(self):
print("Searching file", self.fileName_UI)   
try:
module = __import__(self.fileName_UI)
my_class = getattr(module, "SubWindow")

sub = QMdiSubWindow()

sub.setWidget(my_class())
sub.setWindowTitle("New GUI:  " + self.fileName_UI)
self.mdi.addSubWindow(sub)
sub.show()

print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
device_message = self.fileName_UI
time.sleep(2)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI, "cmd": 
"adding device"}}, indent=2))
time.sleep(1)  # wait
client.loop_stop()  # stop the loop
print("Device added" + "\n")
listofdevice = []
listofdevice.append(self.fileName_UI)
print(listofdevice) 
except:
print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
device_message = self.fileName_UI
time.sleep(2)
print("Subscribing to topic", 
"microscope/light_sheet_microscope/UI")
client.subscribe("microscope/light_sheet_microscope/UI")
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI", 
json.dumps({"type": "device", "payload":{"name": self.fileName_UI}}, indent=2))
time.sleep(2)  # wait
client.loop_stop()  # stop the loop
print(device_message + ".py " + "file doesn't exist")
print("Device not added")
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
publishedMessage = mainWin.getGUIFilename()
sys.exit(app.exec_())

MQTT.py
import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic

class device(mqtt.Client):
def on_connect(self, mqttc, obj, flags, rc):
if rc == 0:
print("Connected to broker")
else:
print("Connection failed")

# mqttc.subscribe("microscope/light_sheet_microscope/UI")

def on_message(self, mqttc, userdata, message):
msg = str(message.payload.decode("utf-8"))
print("message recieved= " + msg)
# print("File which you want to import(with .py extension)")
print("message topic=", message.topic)
print("message qos=", message.qos)
print("message retain flag=", message.retain)

def run(self):
self.connect("broker.hivemq.com", 1883, 60)


How do I decouple these two modules?

2019-08-28 Thread Spencer Du via Python-list
Hi

I have code for a GUI and MQTT. How do I make both of these modules decoupled 
because currently they rely on each other to some extent.

GUI.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from mqtt import *

class MainWindow(QtWidgets.QMainWindow):
def __init__(self,parent = None):
QMainWindow.__init__(self)
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)

self.setMinimumSize(QSize(800, 600))
self.setWindowTitle("PyQt button example - 
pythonprogramminglanguage.com")

pybutton = QPushButton('Add device', self)

pybutton.clicked.connect(self.importbutton)

pybutton.move(100, 400)
pybutton.resize(150, 32)

self.textbox = QLineEdit(self)
self.textbox.move(100,350)
self.textbox.resize(100, 32)

self.fileName_UI = ""

def importbutton(self):
self.fileName_UI = self.textbox.text()
self.loadGUI()

def getGUIFilename(self):
return self.fileName_UI

def loadGUI(self):
print("Searching file", self.fileName_UI)

try:
module = __import__(self.fileName_UI)
my_class = getattr(module, "SubWindow")

sub = QMdiSubWindow()

sub.setWidget(my_class())
sub.setWindowTitle("New GUI:  " + self.fileName_UI)
self.mdi.addSubWindow(sub)
sub.show()

print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
device_message = self.fileName_UI
time.sleep(2)
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI", " Searching file ", device_message+".py 
...")
client.publish("microscope/light_sheet_microscope/UI", 
device_message)
time.sleep(2)  # wait
client.loop_stop()  # stop the loop
print("File imported")
except:
print("creating new instance " + self.fileName_UI)
client = device("Device")
client.run()

client.loop_start()  # start the loop
device_message = self.fileName_UI
time.sleep(2)
print("Publishing message to topic", 
"microscope/light_sheet_microscope/UI", " Searching file ", device_message+".py 
...")
client.publish("microscope/light_sheet_microscope/UI", 
device_message)
time.sleep(2)  # wait
client.loop_stop()  # stop the loop
print(device_message + ".py " + "file doesn't exist")

if __name__ == "__main__":
app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
publishedMessage = mainWin.getGUIFilename()
sys.exit(app.exec_())


MQTT.py

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
import importlib
import os.path
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic

class device(mqtt.Client):
def on_connect(self, mqttc, obj, flags, rc):
if rc == 0:
print("Connected to broker")
else:
print("Connection failed")

mqttc.subscribe("microscope/light_sheet_microscope/UI")

def on_message(self, mqttc, userdata, message):
msg = str(message.payload.decode("utf-8"))
print("File which you want to import(with .py extension)")
print("message topic=", message.topic)
print("message qos=", message.qos)
print("message retain flag=", message.retain)

def run(self):
self.connect("broker.hivemq.com", 1883, 60)

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do i execute some code when I have subscribed to a topic with a message payload for mqtt in python?

2019-08-08 Thread Spencer Du via Python-list
On Thursday, 8 August 2019 22:48:11 UTC+2, Spencer Du  wrote:
> Ok so here is some code below. How do I write an if code block to execute 
> some commands when I subscribe to the topic: 
> microscope/light_sheet_microscope/UI and which has a message which is a 
> device type published to it. I want to execute some code to check if the 
> device has a python file in the currently directory because each device also 
> relates to a python file. If the file exists then import the file into the 
> python program else print an error message. If I need to use on_subscribe 
> callback then tell and show me how the code is to be written and if another 
> method then also tell me and show me how to write the code. I really 
> appreciate all the help you can give me because this is really important for 
> me and I am currently really struggling with MQTT because I need help with 
> writing MQTT code because I am working on MQTT at work.
> 
> import logging
> from datetime import timedelta
> import time
> from thespian.actors import *
> from transitions import Machine
> import paho.mqtt.client as mqtt
> 
> class device(mqtt.Client):
> def on_connect(self, mqttc, obj, flags, rc):
>  if rc == 0:
>   print("Connected to broker") 
>  else:
>   print("Connection failed")
>  mqttc.subscribe("microscope/light_sheet_microscope/UI")
> def on_message(self, mqttc, userdata, message):
> print("message received " ,str(message.payload.decode("utf-8")))
> print("message topic=",message.topic)
> print("message qos=",message.qos)
> print("message retain flag=",message.retain)
> def on_publish(self, mqttc, obj, mid):
> print("mid: "+str(mid))
> def on_subscribe(self, mqttc, obj, mid, granted_qos):
> print("Subscribed: "+str(mid)+" "+str(granted_qos))
> def run(self):
> self.connect("broker.hivemq.com", 1883, 60)
> print("creating new instance laser")
> client = device("Device")
> client.run()
> client.loop_start() #start the loop
> device = "laser"
> time.sleep(2)
> print("Publishing message to topic","microscope/light_sheet_microscope/UI")
> client.publish("microscope/light_sheet_microscope/UI",device)
> time.sleep(2) # wait
> print("subscribing ")
> client.subscribe("microscope/light_sheet_microscope/UI")
> client.loop_stop() #stop the loop
> 
> Thanks
> Spencer

-- 
https://mail.python.org/mailman/listinfo/python-list


How do i execute some code when I have subscribed to a topic with a message payload for mqtt in python?

2019-08-08 Thread Spencer Du via Python-list
Ok so here is some code below. How do I write an if code block to execute some 
commands when I subscribe to the topic: microscope/light_sheet_microscope/UI 
and which has a message which is a device type published to it. I want to 
execute some code to check if the device has a python file in the currently 
directory because each device also relates to a python file. If the file exists 
then import the file into the python program else print an error message. If I 
need to use on_subscribe callback then tell and show me how the code is to be 
written and if another method then also tell me and show me how to write the 
code. I really appreciate all the help you can give me because this is really 
important for me and I am currently really struggling with MQTT because I need 
help with writing MQTT code because I am working on MQTT at work.

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt

class device(mqtt.Client):
def on_connect(self, mqttc, obj, flags, rc):
 if rc == 0:
  print("Connected to broker") 
 else:
  print("Connection failed")
 mqttc.subscribe("microscope/light_sheet_microscope/UI")
def on_message(self, mqttc, userdata, message):
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
def on_publish(self, mqttc, obj, mid):
print("mid: "+str(mid))
def on_subscribe(self, mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def run(self):
self.connect("broker.hivemq.com", 1883, 60)
print("creating new instance laser")
client = device("Device")
client.run()
client.loop_start() #start the loop
device = "laser"
time.sleep(2)
print("Publishing message to topic","microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI",device)
time.sleep(2) # wait
print("subscribing ")
client.subscribe("microscope/light_sheet_microscope/UI")
client.loop_stop() #stop the loop

Thanks
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list