diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..34bd795 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Modulo.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Modulo.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/Modulo" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Modulo" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..1bd2029 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# +# Modulo documentation build configuration file, created by +# sphinx-quickstart on Thu Feb 12 21:07:25 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('..')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Modulo' +copyright = u'2015, Erin Tomson' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '.1' +# The full version, including alpha/beta/rc tags. +release = '.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Modulodoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'Modulo.tex', u'Modulo Documentation', + u'Erin Tomson', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'modulo', u'Modulo Documentation', + [u'Erin Tomson'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'Modulo', u'Modulo Documentation', + u'Erin Tomson', 'Modulo', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..ed05e37 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,76 @@ +Modulo Python Documentation +=========================== + + +Introduction +------------ + + The Modulo python library is easy to use. Simply create a Port object + to open a connection to the hardware, then create a specific type of + Module object for each device that you wish to use. + + The example below gets the angle from a knob and prints it on a display.:: + + import modulo, time + + port = modulo.Port() + knob = modulo.Knob(port) + display = modulo.Display(port) + + while True : + display.clear() + display.set_cursor(0,0) + display.writeln(knob.get_angle()) + display.update() + time.sleep(.05) + +Port +---- + +.. autoclass:: modulo.Port + :members: + :undoc-members: + + +Modules +------- + +.. autosummary:: + modulo.Module + modulo.Display + modulo.DPad + modulo.Knob + modulo.Thermocouple + modulo.Clock + modulo.Controller + +.. autoclass:: modulo.Module + :members: + :undoc-members: + +.. autoclass:: modulo.Display + :members: + :undoc-members: + +.. autoclass:: modulo.DPad + :members: + :undoc-members: + +.. autoclass:: modulo.Knob + :members: + :undoc-members: + +.. autoclass:: modulo.Thermocouple + :members: + :undoc-members: + +.. autoclass:: modulo.Clock + :members: + :undoc-members: + +.. autoclass:: modulo.Controller + :members: + :undoc-members: + + + diff --git a/examples/angle.py b/examples/angle.py new file mode 100644 index 0000000..687a525 --- /dev/null +++ b/examples/angle.py @@ -0,0 +1,12 @@ +import modulo, time + +port = modulo.Port() +knob = modulo.Knob(port) +display = modulo.Display(port) + +while True : + display.clear() + display.set_cursor(0,0) + display.writeln(knob.get_angle()) + display.update() + time.sleep(.05) \ No newline at end of file diff --git a/examples/knob.py b/examples/knob.py old mode 100644 new mode 100755 index 6668dcc..2c13a74 --- a/examples/knob.py +++ b/examples/knob.py @@ -1,3 +1,5 @@ +#!/usr/bin/python + import modulo, math # Open the first Modulo Controller serial port @@ -42,6 +44,6 @@ display.draw_rectangle(20,20,10,10) display.update() - knob.set_color(255,0,255) + knob.set_color(255,255,0) print clock.is_set(), clock.is_battery_low(), clock.get_datetime() diff --git a/examples/setclock.py b/examples/setclock.py new file mode 100755 index 0000000..8f61a02 --- /dev/null +++ b/examples/setclock.py @@ -0,0 +1,11 @@ +#!/usr/bin/python + +import modulo, datetime + +port = modulo.SerialPort() + +clock = port.get_clock() + +clock.set_datetime(datetime.datetime.now()) + +print clock.get_datetime() diff --git a/modulo/__init__.py b/modulo/__init__.py index 98cd6a5..991bc7c 100755 --- a/modulo/__init__.py +++ b/modulo/__init__.py @@ -1,33 +1,108 @@ #!/usr/bin/python + +""" +Modulo Docstring +""" + import os, math import ctypes, ctypes.util, serial + class Port(object) : + """ + The Port class represents a physical connection to Modulo devices through a usb or i2c port. + Once a port has been opened, create a Module object for each device that's connected to the port. + + """ + + + _BroadcastAddress = 9 + + _BroadcastCommandGlobalReset = 0 + _BroadcastCommandGetNextDeviceID = 1 + _BroadcastCommandSetAddress = 2 + _BroadcastCommandGetAddress = 3 + _BroadcastCommandGetDeviceType = 4 + _BroadcastCommandGetVersion = 5 + _BroadcastCommandGetManufacturer = 6 + _BroadcastCommandGetProduct = 7 + _BroadcastCommandGetDocURL = 8 + _BroadcastCommandGetDocURLContinued = 9 + _BroadcastCommandGetInterrupt = 10 + _BroadcastCommandSetStatusLED = 11 + + class _SerialConnection(object) : + def __init__(self, path=None, controller=0) : + super(Port._SerialConnection, self).__init__() + + if path is None : + from serial.tools.list_ports import comports + for port in comports() : + if (port[1] == 'Modulo Controller') : + if (controller == 0) : + path = port[0] + break + controller -= 1 + + self._serial = serial.Serial(path, 9600, timeout=5) + + def transfer(self, address, command, sendData, receiveLen) : + if address is None : + return None + + self._serial.write('T') # Transfer start token + self._serial.write(chr(address)) + self._serial.write(chr(command)) + self._serial.write(chr(len(sendData))) + for c in sendData : + self._serial.write(chr(c)) + self._serial.write(chr(receiveLen)) + + retval = ord(self._serial.read(1)) + if retval and receiveLen > 0: + return [ord(x) for x in self._serial.read(receiveLen)] + return None + + class _I2CConnection(object) : + + def __init__(self, i2cPath) : + super(Port._I2CConnection, self).__init__() + + self._i2cfd = os.open(i2cPath, os.O_RDWR) + if self._i2cfd < 0 : + raise StandardError('Unable to open the i2c device ' + path) + + # This is the ctypes function for transferring data via i2c + self._dll = ctypes.cdll.LoadLibrary('libmodulo.so') + self.transferFunction = self._dll.modulotransfer + + # Wrapper around the modulotransfer function from the dll + def transfer(self, address, command, sendData, receiveLen) : + if address is None : + return None - BroadcastAddress = 9 - - BroadcastCommandGlobalReset = 0 - BroadcastCommandGetNextDeviceID = 1 - BroadcastCommandSetAddress = 2 - BroadcastCommandGetAddress = 3 - BroadcastCommandGetDeviceType = 4 - BroadcastCommandGetVersion = 5 - BroadcastCommandGetManufacturer = 6 - BroadcastCommandGetProduct = 7 - BroadcastCommandGetDocURL = 8 - BroadcastCommandGetDocURLContinued = 9 - BroadcastCommandGetInterrupt = 10 - BroadcastCommandSetStatusLED = 11 - - StatusOff = 0 - StatusOn = 1 - StatusBlinking = 2 - StatusBreathing = 3 - - def __init__(self) : - self._busInitialized = False + sendBuffer = ctypes.create_string_buffer(len(sendData)) + for i in range(len(sendData)) : + sendBuffer[i] = chr(sendData[i]) + receiveBuffer = ctypes.create_string_buffer(receiveLen) + + if (self.transferFunction(self._fd, address, command, sendBuffer, len(sendData), + receiveBuffer, receiveLen) < 0) : + return None + + return [ord(x) for x in receiveBuffer] + + + def __init__(self, serialPortPath=None, i2cPortPath=None) : + self._portInitialized = False self._lastAssignedAddress = 9 + if (i2cPortPath) : + self._connection = self._I2CConnection(i2cPortPath) + else : + self._connection = self._SerialConnection(serialPortPath) + + def _bytesToString(self, bytes) : s = '' for b in bytes : @@ -37,25 +112,26 @@ def _bytesToString(self, bytes) : return s - # Reset all devices on the bus - def global_reset(self) : - self._transfer(self.BroadcastAddress, self.BroadcastCommandGlobalReset, [], 0) - def assign_address(self, requestedDeviceType, deviceID) : + # Reset all devices on the port + def _global_reset(self) : + self._connection.transfer(self._BroadcastAddress, self._BroadcastCommandGlobalReset, [], 0) + + def _assign_address(self, requestedDeviceType, deviceID) : # Ensure that a global reset has been performed - if not self._busInitialized : - self._busInitialized = True - self.global_reset() + if not self._portInitialized : + self._portInitialized = True + self._global_reset() # If no deviceID has been specified, find the first # device with the specified type if deviceID is None : - deviceID = self.get_next_device_id(0) + deviceID = self._get_next_device_id(0) while deviceID is not None : - deviceType = self.get_device_type(deviceID) + deviceType = self._get_device_type(deviceID) if deviceType == requestedDeviceType : break - deviceID = self.get_next_device_id(deviceID+1) + deviceID = self._get_next_device_id(deviceID+1) # No device found. We can't assign an address if deviceID is None : @@ -64,241 +140,226 @@ def assign_address(self, requestedDeviceType, deviceID) : self._lastAssignedAddress += 1 address = self._lastAssignedAddress - self.set_address(deviceID, address) + self._set_address(deviceID, address) return address - def set_address(self, deviceID, address) : + def _set_address(self, deviceID, address) : sendData = [deviceID & 0xFF, deviceID >> 8, address] - self._transfer(self.BroadcastAddress, self.BroadcastCommandSetAddress, + self._connection.transfer(self._BroadcastAddress, self._BroadcastCommandSetAddress, sendData, 0) - def get_address(self, deviceID) : + def _get_address(self, deviceID) : sendData = [deviceID & 0xFF, deviceID >> 8] - retval = self._transfer(self.BroadcastAddress, self.BroadcastCommandGetAddress, + retval = self._connection.transfer(self._BroadcastAddress, self._BroadcastCommandGetAddress, sendData, 1) if retval is None : return None return retval[0] - def get_manufacturer(self, deviceID) : + def _get_manufacturer(self, deviceID) : sendData = [deviceID & 0xFF, deviceID >> 8] - resultData = self._transfer( - self.BroadcastAddress, self.BroadcastCommandGetManufacturer, sendData, 31) + resultData = self._connection.transfer( + self._BroadcastAddress, self._BroadcastCommandGetManufacturer, sendData, 31) return self._bytesToString(resultData) - def get_product(self, deviceID) : + def _get_product(self, deviceID) : sendData = [deviceID & 0xFF, deviceID >> 8] - resultData = self._transfer( - self.BroadcastAddress, self.BroadcastCommandGetProduct, sendData, 31) + resultData = self._connection.transfer( + self._BroadcastAddress, self._BroadcastCommandGetProduct, sendData, 31) return self._bytesToString(resultData) - def set_status(self, deviceID, status) : + def _set_status(self, deviceID, status) : sendData = [deviceID & 0xFF, deviceID >> 8, status] - resultData = self._transfer( - self.BroadcastAddress, self.BroadcastCommandSetStatusLED, sendData, 0) + resultData = self._connection.transfer( + self._BroadcastAddress, self._BroadcastCommandSetStatusLED, sendData, 0) - # Returns the device ID of the device on the bus with the + # Returns the device ID of the device on the port with the # next greater ID than the one provided. - def get_next_device_id(self, lastDeviceID) : + def _get_next_device_id(self, lastDeviceID) : sendData = [lastDeviceID & 0xFF, lastDeviceID >> 8] - resultData = self._transfer( - self.BroadcastAddress, self.BroadcastCommandGetNextDeviceID, sendData, 2) + resultData = self._connection.transfer( + self._BroadcastAddress, self._BroadcastCommandGetNextDeviceID, sendData, 2) if resultData is None : return None return resultData[1] | (resultData[0] << 8) - def get_version(self, deviceID) : + def _get_version(self, deviceID) : sendData = [deviceID & 0xFF, deviceID >> 8] - retval = self._transfer(self.BroadcastAddress, self.BroadcastCommandGetVersion, + retval = self._connection.transfer(self._BroadcastAddress, self._BroadcastCommandGetVersion, sendData, 2) if retval is None : return None return retval[0] | (retval[1] << 8) - def get_device_type(self, deviceID) : + def _get_device_type(self, deviceID) : sendData = [deviceID & 0xFF, deviceID >> 8] - resultData = self._transfer( - self.BroadcastAddress, self.BroadcastCommandGetDeviceType, sendData, 31) + resultData = self._connection.transfer( + self._BroadcastAddress, self._BroadcastCommandGetDeviceType, sendData, 31) return self._bytesToString(resultData) - def get_motor(self, deviceID=None) : - return MotorModule(self, deviceID) - - def get_dpad(self, deviceID=None) : - return DPadModule(self, deviceID) - - def get_clock(self, deviceID=None) : - return ClockModule(self, deviceID) - - def get_knob(self, deviceID=None) : - return KnobModule(self, deviceID) - - def get_mini_display(self, deviceID=None) : - return MiniDisplayModule(self, deviceID) - - def get_io(self, deviceID=None) : - return IOModule(self, deviceID) - - def get_thermocouple(self, deviceID=None) : - return ThermocoupleModule(self, deviceID) - - -class SerialPort(Port) : - def __init__(self, path=None, controller=0) : - super(SerialPort, self).__init__() - - if path is None : - from serial.tools.list_ports import comports - for port in comports() : - if (port[1] == 'Modulo Controller') : - if (controller == 0) : - path = port[0] - break - controller -= 1 - - self._serial = serial.Serial(path, 9600, timeout=5) - - def _transfer(self, address, command, sendData, receiveLen) : - if address is None : - return None - - self._serial.write('T') # Transfer start token - self._serial.write(chr(address)) - self._serial.write(chr(command)) - self._serial.write(chr(len(sendData))) - for c in sendData : - self._serial.write(chr(c)) - self._serial.write(chr(receiveLen)) - - retval = ord(self._serial.read(1)) - if retval and receiveLen > 0: - return [ord(x) for x in self._serial.read(receiveLen)] - return None - -class I2CPort(Port) : - - def __init__(self, i2cPath) : - super(I2CPort, self).__init__() - - self._i2cfd = os.open(i2cPath, os.O_RDWR) - if self._i2cfd < 0 : - raise StandardError('Unable to open the i2c device ' + path) - - # This is the ctypes function for transferring data via i2c - self._dll = ctypes.cdll.LoadLibrary('libmodulo.so') - self._transferFunction = self._dll.modulo_transfer - - # Wrapper around the modulo_transfer function from the dll - def _transfer(self, address, command, sendData, receiveLen) : - if address is None : - return None - - sendBuffer = ctypes.create_string_buffer(len(sendData)) - for i in range(len(sendData)) : - sendBuffer[i] = chr(sendData[i]) - receiveBuffer = ctypes.create_string_buffer(receiveLen) - - if (self._transferFunction(self._fd, address, command, sendBuffer, len(sendData), - receiveBuffer, receiveLen) < 0) : - return None - - return [ord(x) for x in receiveBuffer] +class Module(object) : + """ + The base class for all Modules. Generally you should not create instances + of this class directly. + """ + def __init__(self, port, deviceType, deviceID) : + if port is None : + raise ValueError("Cannot create a Module with an invalid port") -class Module(object) : - def __init__(self, bus, deviceType, deviceID) : - self._bus = bus + self._port = port self._deviceType = deviceType self._deviceID = deviceID self._address = None - def _transfer(self, command, sendData, receiveLen) : - return self._bus._transfer(self.get_address(), command, sendData, receiveLen) + def transfer(self, command, sendData, receiveLen) : + return self._port._connection.transfer(self.get_address(), command, sendData, receiveLen) def get_address(self) : + """ + Returns the module's i2c address. + + A module's address is an 8 bit number used to identify the device on the i2c bus. + The address will be assigned automatically when the device is first accessed + after power up or after a global reset. + + Normally you do not need to know a Module's address or do anything with it directly + """ + if self._address is None : - self._address = self._bus.assign_address(self._deviceType, self._deviceID) + self._address = self._port._assign_address(self._deviceType, self._deviceID) return self._address -class MotorModule(Module) : - - def __init__(self, bus, deviceID = None) : - super(self, MotorModule).__init__(bus, "co.modulo.motor", deviceID) + def get_device_id(self) : + """ + Returns the module's device ID. + A module's device ID is a 16 bit number that is programmed into the device by + the manufacturer. It never changes and therefore can be reliably used to distingush + one module from another, even if they are the same type of module + """ -class KnobModule(Module) : + return self._deviceID - FunctionGetButton = 0 - FunctionGetPosition = 1 - FunctionAddOffsetPosition = 2 - FunctionSetColor = 3 +class Knob(Module) : + """ + Connect to the module with the specified *deviceID* on the given *port*. + If *deviceID* isn't specified, finds the first unused KnobModule. + """ - def __init__(self, bus, deviceID = None) : - super(KnobModule, self).__init__(bus, "co.modulo.knob", deviceID) + _FunctionGetButton = 0 + _FunctionGetPosition = 1 + _FunctionAddOffsetPosition = 2 + _FunctionSetColor = 3 - def set_color(self, r, g, b) : - sendData = [r,g,b] - self._transfer(self.FunctionSetColor, sendData, 0) + def __init__(self, port, deviceID = None) : + super(Knob, self).__init__(port, "co.modulo.knob", deviceID) + + def set_color(self, red, green, blue) : + """Set the color of the knob's LED. *red*, *green*, and *blue* should be + between 0 and 1""" + sendData = [r*255,g*255,b*255] + self.transfer(self._FunctionSetColor, sendData, 0) def get_button(self) : - receivedData = self._transfer(self.FunctionGetButton, [], 1) + """Return whether the knob is currently being pressed""" + receivedData = self.transfer(self._FunctionGetButton, [], 1) if receivedData is None : return False return bool(receivedData[0]) def get_position(self) : - receivedData = self._transfer(self.FunctionGetPosition, [], 2) + """Return the position of the knob in steps. There are 24 steps per revolution""" + receivedData = self.transfer(self._FunctionGetPosition, [], 2) if receivedData is None : return 0 return ctypes.c_short(receivedData[0] | (receivedData[1] << 8)).value -class DPadModule(Module) : - FunctionGetButtons = 0 + def get_angle(self) : + """Return the knob's angle in degrees""" + return self.get_position()*360/24 + +class DPad(Module) : + """ + Connect to the module with the specified *deviceID* on the given *port*. + If *deviceID* isn't specified, finds the first unused DPadModule. + """ - def __init__(self, bus, deviceID = None) : - super(DPadModule, self).__init__(bus, "co.modulo.dpad", deviceID) + _FunctionGetButtons = 0 + + def __init__(self, port, deviceID = None) : + super(DPad, self).__init__(port, "co.modulo.dpad", deviceID) def get_button(self, button) : + """Return whether the specified button is currently being pressed""" return bool(self.getButtons() & (1 << button)) def get_buttons(self) : - receivedData = self._transfer(self.FunctionGetButtons, [], 1) + """Return a byte with the state of each button in a different bit""" + receivedData = self.transfer(self._FunctionGetButtons, [], 1) if receivedData is None : return 0 return receivedData[0] -class ThermocoupleModule(Module) : - FunctionGetTemperature = 0 +class Thermocouple(Module) : + """ + Connect to the module with the specified *deviceID* on the given *port*. + If *deviceID* isn't specified, finds the first unused ThermocoupleModule. + """ + + _FunctionGetTemperature = 0 + + InvalidTemperature = -1000 + + def __init__(self, port, deviceID = None) : + super(ThermocoupleModule, self).__init__(port, "co.modulo.thermocouple", deviceID) - def __init__(self, bus, deviceID = None) : - super(ThermocoupleModule, self).__init__(bus, "co.modulo.thermocouple", deviceID) def get_celsius(self) : - receivedData = self._transfer(self.FunctionGetTemperature, [], 2) + """ + Return the thermocouple temperature in celsius. + Returns None if no probe is connected + """ + + receivedData = self.transfer(self._FunctionGetTemperature, [], 2) if (receivedData is None) : return None tenths = ctypes.c_short(receivedData[0] | (receivedData[1] << 8)).value + if (tenths == -10000) : # Check for the invalid temperature sentinal + return None return tenths/10.0 def get_fahrenheit(self) : + """ + Return the thermocouple temperature in celsius. + Returns None if no probe is connected + """ tempC = self.getTemperatureC() if (tempC is None) : return None return tempC*1.8 + 32 -class ClockModule(Module) : +class Clock(Module) : + """ + Connect to the module with the specified *deviceID* on the given *port*. + If *deviceID* isn't specified, finds the first unused ClockModule. + """ - FunctionGetTime = 0 - FunctionSetTime = 1 - FunctionGetTemperature = 2 + _FunctionGetTime = 0 + _FunctionSetTime = 1 + _FunctionGetTemperature = 2 - def __init__(self, bus, deviceID = None) : - super(ClockModule, self).__init__(bus, "co.modulo.clock", deviceID) + def __init__(self, port, deviceID = None) : + super(Clock, self).__init__(port, "co.modulo.clock", deviceID) def get_datetime(self) : - receivedData = self._transfer(self.FunctionGetTime, [], 9) + """ + Return a datetime object representing the date and time stored + in the clock module + """ + receivedData = self.transfer(self._FunctionGetTime, [], 9) if (receivedData is None) : return None @@ -315,6 +376,11 @@ def get_datetime(self) : receivedData[0]) # second def set_datetime(self, t = None) : + """ + Set the module's date and time using the provided datetime, or the current + date and time if *t* is None + """ + if t is None : import datetime t = datetime.datetime.now() @@ -327,30 +393,57 @@ def set_datetime(self, t = None) : t.weekday(), t.month, t.year-2000] - self._transfer(self.FunctionSetTime, sendData, 0) + self.transfer(self._FunctionSetTime, sendData, 0) def is_set(self) : - receivedData = self._transfer(self.FunctionGetTime, [], 9) + """ + Return whether the date and time have been set since the last battery failure + """ + receivedData = self.transfer(self._FunctionGetTime, [], 9) if (receivedData is None) : return False return bool(receivedData[7]) def is_battery_low(self) : - receivedData = self._transfer(self.FunctionGetTime, [], 9) + """ + Return whether the battery is low + """ + receivedData = self.transfer(self._FunctionGetTime, [], 9) if (receivedData is None) : return False return bool(receivedData[8]) -class MiniDisplayModule(Module) : +class Controller(Module) : + """ + Connect to the Controller module on the given port. + + TODO: Needs additional API for accessing I/O pins. + """ + + def __init__(self, port) : + super(Controller, self).__init__(port, "co.modulo.controller", deviceID) + + def readTemperatureProbe(self, pin) : + receivedData = self.transfer(self._FunctionReadTemperatureProbe, [pin], 2) + return ctypes.c_short(receivedData[0] | (receivedData[1] << 8)).value + +class Display(Module) : + """ + Connect to the module with the specified *deviceID* on the given *port*. + If *deviceID* isn't specified, finds the first unused MiniDisplayModule. + """ + SetPixelsFunction = 0 - def __init__(self, bus, deviceID = None) : - super(MiniDisplayModule, self).__init__(bus, "co.modulo.MiniDisplay", deviceID) + def __init__(self, port, deviceID = None) : + + super(Display, self).__init__(port, "co.modulo.MiniDisplay", deviceID) self._width = 128 self._height = 64 + self._cursor = (0,0) self._currentBuffer = bytearray(self._width*self._height/8) self._previousBuffer = bytearray(self._width*self._height/8) @@ -364,22 +457,55 @@ def __init__(self, bus, deviceID = None) : self._drawContext.text((0,0), "Hello", fill=1) def get_width(self) : + "The width in pixels of the display" return self._width def get_height(self) : + "The height in pixels of the display" return self._height + def set_cursor(self, x, y) : + self._cursor = (x,y) + + def write(self, obj, color=1) : + first = True + for line in str(obj).split("\n") : + w,h = self._drawContext.textsize(line) + x,y = self._cursor + + if not first : + x = 0 + y += h + + self._drawContext.text((x,y), line, fill=color) + + first = False + self._cursor = (x+w, y) + + def writeln(self, obj, color=1) : + self.write(str(obj) + "\n", color) + def clear(self, color=0) : + "Clear the display, setting all pixels to the specified *color*." self.draw_rectangle(0, 0, self._width, self._height, fill=color, outline=None) def draw_pixel(self, x, y, color) : + "Set a single pixel to the specified *color*" self._drawContext.point((x,y), color) def draw_line(self, points, color=1, width=1) : + """ + Draw lines connecting the specified points (a sequence of (x,y) tuples) + with the specified *color* and *width* + """ self._drawContext.line(points, fill=color, width=width) - def draw_ellipse(self, x, y, w, h, fill=None, outline=1) : - self._drawContext.ellipse([x,y,x+w,y+h], fill=fill, outline=outline) + def draw_ellipse(self, x, y, width, height, fill=None, outline=1) : + """ + Draw an elipse centered at *x*,*y* with given *width* and *height* + Optionally *fill* and *outline* the elipse with the specified + """ + self._drawContext.ellipse([x,y,x+width,y+height], fill=fill, outline=outline) def draw_arc(self, x, y, w, h, start, end, outline) : self._drawContext.arc([x,y,x+w, y+h], start, end, fill=outline) @@ -394,6 +520,8 @@ def draw_polygon(self, points, fill, outline) : self._drawContext.polygon(points, fill=fill, outline=outline) def update(self) : + """Update the display with the current image""" + # Copy the pixels from the PIL image into the _currentBuffer bytearray for x in range(self._width) : for y in range(self._height) : @@ -415,4 +543,4 @@ def update(self) : dataToSend.append(self._currentBuffer[index]) if (needsTransfer) : - self._transfer(self.SetPixelsFunction, dataToSend, 0) + self.transfer(self.SetPixelsFunction, dataToSend, 0)