"""mems.instrument.hardware.fake_microscope

Code for a simulated microscope.
"""

# created 2001/09/24, AMK

__revision__ = "$Id: fake_microscope.py,v 1.6 2002/04/18 20:53:30 akuchlin Exp $"

import sys

from mems.instrument import protocols
from mems.instrument.server import util
from mems.instrument.server.configuration import get_configuration

class Microscope:
    "Placeholder class for storing the microscope's state"
    
    def __init__ (self):
        self.x = self.y = self.z = 0
        self.magnification = 5
        self.mode = protocols.MODE_BRIGHTFIELD
        self.aperture = 1
        self.light = 0

scope = Microscope()

def update_network():
    args = {'x':scope.x, 'y':scope.y, 'z':scope.z,
            'magnification': scope.magnification,
            'mode': scope.mode, 'aperture':scope.aperture,
            'light': scope.light,
            'x_scale': 90, 'y_scale':60,
            'angle':0,
        }
    msg = protocols.build_message_line('scope', **args)
    util.send_message('network_server', msg)

def do_move(x=None, y=None, z=None, angle=None):
    if x is not None:     scope.x = x
    if y is not None:     scope.y = y
    if z is not None:     scope.z = z
    if angle is not None: scope.angle = angle
    update_network()

def do_magnification(value):
    assert value in [5,10,20,50,100]
    scope.magnification = value
    update_network()

def do_mode(value):
    value = value.lower()
    assert value in [protocols.MODE_BRIGHTFIELD,
                     protocols.MODE_DARKFIELD,
                     protocols.MODE_ICR]
    scope.mode = value
    update_network()
    
def do_light(value):
    assert 0<= value <= 100
    scope.light = value
    update_network()
    
def do_aperture(value):
    assert 1 <= value <= 5
    scope.aperture = value
    update_network()
    
def do_autofocus(value):
    assert value in ['on', 'off']
    scope.autofocus = value
    update_network()
    
def main():
    config = get_configuration()
    while 1:
        if util.has_input_waiting(sys.stdin):
            line = sys.stdin.readline()
            if line == "": continue
            cmd, args = protocols.parse_message_line(line)

            if config.get_debug():
                print '%s: Received command %s %r' % (__name__, cmd, args)

            if cmd == 'quit':
                if config.get_debug():
                    print '%s: exiting' % __name__
                break
            elif cmd == "move":
                do_move(**args)
            elif cmd == "magnification":
                do_magnification(**args)
            elif cmd == "mode":
                do_mode(**args)
            elif cmd == "light":
                do_light(**args)
            elif cmd == "aperture":
                do_aperture(**args)
            elif cmd == "autofocus":
                do_autofocus(**args)
            else:
                raise RuntimeError, ("Unknown command %r args=%r" % (cmd, args))

    return 
