#!/bin/sh

## MUPLEX - muplex.sh.
## NMEA multiplexer, in server mode, receive input datas from serial, USB
## or bluetooth, and mix all datas to pseudos serial ports and network (optional),
## or, in client mode, split NMEA datas from network to pseudos serial ports.
## In network mode, can replace GPSDd daemon and transfert AIS datas.  
## Powered with SoCat by Gerhard Reiger.
## Run on any Linux distro with socat and optionnaly zenity or yad (prefered)

## COPYRIGHT 2010-2016 Free Software Foundation, Inc. License GNU.
## GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
## This  is  free  software:  you  are free to use, change and redistribute it.
## There is NO WARRANTY, to the extent permitted by law.
## Navigation beta software, use it as your own risks !
## Frank Baudet <http://marinux.tuxfamily.org>.

## HISTORY
## 28/12/10 first public release > V0.1a
## 23/01/11 some comments and adjusts in config file > V0.1b
## 05/03/11 modif test running procedure (adding $socat_on for all users) and intermediate yad ending process
## 15/05/12 speed ouput default to 4800 (strict NMEA) and add comment for autostart
## 17/05/12 modify exit at first start
## 17/05/12 add timewait and verify devices input > V0.2
## 25/02/13 add client network mode, muplex.conf location as variable > V0.3
## 28/02/13 console mode and add yad for dialogs, notify auto mode
## 21/09/13 default waitime for devices ready to 20s
## 01/06/15 include AIS, default port 2947 (as GPSd) > V0.4

## TODO
## bi-directionnal option
## socat in UDP mode > tested, failure
## detect socat


if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
   help="\r
   *** MUPLEX V0.4 - NMEA MULTIPLEXER ***
   NMEA multiplexer, in server mode, receive input datas from serial, USB
   or bluetooth, and mix all datas to pseudos serial ports and network (optional),
   or, in client mode, split NMEA datas from network to pseudos serial ports.
   In network mode, can replace GPSDd daemon and transfert AIS datas.  
   Powered with SoCat by Gerhard Reiger.
   Run on any Linux distro with socat and optionnaly zenity or yad (prefered)
   GPL 3+, Navigation beta software, use it under your own responsability !
   Frank Baudet <http://marinux.tuxfamily.org>
   \r
   \r muplex.sh run as a flip flop:
   \r if you launch muplex.sh when it's running, it stop.
   \r At the next relaunch it restart and so one.
   \r See config in /etc/muplex.conf, created after the first launch.
   \r Add a command line \"muplex.sh &\" in your /etc/rc.local
   \r to run it automatically at start.
   \r\n"
   printf "$help"
   exit 0
fi   

clear
# debug
#set -x
# verbose socat
#dbg="-d"
conf_path=""
conf_file=""

# config for xinutop mode only
if [ -d /base/configs/etc ]; then
   conf_path="/base/configs/etc"
else
# for standard mode
   conf_path="/etc"
fi
# for all modes
conf_file="muplex.conf"

# look for dialogs
diag=""
parm=""
xcli=""
# look for dialog
if (which zenity >/dev/null); then
   diag="zenity"
   parm=""
fi
# yad prefered, more options, many less dependancies
if (which yad >/dev/null); then
   diag="yad"
   parm="--button=gtk-ok"
fi
# validate dialogs
if ([ -n "$diag" ] && [ -n "$DISPLAY" ]); then
   xcli="OK"
fi 

## create default file configuration at first start
if [ ! -e "${conf_path}/${conf_file}" ]; then
   conf='   ##
   ## MUPLEX - muplex.conf for muplex.sh
   ## NMEA multiplexer, in server mode, receive input datas from serial, USB
   ## or bluetooth, and mix all datas to pseudos serial ports and network (optional),
   ## or, in client mode, split NMEA datas from network to pseudos serial ports.
   ## In network mode, can replace GPSDd daemon and transfert AIS datas.  
   ## Powered with SoCat by Gerhard Reiger.
   ## Run on any Linux distro with socat and optionnaly zenity or yad (prefered)   
   ## GPL 3+, Navigation beta software, use it under your own responsability !
   ## Frank Baudet <http://marinux.tuxfamily.org>

   ## default values convenient for most of cases
   ## at minimum, adjust your input devices, serial and/or USB and/or
   ## bluetooth in server mode, and only server address in client mode


   #################################
   ## common server/client config ##
   #################################

   ## mode server or client
   mode=server
   ## number of virtual ports to create (named /ttyPS(x))
   nb_vports=3
   ## speed output (b4800, b9600, b19200, b38400)
   spd_out=b4800
   ## network port to bind, same as GPSd and may replace it for programs which can`t use
   ## virtual ports (ex: jPSKmail),but change this port if you have already a GPSd running.
   port_net=2947
   ## max waitime in seconds for devices or network ready at startup
   max_wait=20


   ###################
   ## server config ##
   ###################

   ## standard serial NMEA input parameters
   params_port="raw,clocal=1,cs8,cstopb=0,parenb=0,crtscts=0,echo=0,icanon"
   ## speed input (b4800, b9600, b19200, b38400)
   spd_in=b4800
   ## devices input: ttyS(x), ttyUSB(x), rfcomm(x); (x)=number of port (integrer value)
   ## type < ls /dev/ttyS* or ttyUSB* or rfcomm* > to examine your devices
   ## only a space between your multiple devices
   dev_in="ttyS0 rfcomm0 ttyUSB1"
   ## AIS port, from same type of device as above, leave blank if no AIS
   ais_in=
   ## multicast port for devices
   pcast_dev=23000
   ## multicast port for applications
   pcast_app=23001
   ## send datas over the network server (true / false)
   mode_net=true


   ###################
   ## client config ##
   ###################

   ## network address to get datas
   net_addr=192.168.127.1


   #################
   ## information ##
   #################

   ## After restart Muplex, you can verify in a console as it:
   ## test existence of virtual ports: < ls /dev/ttyPS* >
   ## test flow datas, replace (x) by the number of port created : < cat /dev/ttyPS(x) >
   ## test flow network datas in server mode on loopback: < cat </dev/tcp/127.0.0.1/2947 >
   ## test flow datas from network in client mode: < cat </dev/tcp/server_address/2947 >
   ## sometime, cat have some trouble using this mode of reading (fixme - line buffered ?)
   ## so use Putty for serial and network
   ## considering pseudos-virtual ports as normal serial port, ex: /dev/ttyPS1
   ## NMEA 0183 prococol: 4800bps, 8bits, no parity, 1 stop bit, no xon/xoff, no rts/cts
   ## NMEA 0183 HS: idem except 38400bps
   ## AIS: fixed speed to 38400bps
   ## To start automatically Muplex, add "/usr/local/sbin/muplex.sh &"
   ## at your /etc/rc.local
   ## '

   # create dir(s) for conf if necessary
   [ -d ${conf_path} ] || mkdir -p ${conf_path}
   # record conf
   printf "$conf" > "${conf_path}/${conf_file}"
   # advise user
   msg="
   ${conf_path}/${conf_file} created
   edit it manually as root or sudo to adjust
   your own settings and restart MUPLEX.
   "
   echo "$msg"
   [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --text="$msg"
   kill $$
fi


## starting Muplex
# flip flop: start at first launch, stop at second lauch and so one
# stop
if (pgrep "socat") ; then
   msg="
   Stopping MUPLEX, wait a little...
   "
   echo "$msg"
   [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --text="$msg"
   kill $$
fi

# start
if [ "$1" = "--notify" ] || [ "$1" = "-n" ]; then
   msg="
   Starting MUPLEX
   "
   echo "$msg"
   [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --timeout=3 --text="$msg"
fi


# load variables from conf
eval $(grep -v \# "${conf_path}/${conf_file}")

## server mode
if [ "$mode" = "server" ]; then
   # configure multicast, the crossroad and dispatcher for all datas
   ifconfig lo |
   if ! (grep -i -q multicast) ; then
      ifconfig lo multicast
   fi
   #
   route |
   if ! (grep -i -q 230.0.0.0) ; then
      route add -net 230.0.0.0 netmask 255.255.255.0 dev lo
   fi

   # verify and waiting for input devices get ready
   nb_dev=$(echo $dev_in | wc -w)
   i=0
   until [ "$i" = "$nb_dev" ]; do
      dev_nme=$(echo $dev_in | cut -d ' ' -f $(($i+1)))
      until [ -e /dev/$dev_nme ]; do
         sleep 1
         j=$(($j+1))
         if [ "$j" = "$max_wait" ]; then
            msg="
            MUPLEX ERROR
            Input devices not detected or bad configuration
            "
            echo "$msg"
            [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --text="$msg"
            kill $$
         fi
      done
      i=$(($i+1))
   done


   ## the magics  incantations
   # transfering NMEA datas devices to multicast
   nb_dev=$(echo $dev_in | wc -w)
   i=0
   until [ "$i" = "$nb_dev" ]; do
      dev_nme=$(echo $dev_in | cut -d ' ' -f $(($i+1)))
      socat $dbg -u FILE:/dev/$dev_nme,$spd_in,$params_port \
         UDP4-DATAGRAM:230.0.0.1:$pcast_app,bind=:$pcast_dev,reuseaddr,ip-add-membership=230.0.0.0:127.0.0.1 &
      i=$(($i+1))
   done
   #
   # create virtual ports and transfering
   i=0
   until [ "$i" = "$nb_vports" ]; do
      socat $dbg -u UDP4-DATAGRAM:230.0.0.0:$pcast_dev,bind=:$pcast_app,reuseaddr,ip-add-membership=230.0.0.1:127.0.0.1 \
         PTY,link=/dev/ttyPS$i,$spd_out,$params_port,group=dialout,mode=666 &
      i=$(($i+1))
   done
   #
   # AIS
   if [ -n "$ais_in" ]; then
      dev_nme="$ais_in"
      spd_in=b38400
      socat $dbg -u FILE:/dev/$dev_nme,$spd_in,$params_port \
         UDP4-DATAGRAM:230.0.0.1:$pcast_app,bind=:$pcast_dev,reuseaddr,ip-add-membership=230.0.0.0:127.0.0.1 &
   fi
   #
   # create network server
   if [ "$mode_net" = "true" ]; then
      socat $dbg -U TCP4-L:$port_net,reuseaddr,fork \
         UDP4-DATAGRAM:230.0.0.0:$pcast_dev,bind=:$pcast_app,reuseaddr,ip-add-membership=230.0.0.1:127.0.0.1
   fi


## mode client
elif [ "$mode" = "client" ]; then
   # wait time network established
   i=0
   j=1
   until [ "$j" = "0" ] || [ "$i" = "$max_wait" ]; do
      ping -c1 $net_addr >/dev/null 2>&1
      j=$?
      sleep 1
      i=$(($i+1))
   done
   if [ "$i" = "$max_wait" ]; then
      msg="
      MUPLEX ERROR
      server unreachable
      "
      echo "$msg"
      [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --text="$msg"
      kill $$
   fi


   # create virtual ports and transfering directy from network
   i=0
   until [ "$i" = "$nb_vports" ]; do
      socat $dbg -u TCP4:$net_addr:$port_net,fork \
         PTY,link=/dev/ttyPS$i,$spd_out,$params_port,group=dialout,mode=666 &
      i=$(($i+1))
   done


## error
else
   msg="
   MUPLEX ERROR mode
   in ${conf_path}/${conf_file}
   "
   echo "$msg"
   [ -n "$xcli" ] && ${diag} ${parm} --info --no-wrap --text="$msg"
   fi
   kill $$


fi

exit 0
