I want to send some data to a sensor and if the python script doesn't receive the data I want the receive function to timeout and resend the data.
def subscribe():
UDP_IP = "192.168.1.166"
UDP_PORT = 10000
MESSAGE = '6864001e636caccf2393730420202020202004739323cfac202020202020'.decode('hex')
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
recieve_data = recieve()
if recieve_data == subscribe_recieve_on or recieve_data == subscribe_recieve_off:
logging.info('Subscribition to light successful')
else:
logging.info('Subscribition to light unsuccessful')
def recieve():
UDP_IP = "192.168.1.118"
UDP_PORT = 10000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
return data.encode('hex')
subscribe()
At the moment it gets stuck in the receive function if it doesn't receive any data:
data, addr = sock.recvfrom(1024)
However I want it to timeout after e.g. 2 seconds and rerun the subscribe() function.
I've tried using a while true statement with a timeout and try/exception however I get a port currently in use even when closing the port. Also feel this way is messy.
Any ideas would be appreciated.