Why my app crash without error using PyQT5 - python

I program an app witgh QT interface to read modbus data, I display data on GUI create with PyQT5.
When I launch program, it crash after few second, I haven't message error. I used debugger and nothing wrong thing, program just close.
This is a part of my code where is my problem, I'll explain after
def displayModbus(self):
modbusReturn = modbus.readModbus()
commStatus = modbusReturn[0]
if commStatus:
listRegValue = modbusReturn[1]
#Display data to ui
if str(listRegValue[1]) == "1": #HEATING_ST
self.ui.lnHeatingStatus.setText("On")
else:
self.ui.lnHeatingStatus.setText("Off")
# self.ui..setText(str(listRegValue[2])) #WAIT_TIME_CHG
# self.ui..setText(str(listRegValue[3])) #RUN_TIME_CHG
if str(listRegValue[4]) == "1": #ON_WAIT_TIME_P
self.ui.ledWaitTime.setStyleSheet("QPushButton {background-color:green;}")
else:
self.ui.ledWaitTime.setStyleSheet("QPushButton {background-color:red;}")
if str(listRegValue[5]) == "1": #RUN_CYCLE
self.ui.lnRunCycle.setText("On")
else:
self.ui.lnRunCycle.setText("Off")
# self.ui..setText(str(listRegValue[6])) #LEVEL_RESET
# self.ui..setText(str(listRegValue[7])) #CYL_MAN_CYCLE
# self.ui..setText(str(listRegValue[8])) #CYL_EMPTY
# self.ui..setText(str(listRegValue[9])) #CYL_EMPTY_END
# self.ui..setText(str(listRegValue[10])) #NORASYSTEM_MANUAL
# self.ui..setText(str(listRegValue[11])) #NORASYSTEM_ON
# self.ui..setText(str(listRegValue[12])) #HEATING_ALLOW
if str(listRegValue[13]) == "1": #LOW_AIRFLOW
self.ui.lnLowAirflow.setText("Low")
else:
self.ui.lnLowAirflow.setText("Normal")
# self.ui..setText(str(listRegValue[15])) #HUM_ALLOW
TC1 = listRegValue[16] / 100
self.ui.lnTC1.setText(str(TC1)+" °C") #TC1
TC2 = listRegValue[17] / 100
self.ui.lnTC2.setText(str(TC2)+" °C") #TC2
TC3 = listRegValue[18] / 100
self.ui.lnTC3.setText(str(TC3)+" °C") #TC3
TC4 = listRegValue[19] / 100
self.ui.lnTC4.setText(str(TC4)+" °C") #TC4
self.ui.lnH1.setText(str(listRegValue[20])+" %RH") #HUM1
waitTime = str(listRegValue[22] / 3600)
self.ui.lnWaitTime.setText(str(waitTime+" hr")) #WAIT_TIME_D
runTime = str(listRegValue[23] / 60)
self.ui.lnRunTime.setText(str(runTime+" min")) #RUN_TIME_D
timeRemainM = str(int(listRegValue[24] / 60))
timeRemainS = str(int(listRegValue[24] % 60))
self.ui.lnTimeRemain.setText(str(timeRemainM + " min "+timeRemainS + " sec")) #TIME_REMAIN_D
self.ui.lnLevel.setText(str(listRegValue[25])) #LEVEL_D
self.statusBar().showMessage("Modbus communication OK")
else:
self.statusBar().showMessage("Error modbus communication")
The problem come from this function after many try and error method. If I delete it program doesn't crash BUT if I modify it by print function (example: print(str(listRegValue[4]))) all is good so my problem doesn't come from mGUI assignation odbus module.
my function displayModbus is refresh every 5 second (using QtThreading).
If I keep just one variable to display my app doesn't crash.
I have another app to read and record modbus data using same displayModbus function (without QT5 display) and I haven't problem
I have this problem on 2 computers and I try it on 5 computers (4x windows 10 and 1x Linux)
Python 3.8.6
PyQT==5.15.1
PyQt5-sip==12.8.1
Any idea?
Thanks.

Related

How to setup internet networking for controlling a robot?

I built a robot and setup local networking by having it act as an access point. I then connect to the access point from a laptop and send commands over UDP using python.
I would like to do the same thing but over the internet and Im really lost on how to get started. I've seen some IoT services but they dont seem well suited for such an application. I know some basics of networking enough to get a local network running but I have no idea how to get started on sending data over the internet.
Here is how I sent data over my local network (I would love to be able to do the same over the internet). I understand the requirements are a little different as I can't have a static IP address. If you could even point me to resources, I would appreciate it.
Note: the non-networking stuff is irrelevant to my question but I included it in the code for the sake of completion.
import pygame
import socket
import time
import math
#UDP_IP = "192.168.4.1" # if using ESP32
UDP_IP = "10.42.0.1" # if using jetson nano AP
UDP_PORT = 8080
l1=127/2
l2=127/2
r1=127/2
r2=127/2
intake = 127/2
elevator = 127/2
base_line=127/2
joy_deadzone= 0.2
'''
Joystick setup
'''
pygame.joystick.init()
pygame.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
counter = 0
for joy in joysticks:
joy_index = counter
counter+=1
joysticks[joy_index].init()
print("The number of joysticks: " + str(pygame.joystick.get_count()))
print("The name of joystick: " + joysticks[joy_index].get_name())
print("The number of axis: " + str(joysticks[joy_index].get_numaxes()))
hats = joysticks[joy_index].get_numhats()
print ("Number of hats: {}".format(hats) )
'''
end of joystick setup
'''
time.sleep(1)
keepRunning = True
def numToStringF(num):
# Make each pwm value 3 characters
num = int(num)
ans = str(num)
if len(ans) == 1:
return "00" + ans
elif len(ans) == 2:
return "0" + ans
else:
return ans
axisX = 0;
axisY = 0;
X = 25;
up_button_last = False
down_button_last = False
left_button_last = False
right_button_last = False
while keepRunning:
#for event in pygame.event.get():
#time.sleep(1)
if abs(round(joysticks[joy_index].get_axis(3), 1))>joy_deadzone:
axisY = (round(joysticks[joy_index].get_axis(3), 1)) * -base_line
else:
axisY=0
if abs(round(joysticks[joy_index].get_axis(0), 1))>joy_deadzone:
axisX = round(joysticks[joy_index].get_axis(0), 1) * base_line
else:
axisX=0
if abs(round(joysticks[joy_index].get_axis(2), 1))>joy_deadzone:
axisS = round(joysticks[joy_index].get_axis(2), 1) * -base_line
else:
axisS=0
print('Calculated:')
print("X: " + str(axisX))
print("S: " + str(axisS))
print("Y: " + str(axisY) + "\n\n")
print('-------')
print('joystick axis:')
print(round(joysticks[joy_index].get_axis(3), 1))
print(round(joysticks[joy_index].get_axis(1), 1))
print('-------')
l1 = int(base_line+axisY+axisX-axisS)
l2 = int(base_line+-axisY-axisX-axisS)
r1 = int(base_line+axisY-axisX+axisS)
r2 = int(base_line+-axisY+axisX+axisS)
if(l1>127):
l1=127
elif(l1<0):
l1=0
if(l2>127):
l2=127
elif(l2<0):
l2=0
if(r1>127):
r1=127
elif(r1<0):
r1=0
if(r2>127):
r2=127
elif(r2<0):
r2=0
intake = int(base_line+joysticks[joy_index].get_button(14)*30)
elevator = int(base_line+joysticks[joy_index].get_button(14)*30)
print('the motors in sequence (l1,l2,r1,r2) are:')
print((l1,l2,r1,r2))
pygame.time.delay(50)
pygame.event.pump()
#time.sleep(0.1)
MESSAGE = "d" + numToStringF(l1) + numToStringF(l2)+numToStringF(r1)+numToStringF(r2)+numToStringF(intake)+numToStringF(elevator)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode("utf-8"), (UDP_IP, UDP_PORT))
print('the message sent is')
print(MESSAGE)
print('-----')
I ended up using firebase which has a real-time database and seems suitable for data streaming. I still have to do some testing to make sure it's good enough for robot control.
As for interfacing firebase with python, you can use this library:
https://github.com/thisbejim/Pyrebase
This doesn't seem to be a topic with many resources on the internet. I hope more roboticists discuss it/post tutorials and resources if they do some IoT-like robotics.

How do you use pyautogui/win32gui and Pillow together?

I'm working on my first big project on Python - Inspired by the Chris Kiehl sushi go round tutorial, I'm building a bot that plays a text sim game using gui automation and basic computer vision. I want to use Pillow to take screenshots and gui apis to manipulate the operating system but I can make scripts that do either but not both. I'm not quite sure what I'm doing wrong - any help would be really appreciated - thanks.
Here's an abridged version of what I'm trying to do:
def match_loop():
global home_or_away
box = (x_pad+1,y_pad+1,x_pad+806,y_pad+629)
im2 = ImageGrab.grab(box)
time.sleep(1)
mousePos((x_pad+49, y_pad+149))
leftClick()
time.sleep(1)
if home_or_away == "home":
mousePos((x_pad+175, y_pad+543))
leftClick()
mousePos((x_pad+49, y_pad+149))
else:
mousePos((x_pad+728, y_pad+543))
leftClick()
mousePos((x_pad+49, y_pad+149))
im2.save(os.getcwd() + '\\full_snap_' + str(int(time.time()))+'.png', 'PNG')
while im2.getpixel((33,136)) != (206,203,214) : #while it's the first half
im2 = ImageGrab.grab(box)
im2.save(os.getcwd() + '\\full_snap_' + str(int(time.time()))+'.png', 'PNG')
time.sleep(1)
if im2.getpixel((33,136)) == (206,203,214): #if's the secondhalf
secondhalf()
secondhalf()
The code above runs fine but the code below runs into a syntax error after the mousePos function call, which works in the function above, no matter what I put afterwards:
def subsaudit():
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap_' + '.png', 'PNG')
if im.getpixel((124,399)) or im.getpixel((125,399)) or im.getpixel((126,399)) or im.getpixel((127,399)) or im.getpixel((128,399)) or im.getpixel((129,399)) or im.getpixel((130,399)) or im.getpixel((131,399)) or im.getpixel((132,399)) or im.getpixel((133,399)) or im.getpixel((134,399)) or im.getpixel((135,399)) or im.getpixel((136,399)) or im.getpixel((137,399)) != (0,0,66):
subscount = 1
if im.getpixel((124,419)) or im.getpixel((125,419)) or im.getpixel((126,419)) or im.getpixel((127,419)) or im.getpixel((128,419)) or im.getpixel((129,419)) or im.getpixel((130,419)) or im.getpixel((131,419)) or im.getpixel((132,419)) or im.getpixel((133,419)) or im.getpixel((134,419)) or im.getpixel((135,419)) or im.getpixel((136,419)) or im.getpixel((137,419)) != (0,0,66):
subscount = 2
if subscount >= 1 :
mousePos(((x_pad+178, y_pad+399))
time.sleep(1)
leftClick()
box = (x_pad+1,y_pad+1,x_pad+806,y_pad+629)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap_' + '.png', 'PNG')

Python loading bar with milestones

Im trying to make a underground controlling program with visualisation (for fun of course ;D). I know there are many different loading bar libraries but I couldnt find anything wiht milestones if you know what I mean. Im using Python 3 on windows. I will be thankfull for any help
A loading bar with milestones can be achived with sys:
def updt(total, progress):
barLength, status = 25, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}".format(
"#" * block + "-" * (barLength - block), round(progress * 100, 0),
status)
sys.stdout.write(text)
sys.stdout.flush()
runs = 250
for run_num in range(runs):
time.sleep(.1)
updt(runs, run_num + 1)
time.sleep(1)

Python for Robotics: How to generate an app for localization of a Pepper robot

These days I have tried to generate an application using the pythonapp template from the Github project Jumpstarter(https://github.com/aldebaran/robot-jumpstarter) to do the localization of Pepper. My basic idea is to combine the LandmarkDetector module in the generated app „Lokalisierung“(Localization of German).
You can read the whole code of "LandmarkDetector.py","main.py" and"MainLandmarkDetection.py" here:
"LandmarkDetector.py":
#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
"""Example: Demonstrates a way to localize the robot with
ALLandMarkDetection"""
import qi
import time
import sys
import argparse
import math
import almath
class LandmarkDetector(object):
"""
We first instantiate a proxy to the ALLandMarkDetection module
Note that this module should be loaded on the robot's naoqi.
The module output its results in ALMemory in a variable
called "LandmarkDetected".
We then read this ALMemory value and check whether we get
interesting things.
After that we get the related position of the landmark compared to robot.
"""
def __init__(self, app):
"""
Initialisation of qi framework and event detection.
"""
super(LandmarkDetector, self).__init__()
app.start()
session = app.session
# Get the service ALMemory.
self.memory = session.service("ALMemory")
# Connect the event callback.
# Get the services ALMotion & ALRobotPosture.
self.motion_service = session.service("ALMotion")
self.posture_service = session.service("ALRobotPosture")
self.subscriber = self.memory.subscriber("LandmarkDetected")
print "self.subscriber = self.memory.subscriber(LandmarkDetected)"
self.subscriber.signal.connect(self.on_landmark_detected)
print "self.subscriber.signal.connect(self.on_landmark_detected)"
# Get the services ALTextToSpeech, ALLandMarkDetection and ALMotion.
self.tts = session.service("ALTextToSpeech")
self.landmark_detection = session.service("ALLandMarkDetection")
# print "self.landmark_detection" is repr(self.landmark_detection)
self.motion_service = session.service("ALMotion")
self.landmark_detection.subscribe("LandmarkDetector", 500, 0.0 )
print "self.landmark_detection.subscribe(LandmarkDetector, 500, 0.0 )"
self.got_landmark = False
# Set here the size of the landmark in meters.
self.landmarkTheoreticalSize = 0.06 #in meters 0 #.05 or 0.06?
# Set here the current camera ("CameraTop" or "CameraBottom").
self.currentCamera = "CameraTop"
def on_landmark_detected(self, markData):
"""
Callback for event LandmarkDetected.
"""
while markData == [] : # empty value when the landmark disappears
self.got_landmark = False
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
if not self.got_landmark: # only speak the first time a landmark appears
self.got_landmark = True
#stop.motion_service.moveTo
print "Ich sehe eine Landmarke! "
self.tts.say("Ich sehe eine Landmarke! ")
# Retrieve landmark center position in radians.
wzCamera = markData[1][0][0][1]
wyCamera = markData[1][0][0][2]
# Retrieve landmark angular size in radians.
angularSize = markData[1][0][0][3]
# Compute distance to landmark.
distanceFromCameraToLandmark = self.landmarkTheoreticalSize / ( 2 * math.tan( angularSize / 2))
# Get current camera position in NAO space.
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
transformList = almath.vectorFloat(transform)
robotToCamera = almath.Transform(transformList)
# Compute the rotation to point towards the landmark.
cameraToLandmarkRotationTransform = almath.Transform_from3DRotation(0, wyCamera, wzCamera)
# Compute the translation to reach the landmark.
cameraToLandmarkTranslationTransform = almath.Transform(distanceFromCameraToLandmark, 0, 0)
# Combine all transformations to get the landmark position in NAO space.
robotToLandmark = robotToCamera * cameraToLandmarkRotationTransform *cameraToLandmarkTranslationTransform
# robotTurnAroundAngle = almath.rotationFromAngleDirection(0, 1, 1, 1)
# print "robotTurnAroundAngle = ", robotTurnAroundAngle
print "x " + str(robotToLandmark.r1_c4) + " (in meters)"
print "y " + str(robotToLandmark.r2_c4) + " (in meters)"
print "z " + str(robotToLandmark.r3_c4) + " (in meters)"
def run(self):
"""
Loop on, wait for events until manual interruption.
"""
# Wake up robot
self.motion_service.wakeUp()
# Send robot to Pose Init
self.posture_service.goToPosture("StandInit", 0.5)
# Example showing how to get a simplified robot position in world.
useSensorValues = False
result = self.motion_service.getRobotPosition(useSensorValues)
print "Robot Position", result
# Example showing how to use this information to know the robot's diplacement.
useSensorValues = False
# initRobotPosition = almath.Pose2D(self.motion_service.getRobotPosition(useSensorValues))
# Make the robot move
for i in range(1, 12, 1):
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
print "self.motion_service.moveTo(0, 0, (0.1)*math.pi)"
print "Starting LandmarkDetector"
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, stopping LandmarkDetector"
self.landmark_detection.unsubscribe("LandmarkDetector")
#stop
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str, default="10.0.0.10",
help="Robot IP address. On robot or Local Naoqi: use
'10.0.0.10'.")
parser.add_argument("--port", type=int, default=9559,
help="Naoqi port number")
args = parser.parse_args()
try:
# Initialize qi framework.
connection_url = "tcp://" + args.ip + ":" + str(args.port)
app = qi.Application(["LandmarkDetector", "--qi-url=" + connection_url])
except RuntimeError:
print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
"Please check your script arguments. Run with -h option for help.")
sys.exit(1)
landmark_detector = LandmarkDetector(app)
landmark_detector.run()
"main.py":
""" A sample showing how to make a Python script as an app. """
version = "0.0.8"
copyright = "Copyright 2015, Aldebaran Robotics"
author = 'YOURNAME'
email = 'YOUREMAIL#aldebaran.com'
import stk.runner
import stk.events
import stk.services
import stk.logging
class Activity(object):
"A sample standalone app, that demonstrates simple Python usage"
APP_ID = "com.aldebaran.lokalisierung"
def __init__(self, qiapp):
self.qiapp = qiapp
self.events = stk.events.EventHelper(qiapp.session)
self.s = stk.services.ServiceCache(qiapp.session)
self.logger = stk.logging.get_logger(qiapp.session, self.APP_ID)
def on_touched(self, *args):
"Callback for tablet touched."
if args:
self.events.disconnect("ALTabletService.onTouchDown")
self.logger.info("Tablet touched: " + str(args))
self.s.ALTextToSpeech.say("Yay!")
self.stop()
def on_start(self):
"Ask to be touched, waits, and exits."
# Two ways of waiting for events
# 1) block until it's called
self.s.ALTextToSpeech.say("Touch my forehead.")
self.logger.warning("Listening for touch...")
while not self.events.wait_for("FrontTactilTouched"):
pass
# 2) explicitly connect a callback
if self.s.ALTabletService:
self.events.connect("ALTabletService.onTouchDown", self.on_touched)
self.s.ALTextToSpeech.say("okay, now touch my tablet.")
# (this allows to simltaneously speak and watch an event)
else:
self.s.ALTextToSpeech.say("touch my tablet ... oh. " + \
"I don't haave one.")
self.stop()
def stop(self):
"Standard way of stopping the application."
self.qiapp.stop()
def on_stop(self):
"Cleanup"
self.logger.info("Application finished.")
self.events.clear()
if __name__ == "__main__":
stk.runner.run_activity(Activity)
"MainLandmarkDetection.py":
#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
"""A sample showing how to make a Python script as an app to localize
the robot with ALLandMarkDetection"""
version = "0.0.8"
copyright = "Copyright 2015, Aldebaran Robotics"
author = 'YOURNAME'
email = 'YOUREMAIL#aldebaran.com'
import stk.runner
import stk.events
import stk.services
import stk.logging
import time
import sys
import math
import almath
class Activity(object):
"A sample standalone app, that demonstrates simple Python usage"
APP_ID = "com.aldebaran.lokalisierung"
def __init__(self, qiapp):
self.qiapp = qiapp
self.events = stk.events.EventHelper(qiapp.session)
self.s = stk.services.ServiceCache(qiapp.session)
self.logger = stk.logging.get_logger(qiapp.session, self.APP_ID)
self.qiapp.start()
session = qiapp.session
# Get the service ALMemory.
self.memory = session.service("ALMemory")
# Connect the event callback.
# Get the services ALMotion & ALRobotPosture.
self.motion_service = session.service("ALMotion")
self.posture_service = session.service("ALRobotPosture")
self.subscriber = self.memory.subscriber("LandmarkDetected")
print "self.subscriber = self.memory.subscriber(LandmarkDetected)"
self.subscriber.signal.connect(self.on_landmark_detected)
print "self.subscriber.signal.connect(self.on_landmark_detected)"
# Get the services ALTextToSpeech, ALLandMarkDetection and ALMotion.
self.tts = session.service("ALTextToSpeech")
self.landmark_detection = session.service("ALLandMarkDetection")
# print "self.landmark_detection" is repr(self.landmark_detection)
self.motion_service = session.service("ALMotion")
self.landmark_detection.subscribe("Activity", 500, 0.0)
print "self.landmark_detection.subscribe(Activity, 500, 0.0 )"
self.got_landmark = False
# Set here the size of the landmark in meters.
self.landmarkTheoreticalSize = 0.06 # in meters 0 #.05 or 0.06?
# Set here the current camera ("CameraTop" or "CameraBottom").
self.currentCamera = "CameraTop"
def on_landmark_detected(self, markData):
"""
Callback for event LandmarkDetected.
"""
while markData == []: # empty value when the landmark disappears
self.got_landmark = False
# self.motion_service.moveTo(0, 0, 0.1 * math.pi)
if not self.got_landmark: # only speak the first time a landmark appears
self.got_landmark = True
# stop.motion_service.moveTo
print "Ich sehe eine Landmarke! "
# self.tts.say("Ich sehe eine Landmarke! ")
# Retrieve landmark center position in radians.
wzCamera = markData[1][0][0][1]
wyCamera = markData[1][0][0][2]
# Retrieve landmark angular size in radians.
angularSize = markData[1][0][0][3]
# Compute distance to landmark.
distanceFromCameraToLandmark = self.landmarkTheoreticalSize / (2 * math.tan(angularSize / 2))
# Get current camera position in NAO space.
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
transformList = almath.vectorFloat(transform)
robotToCamera = almath.Transform(transformList)
# Compute the rotation to point towards the landmark.
cameraToLandmarkRotationTransform = almath.Transform_from3DRotation(0, wyCamera, wzCamera)
# Compute the translation to reach the landmark.
cameraToLandmarkTranslationTransform = almath.Transform(distanceFromCameraToLandmark, 0, 0)
# Combine all transformations to get the landmark position in NAO space.
robotToLandmark = robotToCamera * cameraToLandmarkRotationTransform * cameraToLandmarkTranslationTransform
# robotTurnAroundAngle = almath.rotationFromAngleDirection(0, 1, 1, 1)
# print "robotTurnAroundAngle = ", robotTurnAroundAngle
print "x " + str(robotToLandmark.r1_c4) + " (in meters)"
print "y " + str(robotToLandmark.r2_c4) + " (in meters)"
print "z " + str(robotToLandmark.r3_c4) + " (in meters)"
def run(self):
"""
Loop on, wait for events until manual interruption.
"""
# Wake up robot
self.motion_service.wakeUp()
# Send robot to Pose Init
self.posture_service.goToPosture("StandInit", 0.5)
# Example showing how to get a simplified robot position in world.
useSensorValues = False
result = self.motion_service.getRobotPosition(useSensorValues)
print "Robot Position", result
# Example showing how to use this information to know the robot's diplacement.
useSensorValues = False
# initRobotPosition = almath.Pose2D(self.motion_service.getRobotPosition(useSensorValues))
# Make the robot move
for i in range(1, 20, 1):
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
print "self.motion_service.moveTo(0, 0, (0.1)*math.pi)"
print "Starting Activity"
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, stopping Activity"
self.landmark_detection.unsubscribe("Activity")
# stop
sys.exit(0)
def stop(self):
"Standard way of stopping the application."
self.qiapp.stop()
def on_stop(self):
"Cleanup"
self.logger.info("Application finished.")
self.events.clear()
if __name__ == "__main__":
stk.runner.run_activity(Activity)
landmark_detector = Activity()
landmark_detector.run()
This is how it worked in cmd.exe:
And I have a question to the parameter by ”landmark_detector = Activity()” in line 157 at almost the end of the program because of the Error in the image, which I should pass. After reading the answers to the similar question here by StackoverflowPython: TypeError: __init__() takes exactly 2 arguments (1 given), I am still confused. I think it should be a value which is given to the "qiapp", but what value?
Best regards,
Frederik
Actually, when you call
stk.runner.run_activity(Activity)
... it will instantiate that activity object for you, with the right parameters, you don't need to landmark_detector = Activity() etc. in MainLandmarkDetector.py
And if this object has a method called on_start, that method will be called once everything is ready (so you may only need to rename your run() method to on_start()
Note also that instead of calling sys.stop(), you can just call self.stop() or self.qiapp.stop() (which is a bit cleaner in terms of letting the cleanup code in on_stop to be called, if you need to unsubscribe to things etc.)
See here for some documentation on stk.runner.
Note also that instead of doing
self.motion_service = session.service("ALMotion")
(...)
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
you can directly do
transform = self.s.ALMotion.getTransform(self.currentCamera, 2, True)
... which (in my opinion) makes it easier to see what is being done exactly (and reduces the number of variables).

pyqt4 QTextEdit won't work in my code because of a loop

I have this code that creates a text edit window :
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.initUI()
print("just started the ui")
def initUI(self):
print("i am in initUi")
self.text = QtGui.QTextEdit(self)
self.setCentralWidget(self.text)
# x and y coordinates on the screen, width, height
self.setGeometry(100,100,1030,800)
self.setWindowTitle("Writer")
sleep(1)
the write_msg() function is ok and writes text to my terminal as expected. but now i would like to use this function to write inside the QTextEdit. problem is that write_msg() has a while loop inside if i have the while loop the window never pop's up, if i remove the while loop window pops up, the editor is there and i can type from my keyboard anything but my function can not work while it fundamental for it.
Here is my write_msg() function :
def write_msg():
print("i am in write_msg function")
#Each analog sensor has some characters to roll
sensor16=['1','-','\\','/','*','!']
sensor15=['4','G','H','I']
sensor14=['7','P','Q','R','S']
sensor13=['*']
sensor12=['2','A','B','C']
sensor11=['5','J','K','L']
sensor10=['8','T','U','V']
sensor09=['0',' ']
sensor08=['3','D','E','F']
sensor07=['6','M','N','O']
sensor06=['9','W','X','Y','Z']
sensor05=['#']
sensor04=['BACKSPACE']
sensor03=['DELETE ALL']
sensor02=['READ']
sensor01=['TRANSMITE']
sensor=[sensor01,sensor02,sensor03,sensor04,sensor05,sensor06,sensor07,sensor08,sensor09,sensor10,sensor11,sensor12,sensor13,sensor14,sensor15,sensor16]
#the maximum number of times each sensor can be pressed
#before it rols back to the first character.
max_press=[1,1,1,1,1,5,4,4,2,4,4,4,1,5,4,6]
num_press=0
message=[]
steps=0
i=0
x=0
key=0
key_pressed=0
#message_string="kjsdfgaqlkfvbnajkefnvbsfejfhvbjhkefrbvksjehdjefbv"
#print(message_string)
#p1 = subprocess.Popen(["minimodem" , '--tx' , '300'], stdin=subprocess.PIPE)
#p1.stdin.write(bytes(message_string, 'UTF-8'))
while state == "wrt":
print("i am looping")
binary_x="{0:04b}".format(x)
GPIO.output(15, int(binary_x[0]))
GPIO.output(13, int(binary_x[1]))
GPIO.output(11, int(binary_x[2]))
GPIO.output(7, int(binary_x[3]))
# average three readings to get a more stable one
channeldata_1 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_2 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_3 = read_mcp3002(0) # get CH0 input
channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
#
# Voltage = (CHX data * (V-ref [= 3300 mV] * 2 [= 1:2 input divider]) / 1024 [= 10bit resolution] #
voltage = int(round(((channeldata * vref * 2) / resolution),0))+ calibration
#print(voltage)
if DEBUG : print("Data (bin) {0:010b}".format(channeldata))
#key_pressed=x
if x==15 : # some problem with this sensor so i had to go and twicked the thresshold
voltage = voltage - 500
#time.sleep(0.05)
if ( voltage > 2500) : #key is released
keypressed = False
keyreleased = True
x=x+1
if ( voltage <= 2500) : #key is pressed
keypressed = True
keyreleased = False
key_pressed=x#define which key is pressed
if key_pressed==0 and key!=0:
transmite(message)
sleep(0.01)
x=x+1
if key_pressed==1:
state == "rd_msg"
x=x+1
if key_pressed==2:
sys.stdout.write('\033[2K')
sys.stdout.write('\033[1G')
message_len = len(message)
for m in range(message_len):
del message[m]
x=x+1
if key_pressed==3:
#print('\b\b')
print('\b ', end="", flush=True)
sys.stdout.write('\010')
message_len = len(message)
del message[message_len]
sleep(1)
x=x+1
if key_pressed > 3:
print("i am pressing a number")
if key == key_pressed :
while num_press <= (max_press[key_pressed]) and keyreleased==False:
# average three readings to get a more stable one
channeldata_1 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_2 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_3 = read_mcp3002(0) # get CH0 input
channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
#
# Voltage = (CHX data * (V-ref [= 3300 mV] * 2 [= 1:2 input divider]) / 1024 [= 10bit resolution]
#
voltage = int(round(((channeldata * vref * 2) / resolution),0))+ calibration
if DEBUG : print("Data (bin) {0:010b}".format(channeldata))
if x==15 : # some problem with this sensor so i had to go and twicked the thresshold
voltage = voltage - 500
time.sleep(0.05)
if ( voltage > 2500) : #key is released
keyreleased = True
keypressed = False
sys.stdout.write('\033[1C')
char=sensor[key_pressed][num_press-1]
message.append(char)
self.text.setText(char)
num_press=0
else :
keypressed = True
keyreleased= False
if num_press <= max_press[key_pressed] and keyreleased == False:
print(sensor[key_pressed][num_press], end="", flush=True)
sys.stdout.write('\010')
num_press=num_press+1
time.sleep(0.5)
if num_press == max_press[key_pressed] :
num_press=0
if x == 16 :
x=0
key = key_pressed
I have to continuously change the value of x increasing it from 0 to 16 for this function to work properly. Any one has any idea ?
ok ! i've tried to use threading so i can run my write_msg() function but couldn't get it to work either, if i comment the threading the text editor window pops up normally, like nothing happened, and if i uncomment it it pops out this error message:
pi#raspberrypi:~ $ sudo python3 ./Documents/Examples/texting_app.py
[xcb] Unknown sequence number while processing reply
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python3: ../../src/xcb_io.c:635: _XReply: Assertion `!xcb_xlib_threads_sequence_lost' failed.
this is the code in main() to start everything:
def main():
#t = threading.Thread(target=write_msg)
#t.daemon = True
#t.start()
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())

Categories

Resources