As Im going to using flask.socketio to build a project , I found something wrong, the code are as follows
@socketio.on('message')
def handle_message(message):
if 'self' in message:
flag = 1
@copy_current_request_context
def movingcamera():
global flag, status
print('Start moving')
while flag:
GPIO.output(3, move[status][0])
GPIO.output(2, move[status][1])
if status == 2:
break
socketio.start_background_task(target=movingcamera)
@socketio.on('moving')
def handle_moving(message):
global status
if 'up' in message:
print('Got up message')
status = 1
time.sleep(2)
status = 0
elif 'down' in message:
print('Got down message')
status = -1
time.sleep(2)
status = 0
elif 'mid' in message:
status = 2
the code above is about control a mechine and got control message through sockerio.As I send 'self' to backend, it start work, howerver ,after that ,whatever I sent wasn't process anymore. my operates are as follows: enter image description here First I send 'moving' 'up' , the backend got the message and print 'Got up message'.Second I Send 'message' 'move' to start the mechine , the backend got the message and print 'recieved message:self', After that , whether how I send 'moving' or 'message' , it con't successfully process it and give me a reply .
I wonder if there are something wrong of my code or my operate. Or it's because of the 'socketio.start_background_test function'?
CodePudding user response:
The reason why start_background_task stunk is 'while 1', maybe because of the time piece was fully spend in this while loop. So ,just adding a "socketio.sleep(0.5)" in the while loop can solve this problem easily.Just like the code as follows:
@socketio.on('message')
def handle_message(message):
if 'self' in message:
flag = 1
@copy_current_request_context
def movingcamera():
global flag, status
print('Start moving')
while flag:
GPIO.output(3, move[status][0])
GPIO.output(2, move[status][1])
socketio.sleep(0.5)
if status == 2:
break
socketio.start_background_task(target=movingcamera)
@socketio.on('moving')
def handle_moving(message):
global status
if 'up' in message:
print('Got up message')
status = 1
socketio.sleep(2)
status = 0
elif 'down' in message:
print('Got down message')
status = -1
socketio.sleep(2)
status = 0
elif 'mid' in message:
status = 2
