"""mems.instrument.server.timer

Provides a subprocess that handles timed events within the microscope server.
For now it just causes an image to be sent out periodically; this will
have to become more elaborate in future.
"""

# created 2001/10/16, AMK

__revision__ = "$Id: timer.py,v 1.6 2002/03/29 17:03:22 akuchlin Exp $"

import sys, time

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


def main():
    # Set the delay between sending out packets
    config = get_configuration()
    if config.get_debug():
        delay = 1.0
    else:
        delay = 1.0 / config.get_num_frames()
        
    # Wait a bit before getting the first image
    time.sleep(0.5)
    util.send_message('camera', 'snapshot')
    last_snapshot = time.time()
    
    while 1:
        if not util.has_input_waiting(sys.stdin, timeout=delay):
            # Take a new snapshot every 10 seconds, no matter what.
            if time.time() - last_snapshot > 10:
                util.send_message('camera', 'snapshot')
                last_snapshot = time.time()

            util.send_message('network_server', 'send_image')

        else:
            line = sys.stdin.readline()
            cmd, args = protocols.parse_message_line(line)
            if cmd == "quit":
                return
            
        
