Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SocketSerial feature, to work with optional network relay #58

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyfirmata/mockup.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ def start(self):
def stop(self):
pass


if __name__ == '__main__':
import doctest
doctest.testmod()
Expand Down
30 changes: 29 additions & 1 deletion pyfirmata/pyfirmata.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import time

import serial
import socket
import select

from .util import pin_list_to_board_dict, to_two_bytes, two_byte_iter_to_str

Expand Down Expand Up @@ -75,6 +77,29 @@ class NoInputWarning(RuntimeWarning):
pass


class SocketSerial(socket.socket):
"""SocketSerial -- provides the identical api to serial.Serial()
you can use it as a drop in replacement for serial.Serial, for pushing firmata stream over the
network."""
def __init__(self, host_port, name=None, timeout=None, **kw):
super().__init__()
(host, port) = host_port.split(':')
addr = socket.getaddrinfo(host, port)[0][-1]
self.connect(addr)
self.setblocking(False)
self.poll = select.poll()
self.poll.register(self, select.POLLIN)

def inWaiting(self):
return self.poll.poll(0)

def read(self):
return self.recv(1)

def write(self, buf):
self.send(buf)


class Board(object):
"""The Base class for any board."""
firmata_version = None
Expand All @@ -86,7 +111,10 @@ class Board(object):
_parsing_sysex = False

def __init__(self, port, layout=None, baudrate=57600, name=None, timeout=None):
self.sp = serial.Serial(port, baudrate, timeout=timeout)
if ':' in port:
self.sp = SocketSerial(port, name=name, timeout=timeout)
else:
self.sp = serial.Serial(port, baudrate, timeout=timeout)
# Allow 5 secs for Arduino's auto-reset to happen
# Alas, Firmata blinks its version before printing it to serial
# For 2.3, even 5 seconds might not be enough.
Expand Down