#!/usr/bin/env python
"""
x10server.py - 2/27/2005

Copyright (c) 2005 Robert Stone
x10.py Copyright (c) 2004 Jimmy Retzlaff

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.

Overview:
    
Read commands from the serial port in argv[2] (or stdin) and interpret them as
commands for the X10 firecracker module which will attempt to drive a
firecracker in argv[1].

For more information on X10 and the "Firecracker" remote control see:
    
    http://www.x10.com/products/x10_cm17a.htm
    http://www.averdevelopment.com/python/x10.html
    http://www.geocities.com/ido_bartana/Firecracker_protocol.htm

See x10control.py for more information on how to set up your system. 

"""

import sys

try:
    import serial
except ImportError:
    print "You need pySerial to run this.\n"\
          "Get it from http://pyserial.sourceforge.net/"
    raise SystemExit

try:
    import x10
except ImportError:
    print "You need Jimmy Retzlaff's x10.py module to run this.\n"\
          "Get it from: http://www.averdevelopment.com/python/x10.html"
    raise SystemExit


class X10Firecracker(object):
    """
    This is a class wrapper around the x10 module with an additional method
    that reads from a file-like object and attempts to parse commands from it.
    Yea, I know I don't really need a class but I did it anyway.
    """
    def __init__(self, fcport, debug=True):
        """
        fcport = name of serial port that firecracker is in.
        """
        self.fcport = fcport
        self.debug = debug

    def sendCommands(self, commands):
        if self.debug:
            print >>sys.stderr, "sending: %s" % (commands.rstrip())
        x10.sendCommands(self.fcport, commands)

    def processCommandsFromFile(self, f):
        commands = f.readline()
        self.sendCommands(commands)

    def serialListen(self, portname):
        readport = serial.Serial(port=portname)
        while 1:
            self.processCommandsFromFile(readport)

def main(argv):
    if len(argv) <= 1:
        print "usage: x10server.py <FC device port> [command listen port]\n"\
            "    <FC device port> is the name of the serial device for\n"\
            "        for the port that your X10 firecracker is connected to.\n"\
            "    [command listen port] is a serial device to read x10.py\n"\
            "        commands from. If not specified, stdin will be used."
        raise SystemExit
    fcport = argv[1]
    fc = X10Firecracker(fcport)
    try:
        listenport = argv[2]
    except IndexError:
        while 1:
            fc.processCommandsFromFile(sys.stdin)
    else:
        fc.serialListen(listenport)
    
if __name__ == '__main__':
    main(sys.argv)