Hello. I need help with socket data send-receive in Python, on Raspberry Pi
I have 2 Raspberry Pi. No 2 is sending data to No 1. I speak into No 1 microphone, and No 1 will send data to No 2 when it detect my voice. No 2 will play a response sound using a .wav file.
There is absolutely no problem with No 1 - No 2 data transmission.
But I noticed that the loop will stuck at this line, until data is received from No 1.
dataByte, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
Then the loop will continue, until it's stuck there again when there is no data received.
How can I make the loop progress, regardless of whether data is received or not?
How can I un-stuck the program loop from that socket waiting for data?
Thanks in advance. Any idea is appreciated.
This is the full code on the receiving Pi:
# receive.py
import time
import socket
import pprint
import pygame
soundstarttime = time.time()
soundendtime = time.time()
soundplaytime = time.time()
soundplaying = 0
#Initialise pygame and the mixer
pygame.init()
pygame.mixer.init()
#load the sound file
voicepath = pygame.mixer.Sound("/home/pi/Desktop/voice/yaaa.wav")
voicepath.play()
mainloop = 1
#---------------------------------------------------------------------------
UDP_IP = "192.168.1.5"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while mainLoop == 1:
#while True:
dataByte, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
dataString = dataByte.decode("utf-8")
print("received message: ", dataString)
#------------------------------------------------------------------------
# PROBLEM!!!! loop stuck at sock.recvfrom(1024) if no data received by LAN
if dataString == "cibo":
voicepath = pygame.mixer.Sound("/home/pi/Desktop/voice/yaaa.wav")
voicepath.play()
#####################################################################
Have a test/if check, if there is any data in sockets buffer.
Err what command should I use to check for data in the socket buffer?
Update
I took out the SD card for backup, and after that it plays just fine np matter how many time I called aplay
I can't really help with python but "waiting/blocking until data is received" is usually intended behaviour. But usually there is a way to set the socket to be non-blocking.
https://docs.python.org/2/howto/sockets.html
Scroll down to the Non-blocking Sockets part. socket.setblocking(0) should be what you are looking for.
Yep non blocking socket works. Can't find any downside from setting it to be non-blocking. Why would they made sockets to be blocking anyway is the first place?
Thank you guys.
Sockets can run on separate threats, which can block anyway.
Sorry, you need to Log In to post a reply to this thread.