- p = self._simple_serial.read(remaining)
- except ReadError:
- if self._debug:
- print "Packet read failed. Try again."
- else:
- # Was the packet filtered?
- if p is not None:
- # Not filtered, so return it.
- # In the current TinyOS the packets from the mote are
- # always NoAckDataFrame
- return NoAckDataFrame(p.data)
-
- # Read timeout expired
- raise ReadTimeoutError
-
- def write(self, payload, timeout=None):
- """Write a packet to the serial port
-
- Keeps retrying endlessly, unless a timeout is set. If the timeout
- expires then WriteTimeoutError is thrown.
-
- """
- if timeout is None:
- timeout = self.timeout
-
- endtime = None
- if timeout is not None:
- endtime = time.time() + timeout
-
- # Generate the next sequence number:
- self._seqno = (self._seqno + 1) % 100
-
- while endtime is None or time.time() < endtime:
- try:
- ackwait = ACK_WAIT
- if endtime is not None:
- remaining = endtime - time.time()
- ackwait = min(ACK_WAIT, remaining)
-
- before = time.time()
- self._simple_serial.write(payload, self._seqno, ackwait)
- length = time.time() - before
-
- if length >= ACK_WARN:
- print "Warning: Packet write took %.3fs!" % (length)
- return True
- except Error:
- if self._debug:
- print "The packet was not acked. Try again."
-
- # Write operation timed out
- raise WriteTimeoutError
-
- def _printf_filter(self, packet):
- """Filter for recieved printf packets"""
- ampkt = ActiveMessage(NoAckDataFrame(packet.data).data)
- if ampkt.type == 100:
- self._printf_msg += "".join([chr(i) for i in ampkt.data]).strip('\0')
- # Split printf data on newline character:
- # (last string in the split list doesn't have a newline after
- # it, so we keep it until next time)
- lines = self._printf_msg.split('\n')
- for line in lines[:-1]:
- print "PRINTF:", line
- self._printf_msg = lines[-1]
- packet = None # No further processing for the printf packet
- return packet
-
-class SFClient:
- def __init__(self, host, port, qsize=10):
- self._in_queue = Queue(qsize)
- self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._s.connect((host, port))
- data = self._s.recv(2)
- if data != 'U ':
- print "Wrong handshake"
- self._s.send("U ")
- print "Connected"
- thread.start_new_thread(self.run, ())
-
- def run(self):
- while True:
- length = ord(self._s.recv(1))
- data = self._s.recv(length)
- data = [ord(c) for c in data][1:]
- #print "Recv %d bytes" % (length), ActiveMessage(data)
- if self._in_queue.full():
- print "Warning: Buffer overflow"
- self._in_queue.get()
- p = RawPacket()
- p.data = data
- self._in_queue.put(p, block=False)
-
- def read(self, timeout=0):
- return self._in_queue.get()
-
- def write(self, payload):
- print "SFClient: write:", payload
- if type(payload) != type([]):
- # Assume this will be derived from Packet
- payload = payload.payload()
- payload = [0] + payload
- self._s.send(chr(len(payload)))
- self._s.send(''.join([chr(c) for c in payload]))
- return True
-
-class AM:
- def __init__(self, s):
- self._s = s