Esempio n. 1
0
    def serialReadEvent(self):
        # get that character we set up
        n = win32file.GetOverlappedResult(
            self._serial._port_handle, self._overlappedRead, 0
        )
        first = to_bytes(self.read_buf[:n])
        # now we should get everything that is already in the buffer
        flags, comstat = self._clearCommError()
        if comstat.cbInQue:
            win32event.ResetEvent(self._overlappedRead.hEvent)
            rc, buf = win32file.ReadFile(
                self._serial._port_handle,
                win32file.AllocateReadBuffer(comstat.cbInQue),
                self._overlappedRead,
            )
            n = win32file.GetOverlappedResult(
                self._serial._port_handle, self._overlappedRead, 1
            )
            # handle all the received data:
            self.protocol.dataReceived(first + to_bytes(buf[:n]))
        else:
            # handle all the received data:
            self.protocol.dataReceived(first)

        # set up next one
        win32event.ResetEvent(self._overlappedRead.hEvent)
        rc, self.read_buf = win32file.ReadFile(
            self._serial._port_handle,
            win32file.AllocateReadBuffer(1),
            self._overlappedRead,
        )
Esempio n. 2
0
    def write(self, data):
        if not self.is_open:
            raise portNotOpenError
        data = to_bytes(data)
        tx_len = len(data)
        while tx_len > 0:
            to_be_sent = min(tx_len, 0x3F)
            report = to_bytes([to_be_sent]) + data[:to_be_sent]
            self._hid_handle.write(report)

            data = data[to_be_sent:]
            tx_len = len(data)
Esempio n. 3
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = length = len(d)
     timeout = Timeout(self._write_timeout)
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout.is_non_blocking:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif not timeout.is_infinite:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 if timeout.expired():
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [],
                                                 timeout.time_left())
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout.time_left() is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             if e.errno not in (errno.EAGAIN, errno.EALREADY,
                                errno.EWOULDBLOCK, errno.EINPROGRESS,
                                errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         except select.error as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY,
                             errno.EWOULDBLOCK, errno.EINPROGRESS,
                             errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         if not timeout.is_non_blocking and timeout.expired():
             raise writeTimeoutError
     return length - len(d)
Esempio n. 4
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = len(d)
     if self._write_timeout is not None and self._write_timeout > 0:
         timeout = time.time() + self._write_timeout
     else:
         timeout = None
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 timeleft = timeout - time.time()
                 if timeleft < 0:
                     raise writeTimeoutError
                 _, ready, _ = select.select([], [self.fd], [], timeleft)
                 if not ready:
                     raise writeTimeoutError
             else:
                 # wait for write operation
                 _, ready, _ = select.select([], [self.fd], [], None)
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: %s' % (v,))
     return len(data)
Esempio n. 5
0
def start_server(port, baud_rate, receiver):
    """Start serial server. Keeps listening to the given port at the baud rate
    specified and writes the commands coming in to the receiver
    :param port: the serial port address to listen at
    :param baud_rate: the data transmission rate
    :param receiver: the receiver in charge of handling the incoming messages
    """
    with serial.Serial(port, baud_rate, timeout=2) as ser:
        print("Listening on port {}, press Ctrl+c to exit.".format(port))
        while True:
            if receiver.is_timeout():
                logger.warn("Timeout")
                receiver.reset()

            # Read from the sender
            line = ser.readline()
            if not line:
                continue

            # Notify the receiver with the new command
            receiver.write(line)

            # Does the receiver has to send something back?
            response = receiver.read()
            if response:
                socket = serial.Serial(port, baud_rate, timeout=10)
                socket.write(to_bytes(response))
Esempio n. 6
0
 def write(self, data):
     """\
     Output the given byte string over the serial port. Can block if the
     connection is blocked. May raise SerialException if the connection is
     closed.
     """
     self._cancel_write = False
     if not self.is_open:
         raise portNotOpenError
     data = to_bytes(data)
     # calculate aprox time that would be used to send the data
     time_used_to_send = 10.0 * len(data) / self._baudrate
     # when a write timeout is configured check if we would be successful
     # (not sending anything, not even the part that would have time)
     if self._write_timeout is not None and time_used_to_send > self._write_timeout:
         # must wait so that unit test succeeds
         time_left = self._write_timeout
         while time_left > 0 and not self._cancel_write:
             time.sleep(min(time_left, 0.5))
             time_left -= 0.5
         if self._cancel_write:
             return 0  # XXX
         raise writeTimeoutError
     for byte in iterbytes(data):
         self.queue.put(byte, timeout=self._write_timeout)
     return len(data)
Esempio n. 7
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     #~ if not isinstance(data, (bytes, bytearray)):
         #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
     # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
     data = to_bytes(data)
     if data:
         #~ win32event.ResetEvent(self._overlapped_write.hEvent)
         n = win32.DWORD()
         err = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
         if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
             raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
         if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
             # Wait for the write to complete.
             #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
             err = win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
             if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                 return n.value  # canceled IO is no error
             if n.value != len(data):
                 raise writeTimeoutError
         return n.value
     else:
         return 0
 def write(self, data):
     """\
     Output the given byte string over the serial port. Can block if the
     connection is blocked. May raise SerialException if the connection is
     closed.
     """
     self._cancel_write = False
     if not self.is_open:
         raise portNotOpenError
     data = to_bytes(data)
     # calculate aprox time that would be used to send the data
     time_used_to_send = 10.0 * len(data) / self._baudrate
     # when a write timeout is configured check if we would be successful
     # (not sending anything, not even the part that would have time)
     if self._write_timeout is not None and time_used_to_send > self._write_timeout:
         # must wait so that unit test succeeds
         time_left = self._write_timeout
         while time_left > 0 and not self._cancel_write:
             time.sleep(min(time_left, 0.5))
             time_left -= 0.5
         if self._cancel_write:
             return 0  # XXX
         raise writeTimeoutError
     for byte in iterbytes(data):
         self.queue.put(byte, timeout=self._write_timeout)
     return len(data)
Esempio n. 9
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = len(d)
     if self._write_timeout is not None and self._write_timeout > 0:
         timeout = time.time() + self._write_timeout
     else:
         timeout = None
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 timeleft = timeout - time.time()
                 if timeleft < 0:
                     raise writeTimeoutError
                 _, ready, _ = select.select([], [self.fd], [], timeleft)
                 if not ready:
                     raise writeTimeoutError
             else:
                 # wait for write operation
                 _, ready, _ = select.select([], [self.fd], [], None)
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: %s' % (v, ))
     return len(data)
Esempio n. 10
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     #~ if not isinstance(data, (bytes, bytearray)):
     #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
     # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
     data = to_bytes(data)
     if data:
         #~ win32event.ResetEvent(self._overlapped_write.hEvent)
         n = win32.DWORD()
         err = win32.WriteFile(self._port_handle, data, len(data),
                               ctypes.byref(n), self._overlapped_write)
         if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
             raise SerialException("WriteFile failed ({!r})".format(
                 ctypes.WinError()))
         if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
             # Wait for the write to complete.
             #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
             err = win32.GetOverlappedResult(self._port_handle,
                                             self._overlapped_write,
                                             ctypes.byref(n), True)
             if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                 return n.value  # canceled IO is no error
             if n.value != len(data):
                 raise writeTimeoutError
         return n.value
     else:
         return 0
Esempio n. 11
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = length = len(d)
     timeout = Timeout(self._write_timeout)
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout.is_non_blocking:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif not timeout.is_infinite:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 if timeout.expired():
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left())
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout.time_left() is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         except select.error as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         if not timeout.is_non_blocking and timeout.expired():
             raise writeTimeoutError
     return length - len(d)
 def write(self, data):
     """\
     Output the given byte string over the serial port. Can block if the
     connection is blocked. May raise SerialException if the connection is
     closed.
     """
     if not self.is_open:
         raise portNotOpenError
     try:
         self._socket.sendall(to_bytes(data))
     except socket.error as e:
         # XXX what exception if socket connection fails
         raise SerialException("socket connection failed: %s" % e)
     return len(data)
Esempio n. 13
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = len(d)
     timeout = self._write_timeout
     if timeout and timeout > 0:  # Avoid comparing None with zero
         timeout += time.time()
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout == 0:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif timeout and timeout > 0:  # Avoid comparing None with zero
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 timeleft = timeout - time.time()
                 if timeleft < 0:
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [], timeleft)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: {}'.format(v))
             # still calculate and check timeout
             if timeout and timeout - time.time() < 0:
                 raise writeTimeoutError
     return len(data)
    def serialReadEvent(self):
        #get that character we set up
        n = win32file.GetOverlappedResult(self._serial._port_handle, self._overlappedRead, 0)
        first = to_bytes(self.read_buf[:n])
        #now we should get everything that is already in the buffer
        flags, comstat = self._clearCommError()
        if comstat.cbInQue:
            win32event.ResetEvent(self._overlappedRead.hEvent)
            rc, buf = win32file.ReadFile(self._serial._port_handle,
                                         win32file.AllocateReadBuffer(comstat.cbInQue),
                                         self._overlappedRead)
            n = win32file.GetOverlappedResult(self._serial._port_handle, self._overlappedRead, 1)
            #handle all the received data:
            self.protocol.dataReceived(first + to_bytes(buf[:n]))
        else:
            #handle all the received data:
            self.protocol.dataReceived(first)

        #set up next one
        win32event.ResetEvent(self._overlappedRead.hEvent)
        rc, self.read_buf = win32file.ReadFile(self._serial._port_handle,
                                               win32file.AllocateReadBuffer(1),
                                               self._overlappedRead)
Esempio n. 15
0
 def write(self, data):
     """\
     Output the given byte string over the serial port. Can block if the
     connection is blocked. May raise SerialException if the connection is
     closed.
     """
     if not self.is_open:
         raise portNotOpenError
     try:
         self._socket.sendall(to_bytes(data))
     except socket.error as e:
         # XXX what exception if socket connection fails
         raise SerialException("socket connection failed: %s" % e)
     return len(data)
Esempio n. 16
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = len(d)
     timeout = self._write_timeout
     if timeout and timeout > 0:   # Avoid comparing None with zero
         timeout += time.time()
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout == 0:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif timeout and timeout > 0:  # Avoid comparing None with zero
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 timeleft = timeout - time.time()
                 if timeleft < 0:
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeleft)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: {}'.format(v))
             # still calculate and check timeout
             if timeout and timeout - time.time() < 0:
                 raise writeTimeoutError
     return len(data)
Esempio n. 17
0
    def write(self, data):
        """Output the given byte string over the serial port."""
        if not self.is_open:
            raise PortNotOpenError()
        #~ if not isinstance(data, (bytes, bytearray)):
        #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
        data = to_bytes(data)
        if data:
            #~ win32event.ResetEvent(self._overlapped_write.hEvent)
            n = win32.DWORD()
            success = win32.WriteFile(self._port_handle, data, len(data),
                                      ctypes.byref(n), self._overlapped_write)
            if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
                if not success and win32.GetLastError() not in (
                        win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
                    raise SerialException("WriteFile failed ({!r})".format(
                        ctypes.WinError()))

                # Wait for the write to complete.
                #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
                win32.GetOverlappedResult(self._port_handle,
                                          self._overlapped_write,
                                          ctypes.byref(n), True)
                if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                    return n.value  # canceled IO is no error
                if n.value != len(data):
                    raise SerialTimeoutException('Write timeout')
                return n.value
            else:
                errorcode = win32.ERROR_SUCCESS if success else win32.GetLastError(
                )
                if errorcode in (win32.ERROR_INVALID_USER_BUFFER,
                                 win32.ERROR_NOT_ENOUGH_MEMORY,
                                 win32.ERROR_OPERATION_ABORTED):
                    return 0
                elif errorcode in (win32.ERROR_SUCCESS,
                                   win32.ERROR_IO_PENDING):
                    # no info on true length provided by OS function in async mode
                    return len(data)
                else:
                    raise SerialException("WriteFile failed ({!r})".format(
                        ctypes.WinError()))
        else:
            return 0
Esempio n. 18
0
    def write(self, data):
        """\
        Output the given byte string over the serial port. Can block if the
        connection is blocked. May raise SerialException if the connection is
        closed.
        """
        if not self.is_open:
            raise portNotOpenError

        d = to_bytes(data)
        tx_len = length = len(d)
        timeout = Timeout(self._write_timeout)
        while tx_len > 0:
            try:
                n = self._socket.send(d)
                if timeout.is_non_blocking:
                    # Zero timeout indicates non-blocking - simply return the
                    # number of bytes of data actually written
                    return n
                elif not timeout.is_infinite:
                    # when timeout is set, use select to wait for being ready
                    # with the time left as timeout
                    if timeout.expired():
                        raise writeTimeoutError
                    _, ready, _ = select.select([], [self._socket], [],
                                                timeout.time_left())
                    if not ready:
                        raise writeTimeoutError
                else:
                    assert timeout.time_left() is None
                    # wait for write operation
                    _, ready, _ = select.select([], [self._socket], [], None)
                    if not ready:
                        raise SerialException('write failed (select)')
                d = d[n:]
                tx_len -= n
            except SerialException:
                raise
            except OSError as v:
                if v.errno != errno.EAGAIN:
                    raise SerialException('write failed: {}'.format(v))
                # still calculate and check timeout
                if timeout.expired():
                    raise writeTimeoutError
        return length - len(d)
Esempio n. 19
0
    def write(self, data):
        """Output the given byte string over the serial port."""
        if not self.is_open:
            raise portNotOpenError
        #~ if not isinstance(data, (bytes, bytearray)):
            #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
        data = to_bytes(data)
        if data:
            #~ win32event.ResetEvent(self._overlapped_write.hEvent)
            n = win32.DWORD()
            success = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
            if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
                if not success and win32.GetLastError() != win32.ERROR_IO_PENDING:
                    raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))

                # Wait for the write to complete.
                #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
                win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
                if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                    return n.value  # canceled IO is no error
                if n.value != len(data):
                    raise writeTimeoutError
                return n.value
            else:
                errorcode = win32.ERROR_SUCCESS if success else win32.GetLastError()
                if errorcode in (win32.ERROR_INVALID_USER_BUFFER, win32.ERROR_NOT_ENOUGH_MEMORY,
                                 win32.ERROR_OPERATION_ABORTED):
                    return 0
                elif errorcode in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
                    # no info on true length provided by OS function in async mode
                    return len(data)
                else:
                    raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
        else:
            return 0
Esempio n. 20
0
def getc(size, timeout=1):
    data = to_bytes(ser.read(size))
    return data
Esempio n. 21
0
 def write_delayed(data):
     data = to_bytes(data)
     data = [bytes([b]) for b in data]
     for b in data:
         self.ser.__write_orig(b)
         time.sleep(delay)
Esempio n. 22
0
def putc(data, timeout=1):
    data = to_bytes(data)
    return ser.write(data)
Esempio n. 23
0
 def write(self, tx):
     tx = to_bytes(tx)
     self.formatter.tx(tx)
     return super(Serial, self).write(tx)
Esempio n. 24
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# Python port of BaySerial PHP library
# Author: Stefan Holzheu <*****@*****.**>
#
# 
# 
from time import time, sleep
import serial
from struct import pack, unpack
from serial.serialutil import XON, XOFF, to_bytes

XBEE_ESCAPE  = to_bytes([0x7d])
XBEE_DELIM = to_bytes([0x7e])
API_DATA = to_bytes([0x1])
API_ACK = to_bytes([0x2])
TX_OK = to_bytes([0x1])
TX_CHECKSUM_FAILED = to_bytes([0x2])
TX_BREAK = to_bytes([0x3])

class BaySerial:
    def __init__(self):
        self.ser=None
        self.stack=[]
        self.count=0;
    
    def begin(self,dev,baud=38400):
        self.ser=serial.Serial(dev,baud,timeout=0)
Esempio n. 25
0
#!/usr/bin/python
import os, sqlite3, time
from serial.serialutil import to_bytes

conn = sqlite3.connect('/home/pi/workspace/raspi_net/server/db/sys.db')
c = conn.cursor()
print "Opened database successfully"

cursor = c.execute("SELECT TEMP, HUMI FROM TEMP_HUMI ORDER BY ID DESC LIMIT 1")
row = cursor.fetchone()
command = str(round(row[0], 2)) + "_" + str(round(row[1], 2)) + "_" + str(
    time.strftime("%H", time.localtime()))

print "Operation done successfully"
conn.close()

print command + "\n"

d = to_bytes(command)
serial = os.open('/dev/ttyACM0', os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
os.write(serial, d)