def _send_socket(self, cmd, rtnCmd, ip, port):
socket = self._socket
try:
_LOGGER.debug('Sending to GW {0}'.format(cmd))
self._read_unwanted_data()
socket.settimeout(30.0)
socket.sendto(cmd.encode(), (ip, port))
socket.settimeout(30.0)
data, addr = socket.recvfrom(1024)
if len(data) is not None:
resp = json.loads(data.decode())
_LOGGER.debug('Recieved from GW {0}'.format(resp))
if resp["cmd"] == rtnCmd:
return resp
else:
_LOGGER.error("Response from {0} does not match return cmd".format(ip))
_LOGGER.error(data)
else:
_LOGGER.error("No response from Gateway")
except socket.timeout:
_LOGGER.error("Cannot connect to Gateway")
socket.close()
python类recvfrom()的实例源码
def _listen_to_msg(self):
while self._listening:
if self._mcastsocket is not None:
data, addr = self._mcastsocket.recvfrom(self.SOCKET_BUFSIZE)
try:
data = json.loads(data.decode("ascii"))
cmd = data['cmd']
_LOGGER.debug(format(data))
if cmd == 'heartbeat' and data['model'] == 'gateway':
self.GATEWAY_TOKEN = data['token']
elif cmd == 'report' or cmd == 'heartbeat':
self._queue.put(data)
else:
_LOGGER.error('Unknown multicast data : {0}'.format(data))
except Exception as e:
raise
_LOGGER.error('Cannot process multicast message : {0}'.format(data))
def _thread_data_collection(self,
socket,
messages_to_send,
alarm):
messages = []
for i in range(len(messages_to_send)):
socket.sendto(messages_to_send[i],
(self.transductor.ip_address, self.port))
message_received = socket.recvfrom(256)
messages.append(message_received[0])
# alarm.observe('new data received', alarm.verify_voltage)
# Event('new data received', value)
collection_time = timezone.now()
self._create_measurements_from_data_collected(messages,
collection_time)
def tos_recvfrom(self, bufsize=512):
"""Mimic the behavior of socket.recvfrom() with special behavior.
Args:
bufsize: (int) number of bytes to read from socket
It's not advisable to change this.
Returns:
(UdpData) namedtuple containing timestamps
"""
try:
data, addr = self.recvfrom(bufsize)
rcvd = time.time() * 1000
results = UdpData._make(struct.unpack(self.FORMAT, data))
rtt = rcvd - results.sent
return results._replace(rcvd=rcvd, rtt=rtt, lost=False)
except socket.timeout:
logging.debug('Timed out after {}s waiting to receive'.format(
self.gettimeout()))
return UdpData(self.SIGNATURE, self._tos, 0, 0, 0, True)
def udp_reader(socket, iqueue, size):
"""Read one or more packets from an UDP socket."""
data, peer = socket.recvfrom(size)
iqueue.put_nowait((peer, data))
def addresss2nicestring(address):
#address is a (str,port) tuple from socket.recvfrom() or socket.getpeername()
#output is something nice such as "192.0.2.7" or "2001:0db8:1::7"
if address!=None:
return address[0]
else:
return None
def receive_ping(my_socket, ID, timeout):
"""
receive the ping from the socket
"""
start_time = timeout
while True:
start_select = time.clock()
# select.select(rlist, wlist, xlist[, timeout])
# wait until ready for read / write / exceptional condition
# The return value is a triple of lists
what_ready = select.select([my_socket], [], [], start_time)
how_long = (time.clock() - start_select)
if what_ready[0] == []: #timeout
return
time_received = time.clock()
# socket.recvfrom(bufsize[, flags])
# The return value is a pair (string, address)
rec_packet, addr = my_socket.recvfrom(1024)
icmp_header = rec_packet[20 : 28]
ip_type, code, checksum, packet_ID, sequence = struct.unpack("bbHHh", icmp_header)
if ip_type != 8 and packet_ID == ID: # ip_type should be 0
byte_in_double = struct.calcsize("d")
time_sent = struct.unpack("d", rec_packet[28 : 28 + byte_in_double])[0]
return time_received - time_sent
start_time = start_time - how_long
if start_time <= 0:
return
def tos_reflect(self, bufsize=512):
"""Intended to be the sole operation on a LLAMA reflector.
Args:
bufsize: (int) number of bytes to read from socket
It's not advisable to change this.
"""
data, addr = self.recvfrom(bufsize)
try:
udpdata = UdpData._make(struct.unpack(self.FORMAT, data))
except struct.error:
logging.warn('Received malformed datagram of %s bytes. '
'Discarding.', len(data))
# Don't reflect invalid data
return
self.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, udpdata.tos)
self.sendto(data, addr)
self.processed += 1
if self.processed % 512 == 0:
logging.info('Processed packets: %s', self.processed)