#!/usr/bin/env python """ Copyright (C) 2009 Devon Jones Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For questions regarding this application contact Devon Jones , """ from twisted.internet.protocol import DatagramProtocol, Protocol from twisted.internet import reactor from twisted.internet.serialport import SerialPort from twisted.protocols.basic import LineReceiver from twisted.web import static, server from twisted.web.resource import Resource from optparse import OptionParser import time import sys import os import getopt import re class AmbientResource(Resource): def __init__(self, serialport): self.serialport = serialport def render_POST(self, request): data = request.content.getvalue() try: data = self.validate_data(data.strip()) except: request.setResponseCode(500) return "Invalid post data. Proper form should look like #000000 (where 0 can be any HEX value), or \"roam\"\n" serialwrite(self.serialport, data) request.setResponseCode(204) return "" def validate_data(self, data): data = data.upper() if data == "ROAM": return data if not re.match('^#[0-9A-F]{6}$', data): raise Exception("Invalid post data.") return data class AmbientUDPProtocol(DatagramProtocol): def __init__(self, serialport): self.actions = {} self.serialport = serialport self.lines = [] def bind(self, action, address): self.actions[address] = action def clearBinds(self): self.actions.clear() def datagramReceived(self, data, (host, port)): self.lines.append(data) if data.find('\n') > -1: values = ''.join(self.lines).split('\n') self.completeLine(values) elif data.find('\r') > -1: values = ''.join(self.lines).split('\r') self.completeLine(values) def completeLine(self, values): data = values.pop(0).strip() self.lines = values serialwrite(self.serialport, data) class Client(LineReceiver): def __init__(self, handler): self.linehandler = handler self.setRawMode() def rawDataReceived(self, data): self.linehandler(self, data) def connectionMade(self): pass def serialwrite(serialport, data): if os.name == 'posix': serialport.writeSomeData(data) elif os.name == 'java': serialport.writeSomeData(data) elif sys.platform == 'win32': serialport.write(data) def read_serial(serialclient, line): linelist = strlist(line) sys.stdout.write(line) def strlist(string): retval = [] for c in string: retval.append(c) return retval def get_base_text(): d = '''\ Hello Rpy

Hello World

''' resource = static.Data(d, 'text/html') return resource def main(): parser = optionParser() (options, args) = parser.parse_args() root = get_base_text() print "listening on " + options.tty serialport = SerialPort(Client(read_serial), options.tty, reactor, baudrate=9600) root.putChild('', AmbientResource(serialport)) ambientudpserver = AmbientUDPProtocol(serialport) reactor.listenUDP(int(options.port), ambientudpserver) reactor.listenTCP(int(options.port), server.Site(root)) reactor.run() def optionParser(): usage = "usage: %prog [options]\n\n" usage += "UDP server that listens for ambient orb commands" parser = OptionParser(usage=usage) parser.add_option("-p", "--port", dest="port", default='9000', help="UDP port to listen on (Default 9000)") parser.add_option("-t", "--tty", dest="tty", default='/dev/ttyUSB0', help="Use passed in tty (not compatible with -n)") return parser if __name__ == '__main__': main()