#!/usr/bin/perl -w

# tss_server (for the AO f/15 secondary).
# Tom Trebisky  2009
#
# IMPORTANT:
# the version we actually run lives in ao-server:/home/mmtao/ao/bin
# changes to any other version will lead to hassles and confusion.
# IMPORTANT - do not edit this on hacksaw!!
#
# this runs on ao-server, port 7003
#
# XXX - this has variables without the proper "tss_server"
# 	prefix, this should be changed, and dependent software
# 	and GUI's also brought into sync
#

use IO::Socket;

# use lib prepends to the @INC array.
use lib qw { /home/mmtao/ao/bin /mmt/miniserver };

# As of 10-22-2009, you cannot use MMTserver.pm
# (and you never could.  MMTserver requires DNS.pm, which was
# never installed on ao-server while running fc8)
# So, we run tss_server on hacksaw as of 10-22, which has
# several advantages.  tjt
use IO::AOserver;
#use IO::MMTserver;

# In demo mode, we are talking to the "tss_demo" server
# which is a limited TSS simulator (it returns binary
# status, but does not accept commands).
# Set this to 0 to run with the real TSS.
#my $demo = 1;
my $demo = 0;

# These switches are handy when everything goes to hell,
# but they can produce lots of output in the log files.
my $verbose = 0;
my $debug2 = 0;
my $debug_cmd = 1;
my $debug_data = 0;
my $client_debug = 1;

my $no_update = 0;

# Theory of Operation
# Tom Trebisky  11-3-2008
#
# The tss_server is an event drive protocol translation server
# for the TSS (Thin Shell Safety) subsystem of he AO f/15 secondary.
#
# The TSS itself interfaces via serial IO over fiber, which is handled
# by a copper to fiber media translator on one port of a cylcades terminal
# server, which makes the TSS accessible over the network, but with its own
# peculiar protocol and allowing only one connection at a time.
#
# The purpose of this server is twofold, first to allow multiple connections,
# second to perform protocol translation (it parses the tss response records
# and makes their content available as a set of variables via the usual
# MMT miniserver protocols to facilitate logging as well as a more sane
# control interface.  The server also supports a pass-through mode to allow
# legacy clients to be used with minimal changes.
#
# The AOserver module supports this event driven paradigm, and is used by
# the TSS server as follows:
#
# 1 - a timer (presently running at 1 Hz, sends commands requesting
#     telemetry responses (but does not process the responses).
#     This is supported by update_handler() in this module.
#
# 2 - when a full telemetry response has been collected in the client
#     input buffer, it is passed to client_handler(), which parses
#     the datastream and updates TSS status variables.
#
# - the above process will take place at all times when the tss-server
#   is running, and the TSS itself is powered on.
#
# 3 - in addition, the server supports (potentially multiple) connections from
#     the network.  These connections typically are either of one type or
#     another, namely ascii "miniserver" type connections, or binary "legacy"
#     connections.
#
# 4 - ascii remote connections act like typical MMT miniservers and support the
#     "all" and "get" commands.  These connection and responses are all handled as
#     part of the standard miniserver support code in the AOserver.pm module.
#     A variable "raw_data" provides the unparsed TSS response string.
#
# 5 - legacy "binary" connections support commands from the network that come
#     already wrapped in <STX>xxx<ETX> and are passed along as-is to the TSS.
#     An exception is the <STX>J000<ETX> command which merely requests data,
#     the response for this command comes from the most recently cached data
#     in the tss_server itself.
#
# 6 - special care needs to be taken with pass through binary commands to ensure
#     that they do not get a cached response.  Legacy software (adsec) typically
#     sends a command, and then checks the response (which is in the same format
#     as the J000 thing) to verify that the TSS did what it was told to do.
#
# Legacy code expects a response to each "action command" in the same format as
#  the J000 command provides.  In addition, the response is expected in many
#  cases to reflect the result the action just commanded.  For this reason, this
#  server must take care to provide up-to-date responses after action commands.

my $my_server_port = 7003;

print "TSS server is now serving on port $my_server_port\n";

my $update_interval = 1.0;

# Host name and port for the Cyclades connected to the TSS.
my $client_host = 'mmtts2';
my $client_port = 7003;

my $server;
my $client_handle = 0;
my $client_session = 0;
my $client_mode = "init";
my $active_wait = 0;
my $waiting_session = undef;

my $request;
my $request_string;

# Note: The current dm_status GUI (written in IDL)
# sends the J000 command to get a one-time multi line string.
# (this is the way things were done prior to this server).

# The J001 command gets a different (single line) string,
# over and over and over.
# This works for some things (like getting status), and we don't have to do
# anything but set the TSS up once and then just listen.
# It seems to talk at about a 4 Hz rate.
#
# HOWEVER!  This will not play nice with the way we support legacy software
# that sends commands and expects a J000 format string.  There might be
# a way to make this work, but it has never been tried or tested and is not
# likely to simply work as is by changing the following variable!!

#my $send_j001 = 1;
my $send_j001 = 0;

#my $expect_j001 = 1;
my $expect_j001 = 0;

if ( $send_j001 ) {
    $request = "J001";
} else {
    $request = "J000";
}

if ( $demo ) {
    #$request_string = "$request\n";
    $request_string = "\x02$request\x03";
    $client_host = 'cholla';
    $client_port = 7200;
} else {
    $request_string = "\x02$request\x03";
}

my $last_j000 = "stale";
my $stale_count = 1;

my $parse_format = "A6" x 20 . "A2" x 4 . "A13";
my $flags_format = "A1" x 13;

# names for the boolean flags.
my %onoff = ( "1" => "ON", "0" => "OFF" );
my %yesno = ( "1" => "Yes", "0" => "No" );
my %fiber = ( "1" => "Disconnected", "0" => "Connected" );
my %safe = ( "1" => "SAFE MODE", "0" => "OPERATING MODE (CAUTION)" );
#my %okerr = ( "1" => "OK", "0" => "Err" );

# itsy bitsy perl object to put on command queue
package Command;

sub new {
	my ( $class, $session, $command ) = @_;

	my $self = bless {
		session => $session,
		command => $command
	}, $class;
}

package main;

my @cmd_list = ();

# Here is a list of TSS variables in the order they are sent
# by the TSS, it is sometimes handy to see things in this order,
# rather than alphabetical or whatever, for humans anyway.
my @tss_keys = qw(
total_current
power_vccp
power_vssp
voltage_vccp
voltage_vssp
voltage_vcca
voltage_vssa
voltage_vccl
temp_crate1
temp_crate2
temp_crate3
temp_water_inlet
temp_water_outlet
temp_coldplate1
temp_coldplate2
temp_ambient
humidity_ambient
pressure_inlet
pressure_outlet
max_crate_temp
current_on_tss
max_hold1
max_hold2
max_hold3
overcurrent_vccp
overcurrent_vssp
overcurrent_push
overcurrent_pull

mystery

enable_coil_sw
enable_coil_hw
coil_status
tss_status
power_status
fiber_status
command
wrong
);

# There are some discrepancies in documentation.
# 1) I have a sheet labelled "Power Backplane diagnostic data transmission record"
#    it seems to almost document the J000 response,
#    but it has 19 instead of 20 thingies in the first group,
#    (it leaves off the last thing, current_on_tss),
#    It also lists only 8 flags, not 13.
# 2) I have the ao tss wicki, which only has 19 things in the first group
#    (it omits the humidity)
# 3) I have Vidhya's IDL script that parses the J000 line, and I have used
#    this as the authoritative reference.  It changes the order of two of
#    the flags as compared to the Wicki, in particular it skips over the flag
#    that I label as "mystery".  And it moves "command" to follow "status"
#    instead of following "fiber" as shown in the wicki.
#
# Also, I have been liberal in the assignment of on/ok/yes to the flags,
#    it might be best to just leave them as 0/1, but I would really like
#    to know what 0/1 mean at this level and assign words.
#
# In one aberrant mode, we now (7-6-2009) get the following messages;
#
#client_handler called with 17 bytes of data
#client_handler got data: ---binary junk---
#Weird cyclades junk rejected:  --same binary junk--
#Weird junk, what do I do ?????
#client_handler called with 3 bytes of data
#client_handler got data: *
#
#Weird cyclades junk rejected: *
#Weird junk, what do I do ?????
#client_handler called with 41 bytes of data
#client_handler got data: * * * ttyS3 is being used by (none) !!!
#
#Weird cyclades junk rejected: * * * ttyS3 is being used by (none) !!!
#Weird junk, what do I do ?????
#client_handler called with 3 bytes of data
#client_handler got data: *
#
#Weird cyclades junk rejected: *
#Weird junk, what do I do ?????

sub tss_parser {
    my ( $data ) = @_;

    # Just in case Cyclades is sending weird junk.
    # (as it sometimes does, and we don't want to try to parse it).
    if ( $data =~ /^\*/ ) {
        print "Weird cyclades junk rejected: $data";
        return 1;
    }

    # Just in case Cyclades is sending weird telnet junk.
    # (as it sometimes does, and we don't want to try to parse it).
    if ( $data =~ /^\xff\xfb/ ) {
        print "Weird cyclades telnet junk rejected!\n";
	dump_data ( "telnet junk", $data );
	print "\n";
        return 1;
    }

    print "TSS response processed:\n$data\n" if $debug2;

    if ( $expect_j001 ) {
    	return j001_parser ( $data );
    } else {
    	return j000_parser ( $data );
    }
}

sub dump_data {
	my ( $msg, $data ) = @_;

	print "tss_server dump: $msg\n";

	#my @chars = split //, $data;
	my @chars = unpack "C*", $data;

	foreach $ch ( @chars ) {
	    printf ( "<%02x>", $ch );
	}
}

# This only fixes the unprintables.
sub dump_data_r {
	my ( $msg, $data ) = @_;

	print "$msg\n";

	$data =~ s/\n/<NL>/g;
	$data =~ s/\x02/<STX>/g;
	$data =~ s/\x03/<ETX>/g;
	$data =~ s/\r/<CR>/g;
	$data =~ s/\x00/<NULL>/g;

	print $data;
	print "\n";
}

# This (J000) is the "normal" one time string way.
# It gets a 167 byte multiline reply as follows:
#  (and yes there is a blank line at the start and end)
#-----------------------------------------------------
#
#  3131
#     0
#     0
#     0
#  -504
#     0
#  -174
#     0
#  1949
#  1889
#  1854
#  1693
#  1713
#  2060
#  2038
#  1935
#   496
#  1040
#   671
#  4000
#12
#63
#34
# 8
#1011100011010
#
#-----------------------------------------------------

sub j000_parser {
    my ( $data ) = @_;

    my $nb = length($data);
    #print "Got J000 data: $nb\n";
    #dump_data ( "J000 data", $data );

    # normal count looks to be 167 bytes.
    # we essentially always get something weird on
    # the first read.
    if ( $nb != 167 and $verbose ) {
	print "Bizarre J000 read count (ignored): $nb\n";
	dump_data ( "Bizarre", $data );
	return 1;
    }

    # save multiline response (without STX/ETX)
    $last_j000 = $data;
    $stale_count = 0;

    @lines = split /\r/, $data;

    # always blank line at start
    shift @lines;

    # now 24 lines
    #foreach $l ( @lines ) {
    #	print "line: $l\n";
    #}

    # XXX - check line count

    #$$server_vars{raw_data} = pack $parse_format, @lines;
    $server->publish_verbatim ( "raw_data", pack $parse_format, @lines );

    load_vars ( @lines );

    return 0;
}

# This is the endless telemetry way.
# It gets a single line as follows (141 bytes):
#  3138     0     0     0  -509     0    88     0  1946  1886  1851  1693  1713  2048  2027  1923   502  1046   677  4000126334 81011100011010
#
sub j001_parser {
    my ( $data ) = @_;
    my @stuff;

    my $nb = length($data);
    #print "Got J001 data: $nb\n";
    #dump_data ( "J001 data", $data );

    #$$server_vars{raw_data} = $data;
    $server->publish_verbatim ( "raw_data", $data );

    # we get 37 items (0-36)
    @stuff = unpack $parse_format, $data;

    # XXX validate count XXX

    load_vars ( @stuff );
    return 0;
}


sub load_vars {
    my @stuff = @_;

    $server->publish_verbatim ( 'total_current' , $stuff[0] / 100.0 );
    $server->publish_verbatim ( 'power_vccp' , $stuff[1] / 100.0 );
    $server->publish_verbatim ( 'power_vssp' , $stuff[2] / 100.0 );
    $server->publish_verbatim ( 'voltage_vccp' , $stuff[3] / 1000.0 );
    $server->publish_verbatim ( 'voltage_vssp' , $stuff[4] / 1000.0 );
    $server->publish_verbatim ( 'voltage_vcca' , $stuff[5] / 1000.0 );
    $server->publish_verbatim ( 'voltage_vssa' , $stuff[6] / 1000.0 );
    $server->publish_verbatim ( 'voltage_vccl' , $stuff[7] / 1000.0 );
    $server->publish_verbatim ( 'temp_crate1' , $stuff[8] / 100.0 );
    $server->publish_verbatim ( 'temp_crate2' , $stuff[9] / 100.0 );
    $server->publish_verbatim ( 'temp_crate3' , $stuff[10] / 100.0 );
    $server->publish_verbatim ( 'temp_water_inlet' , $stuff[11] / 100.0 );
    $server->publish_verbatim ( 'temp_water_outlet' , $stuff[12] / 100.0 );
    $server->publish_verbatim ( 'temp_coldplate1' , $stuff[13] / 100.0 );
    $server->publish_verbatim ( 'temp_coldplate2' , $stuff[14] / 100.0 );
    $server->publish_verbatim ( 'temp_ambient' , $stuff[15] / 100.0 );
    $server->publish_verbatim ( 'humidity_ambient' , $stuff[16] / 10.0 );
    $server->publish_verbatim ( 'pressure_inlet' , $stuff[17] / 100.0 );
    $server->publish_verbatim ( 'pressure_outlet' , $stuff[18] / 100.0 );
    $server->publish_verbatim ( 'max_crate_temp' , $stuff[19] / 100.0 );

    $server->publish_verbatim ( 'current_on_tss' , $stuff[20] );
    $server->publish_verbatim ( 'max_hold1' , $stuff[21] );
    $server->publish_verbatim ( 'max_hold2' , $stuff[22] );	# delta current pull
    $server->publish_verbatim ( 'max_hold3' , $stuff[23] );	# delta current push

    # now the flags ... 13 of them (0 thru 12).
    $server->publish_verbatim ( 'flags' , $stuff[24] );
    @flags = unpack $flags_format, $stuff[24];

    $server->publish_verbatim ( 'overcurrent_vccp' , $yesno{$flags[0]} );
    $server->publish_verbatim ( 'overcurrent_vssp' , $yesno{$flags[1]} );

    $server->publish_verbatim ( 'overcurrent_push' , $flags[2] );
    $server->publish_verbatim ( 'overcurrent_pull' , $flags[3] );

    # dm_status.pro ignores this, so do we.
    $server->publish_verbatim ( 'mystery' , $flags[4] );

    $server->publish_verbatim ( 'enable_coil_sw' , $onoff{$flags[5]} );
    $server->publish_verbatim ( 'enable_coil_hw' , $onoff{$flags[6]} );
    $server->publish_verbatim ( 'coil_status' , $yesno{$flags[7]} );
    $server->publish_verbatim ( 'tss_status' , $safe{$flags[8]} );

    # These 3 were in the wrong order prior to 7-7-2009
    $server->publish_verbatim ( 'command' , $onoff{$flags[9]} );
    $server->publish_verbatim ( 'power_status' , $onoff{$flags[10]} );
    $server->publish_verbatim ( 'fiber_status' , $fiber{$flags[11]} );

    $server->publish_verbatim ( 'wrong' , $yesno{$flags[12]} );

    # raw flags without names applied.
    my $i;
    for ( $i = 0; $i < 13; $i++ ) {
        $server->publish_verbatim ( "flag$i" , $flags[$i] );
    }

#    foreach $key ( @tss_keys ) {
#    	$val = $server->examine_verbatim($key);
#	print "$key ==> $val\n";
#    }

}

my $read_count = 0;

# This is called when we get binary responses on the client handle.
# When called, the data already has the STX/ETX stripped.
#
# When some crazy nonsense is going on with the Cyclades, we get:
# (after many update requests)
# client_handler called with 17 bytes of data
#     (binary telnet stuff, see below)
# client_handler called with 3 bytes of data
# client_handler got data: *
# client_handler called with 41 bytes of data
# client_handler got data: * * * ttyS3 is being used by (NONE) !!!
# client_handler called with 3 bytes of data
# client_handler got data: *
# ---
# these cyclades strings end in \r\n
# (so the 3 byte string is just *\r\n)
#
# The telnet stuff looks like:
# FF FB 2c WILL (com port control)
# FF FB 03 WILL (suppress go ahead (no half duplex))
# FF FB 01 WILL (echo)
# FF FB 00 WILL (binary)
# FF FD 00 DO (echo)
# 0D 0A
# and that totals to 17 bytes

sub client_handler {
    my ( $data ) = @_;
    my $invalid;
    my $temp_session;

#    if ( length($data) == 17 ) {
#	print "client_handler, weird data length (17)\n";
#        dump_data ( "client_handler", $data );
#	print "\n";
#	return;
#    }

    print "client_handler called with " . length($data) . " bytes of data\n" if $client_debug;

    if ( $data =~ /^\xff/ ) {
        print "client_handler got binary data ... !!\n";
    } else {
	# even good data (167 byes long) has embedded \r and won't print nicely.
        # print "client_handler got data: " . $data . "\n";
	if ( $debug_data ) {
            dump_data_r ( "client_handler data", $data );
	}
    }

    # connection closed (eof) or error.
    # (socket close should already have been done)

    unless ( defined $data ) {
        print "Lost client connection!\n";
#       $server->client_close ( $client_session );
        undef $client_handle;
        return;
    }

    # !! process the data !!
    $invalid = tss_parser ( $data );
    $client_mode = "idle";

    if ( $invalid ) {
        print "Weird junk, what do I do ?????\n";
    } else {
        #$server_vars->{tss_server_update} = $server->mysql_datetime();
        #$server_vars->{tss_server_timestamp} = time();
	$server->publish( "update", $server->mysql_datetime() );
        $server->publish( "timestamp", time() );
    }

#    print "tjt - client handler\n";

    # respond to a waiting session
    if ( $waiting_session ) {
        # This little dance is to get around the situation (which happens)
        # where we write the response, and another command comes in before we
        # can clear the waiting session flag (which serves as a lock), so the
        # command ends up queued, which is OK (sort of) but confusing.
        $temp_session = $waiting_session;
	$waiting_session = undef;
	$temp_session->write ( "\x02$data\x03" );
	print "Legacy tss command, response sent:\n" if $verbose;
        dump_data_r ( "legacy response data", $data );
    }

    # a reply to the last command just arrived
    # so the client channel is idle, see if we have
    # any commands queued.

    my $qe = shift @cmd_list;
    if ( $qe ) {
	$waiting_session = $qe->{session};
	my $cmd = $qe->{command};
	$client_session->write ( "\x02$cmd\x03" );
	$client_mode = "active";
	$active_wait = 0;
	print "TSS command: $cmd, pulled from queue and sent\n" if $verbose;
    }
}

# This is just a fast track for a mildly revised dm_status GUI.

sub status_handler {
	my ( $session, $cmd ) = @_;

	return "\x02$last_j000\x03";
}

# This handles binary commands from network connections
# (i.e. legacy software).
# the STX/ETX have already been stripped from the command.
sub tss_handler {
	my ( $session, $cmd ) = @_;

	print "Legacy tss command: $cmd\n" if $debug_cmd;

# This is the common case where a legacy piece of
# software is making a status request.
# --
# while testing on 12-15-2008, we found that xadsec was doing things
# (in particular enabling the coil), but then checking too quickly
# for it to appear enabled and complaining, so we will just comment
# this out and relay the J000 commands when they come in like this,
# just like any other command.
# NOTE:  the dm_status_gui could just as well use cached data though.

#	if ( $cmd eq "J000" ) {
#	    $session->write ( "\x02$last_j000\x03" );
#	    return;
#	}

	# If client connection is idle, easy, just send the command.
	if ( $client_mode eq "idle" ) {
	    $client_session->write ( "\x02$cmd\x03" );
	    $client_mode = "active";
	    $active_wait = 0;
	    $waiting_session  = $session;
	    print "TSS command: $cmd, in the clear\n" if $verbose;
	    return;
	}

	# client connection is busy, queue the command.
	my $qe = new Command ( $session, $cmd );
	push @cmd_list, $qe;
	print "TSS command: $cmd, queued\n" if $verbose;
}

# This gets called on a timer event.
#  (typically every 1.0 seconds).
# If needed, it makes a connection to the client.
# NOTE: the tss is on the other side of a cyclades.
# This means that we are essentially always able to make
# a connection, regardless of whether the tss is on or not.
# If the tss is off, we simply will not get any response.
sub update_handler {

	#print "In update handler\n";

	# only for special debug and test
	return if $no_update and $client_mode ne "init";

	# client connection is busy.
	# We could queue the command, but if it
	# really is an active command, it will yield
	# a status anyway, and we can just skip the update,
	# so we do.

	if ( $client_mode eq "active" ) {
		$active_wait++;

		if ( $active_wait < 8 ) {
		    print "update_handler, skipping while busy\n";
		    return;
	        }

		# looks like we lost the connection.
	        $client_mode = "idle";
		$server->remove_client ( $client_session );
		$client_handle->close ();
		undef $client_handle;
		@cmd_list = ();

		# Avoid endlessly responding with stale data.
		if ( $stale_count++ > 10 ) {
		    $last_j000 = "stale";
		}
	}


	# Establish or Re-establish the connection.
	unless ( $client_handle ) {
            print "update_handler, making new connection\n";
	    $client_handle = IO::Socket::INET->new (  PeerAddr => $client_host,
                                        PeerPort => $client_port,
                                        Proto => "tcp",
                                        Timeout => 0.1);

	    unless ( $client_handle ) {
		print "No client\n" if $verbose;
	    }

	    return unless $client_handle;

	    $client_session = $server->add_client ( $client_handle, \&client_handler );
	    $client_mode = "init";
	}

	if ( $send_j001 and $client_mode eq "init" ) {
	    #print "SEND: $request_string\n";
	    print "Initial TSS request: $request\n" if $debug2;
	    $client_session->write ( $request_string );
	    $client_mode = "active";
	    $active_wait = 0;
	    return;
	}

	# Once upon a time, on the first call,
	# we did not yet have a client session
	# and needed to do a sys_write.

	my $now = `date`;
	chomp $now;
	print "update handler, sending request ($now)\n";
        print "Update TSS request: $request\n" if $debug2;

	if ( $client_session ) {
#	    print "session write: $request_string\n";
	    $client_session->write ( $request_string );
	} else {
#	    print "sys write: $request_string\n";
	    syswrite ( $client_handle, $request_string );
	}
	$client_mode = "active";
        $active_wait = 0;
	
	
	# 
	# Start of new code.  JDG  17-Dec-2009
	# This is a temporary fix of pushing data to dataserver2 until we can
	# get ao-server updated with a more recent Fedora version and can use
	# MMTserver.pm.
	if (1) {
	    my %stuff = %{ $server->{data} };
	    
	    # Compose JSON to send to dataserver2.
            if (%stuff) {
		my $json = "{";
		while (my ($key, $value) = each(%stuff)) {
		    # Don't send webserver-related data.
		    if ( $key !~ /^webserver_/ ) {
			# Add commas, as needed, in JSON string.
			if( $json !~ /{$/ ) { 
			    $json .= ",";
			}
			$json .= '"' . $key . '":"' .  $value . '"';
		    }
		}
		$json .= "}";
		
		# Send JSON if we have some data.
		if (length($json) > 5) {
		    my $cmds = "set json " . $json . "\n";
		    # Hard coding host and port info for now.
		    my $sock = IO::Socket::INET->new (  PeerAddr => '128.196.100.19',
							PeerPort => 8660,
							Proto => "tcp",
							Timeout => 0.5);
		    if ($sock) {
			if (1) {
			    print $cmds;
			}
			$sock->send($cmds);
			$sock->close();
		    }
 		}
	    }
	}
	# End of new code.  JDG  17-Dec-2009
	#
	
}

# turn on autoflush so log messages don't get buffered.
select (( select (STDOUT), $|=1)[0]);

my $now = `date`;
chomp $now;
print "TSS server starting ($now)!!\n";
$server = AOserver->new ( "tss_server" );

# Two different ways to use a hash reference.
#$server_vars = $server->get_datx_ref ();
#$$server_vars{junk} = "ham";
#$server_vars->{trash} = "salad";

#$server->debug ( 1 );
#$server->server_debug ( 1 );

$server->set_port ( $my_server_port );
$server->tssmode ( 1 );

# Add hook to just give cached status
$server->add_hook( "J000", \&status_handler );

# Add hook to relay to legacy software,
# this will get anything wrapped in STX/ETX
$server->add_tss_hook( \&tss_handler );

$server->add_update_hook ( \&update_handler, $update_interval );

print " .. starting tss server on port $my_server_port\n";
$server->server_init ();

$server->publish( "update", "0" );
$server->publish( "timestamp", time() );

#print " .. enter main loop\n";
$server->main_loop ();

# THE END
