I have created 2 ports as input, to capture data from a keyboard and a midi surface controller (which has a bunch of sliders and knobs). Although I am not sure how to get data from both
for msg1 in input_hw:
if not msg1.type == "clock":
print(msg1)
# Play the note if the note has been triggered
if msg1.type == 'note_on' or msg1.type == 'note_off' and msg1.velocity > 0:
out.send(msg1)
for msg in input_hw2:
#avoid to print the clock message
if not msg.type == "clock":
print(msg)
The first For loop works, I get the midi note on and off when playing the keyboard, which is tied to the input_hw port, but the second loop never goes through.
Found a solution; you need to wrap the for loops in a while loop, adn use the iter_pending() function, which does allow mido to continue and not getting stuck waiting on the first loop.
Probably there is a more elegant solution, but this is what I was able to find
while True:
for msg1 in input_hw.iter_pending():
if not msg1.type == "clock":
print(msg1)
# Play the note if the note has been triggered
if msg1.type == 'note_on' or msg1.type == 'note_off' and msg1.velocity > 0:
out.send(msg1)
for msg in input_hw2.iter_pending():
#avoid to print the clock message
if not msg.type == "clock":
print(msg)
Related
So my problem is this: I'm running a while loop that will execute Function1 every time, Function2 and Function3 will only be executed when their respective flags are set to True, and I want to be able to alter those flags while the loop is running.
while brkFlag == False:
Function1.run()
if flag2 == True:
Function2.run()
else:
pass
if flag3 == True:
Function3.run()
else:
pass
if someConditions == True:
brkFlag = True
Currently I want to change those flags with a GUI while the loop is running and am trying to do this with tkinter's Buttons and Checkboxes, but no luck so far.
I also can't use multithreading or multiprocessing as they will considerably slow down the speed of the loop (which is already barely acceptable as it is right now, because there are lots of calculations in each function and I need to show the results in a real-time fashion).
Edit: So it seems that there is no way other than doing multithreading/processing after all.
A simple way is to pass a mutable container containing the flags, for example a list:
flags = [flag2, flag3, someConditions ]
while brkFlag == False:
Function1.run(flags)
if flags[0] == True:
Function2.run(flags)
else:
pass
if flags[1] == True:
Function3.run(flags)
else:
pass
if someConditions == True: # or if flags[2] == True:
brkFlag = True
In the callee you implement more or less:
...
def run(flags):
...
flags[0] = True # set flag2
...
I'm looking to move a motorised slider using a Raspberry Pi. However, while debugging the system I was wondering if it is possible to use:
target = int(raw_input(<message>))
In a way that message could dynamically change before the user inputs a value. For me, it would be great to see the current value that is read from the slider in this <message> for example.
And if that isn't possible, is it possible to have a line printed above or below the raw_input that remains changing while the system waits for the users' input?
You can find that as a non-blocking input.
Here is a solution from stack overflow, which uses threads
I did a little modified solution, it still needs some tweaking, but its more or less what you have to do.
python
import threading
import time
import random
userInput = ""
finished = False
sensorValue = 100
previousValue = 0
def Listener():
global userInput, finished, sensorValue
userInput = raw_input(sensorValue)
if len(userInput) > 0:
print(len(userInput))
finished = True
else:
finished = False
while True:
if sensorValue != previousValue:
print("Received new slider info. SliderValue is {}".format(sensorValue))
previousValue = sensorValue
else:
print("No new info from slider. Sleeping two seconds.")
if not finished:
listener = threading.Thread(target=Listener)
listener.start()
else:
break
if random.randint(0,1) == 1:
sensorValue += 10
time.sleep(2)
See if that answers your question! :)
I'm just start learning about python and I have problem with my project to blink LED. when I get new message and start new thread. The old thread is still running.
I want to kill old thread and start new thread. How to solve my problem?
(Sorry if I'm not good in english but I'm trying)
def led_action(topic,message):
print topic+" "+message
if message == 'OFF':
#state = False
print ("Stoping...")
while message == 'OFF':
GPIO.output(8,GPIO.LOW)
elif message == 'ON':
#state = True
print ("Opening...")
while message == 'ON':
GPIO.output(8,GPIO.HIGH) #Set LED pin 8 to HIGH
time.sleep(1) #Delay 1 second
GPIO.output(8,GPIO.LOW) #Set LED pin 8 to LOW
time.sleep(1)
# Get message form NETPIE and Do something
def subscription(topic,message):
set = thread.start_new_thread(led_action, (topic,message))
def connection():
print "Now I am connected with netpie"
def disconnect():
print "disconnect is work"
microgear.setalias("test")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(True)
To terminate a python thread you need to exit your function. You can do this by removing your while message == 'ON'/'OFF' checks. As message doesn't change anyways (it is passed to the function led_action) those checks are unnecessary.
I am running a GUI with a graph that updates rather fast and i had it working great. Recently I've added in another component to my experiment that requires Serial communication via RS-232. When i use the root.after() method to call my function that reads the data from the Serial device the main loop stalls. So I thought i would try to move it to a different thread to try and avoid that but it doesn't seem like that helped. Then according to the comments i split it up into several different callbacks to avoid a costly while loop. The performance is now better but it still stalls. How do i get this to work without stalling the root.mainloop()?
Here is the new code: EDITED:
def callback_PCreadWrapper():
print 'Starting thread'
thread.start_new_thread(callback_PCread1,())
def callback_PCread1():
global ser, um1, trash, status,delay
ser.write('e')
while ser.inWaiting() > 0:
trash += ser.read(1)
ser.write('A')
root.after(500,callback_PCread2)
def callback_PCread2()
trash=''
trash = ser.read(2)
current_status = ser.read(1)
if current_status == " ":
status = 'No alarms'
elif current_status == "!":
status = 'Sensor Fail'
elif current_status == "$":
status = "Count Alarm"
else:
status = current_status
trash += ser.read(24)
um1 = ser.read(6)
while ser.inWaiting() > 0:
trash += ser.read(1)
print 'Ending Thread'
root.after(10000,callback_PCreadWrapper)
Canvas.bind_all("<End>",callback_end)
root.after(samplePeriod, writeData) # status and 1um are written to a file
root.after(10000, callback_PCreadWrapper)
root.mainloop()
if you want to look at all the code here is the LONG version on github
I have created a packet sniffer in python using scapy but kind of stuck in the multithreaded stuff..
def sniffer(ip):
filter_str = "icmp and host " + ip
packets=sniff(filter=filter_str,count=20)
status= False
for p in packets:
packet_load=str(p['Raw'].load)
if packet_load.find("##")!= -1:
status=True
log_thread = Thread(target=logger,args=(packets,))
log_thread.start()
log_thread.join()
break
if status==True:
print "Suspicious Packets sniffed!!"
user_ip = raw_input("Do you want to continue sniffing???(y/n)")
while 1:
if user_ip=="y" or user_ip=="Y":
new_thread = Thread(target=sniffer, args=(ip,))
new_thread.start()
new_thread.join()
else:
#need somthing to quit the program
return
Here, my sniffer sniffs 20 packets at a time and waits for user input for further sniffing.
However if the user enters 'n' as input, then the program hangs. Ideally I would want the program to quit if the user enters 'n'. Can I know what I'm doing wrong here??
while 1 is rarely a good choice when writing a finite loop. Try using flags instead:
leaving = False
while not leaving:
user_ip = raw_input("Do you want to continue sniffing???(y/n)")
if user_ip.lower() == 'y':
new_thread = Thread(target=sniffer, args=(ip,))
new_thread.start()
new_thread.join()
elif user_ip.lower() == 'n':
print "Leaving sniffer"
leaving = True
return