#!/usr/bin/env python3
# # -*- coding: utf-8 -*-

# PiCQ aprs-send.py
# Dieses Skript dient dazu, den Standort des Gateways auf einem APRS-Server bekannt zu geben.
# 
# Die Idee dazu stammt aus einem konkreten Vorschlag von Patrick Wallraff. -Vielen Dank für deine Vorlage 
#
# 16.02.2019 by MiCKi9; M. Kirsch


import sys
import time
import os
import re
import socket
#import serial


global NummerGateway


NummerGateway = 2   #<==========


def LeseConfig():
    Datei = "/var/www/datenbank/data.gate%i"% (NummerGateway)
    config = open(Datei,"r")
    for line in config:
        if "AprsEnable" in line:
                Info = line.split("=")
                global enabled
                enabled = Info[1].replace("\n", "")
                
        if "AprsServ" in line:
                Info = line.split("=")
                Information = Info[1].replace("\n", "")
                AprsGeteilt = Information.split(" ")
                global AprsServ
                AprsServ = AprsGeteilt[0]
                global AprsPort
                AprsPort = AprsGeteilt[1]
                
        if "AprsName" in line:
                Info = line.split("=")
                global AprsName
                AprsName = Info[1].replace("\n", "")
                
        if "AprsPasswd" in line:
                Info = line.split("=")
                global AprsPasswd
                AprsPasswd = Info[1].replace("\n", "")
                
        if "AprsLong1" in line:
                Info = line.split("=")
                global AprsLong1
                AprsLong1 = Info[1].replace("\n", "")
                
        if "AprsLong2" in line:
                Info = line.split("=")
                global AprsLong2
                AprsLong2 = Info[1].replace("\n", "")
                
        if "AprsLong3" in line:
                Info = line.split("=")
                global AprsLong3
                AprsLong3 = Info[1].replace("\n", "")
                
        if "AprsLat1" in line:
                Info = line.split("=")
                global AprsLat1
                AprsLat1 = Info[1].replace("\n", "")
                
        if "AprsLat2" in line:
                Info = line.split("=")
                global AprsLat2
                AprsLat2 = Info[1].replace("\n", "")
                
        if "AprsLat3" in line:
                Info = line.split("=")
                global AprsLat3
                AprsLat3 = Info[1].replace("\n", "")
                
        if "BandChannel" in line:
                Info = line.split("=")
                global BandChannel
                BandChannel = Info[1].replace("\n", "")
                
        if "ManagerAddress" in line:
                Info = line.split("=")
                global ManagerAddress
                ManagerAddress = Info[1].replace("\n", "")
                
        if "Callsign" in line:
                Info = line.split("=")
                global Callsign
                Callsign = Info[1].replace("\n", "")
                
    config.close()
    
    
def Enabled():
    if "yes" in enabled:
        forgrt = "this"
    else:
        sys.exit(0)


def ReadConnection():
    global Connect
    global ConnectPort
    global ConnectNet
    global Typ
    global Symbol
    global PicqTyp
    
    Datei = "/mnt/RAMDisk/server%i.txt" % (NummerGateway)
    config = open(Datei,"r")
    for line in config:
        Lng = line
        Lng = Lng.split(":")
        if "offline" in line:
            print ("OFFLINE !!! \n")
            Connec = "Status unknow"
            ConnectPort = ""
            ConnectNet = ""
            Typ = "Gateway "
            Symbol = "-"
            PicqTyp = "temporarily out of service"
        elif "localhost" in line or "127.0.0.1" in line:
            Connect = ""
            ConnectPort = ""
            ConnectNet = ""
            if "Parrot" in line:
                Typ = "Repeater "
                Symbol = "-"
                PicqTyp = "Local repeater (Parrot)."
            if "Gateway" in line:
                Typ = "Gateway "
                Symbol = "-"
                PicqTyp = "local gateway between 2 frequencies."
        else:
            Connect = Lng[0]
            Connect = Connect.replace(" ", "")
            ConnectPort = Lng[1]
            ConnectNet = Lng[2]
            ConnectNet = ConnectNet.replace("\n", "")
            Typ = "FRN-Gateway "
            Symbol = "-"
            PicqTypEntwurf = "Server: ", str(Connect), ", Port: ", str(ConnectPort), ", Net: ", str(ConnectNet), ", under FRN-Masterserver: ", str(ManagerAddress)
            PicqTyp = "".join(PicqTypEntwurf)
            print ("***")
    config.close()
    
        
def MatchAPRS():
    KoordinatenEntwurf = str(AprsLong1), str(AprsLong2), ".", str(AprsLong3), "/", str(AprsLat1), str(AprsLat2), ".", str(AprsLat3)
    Koordinaten = "".join(KoordinatenEntwurf)
    
    Bake1Entwurf = "user ", str(AprsName), " pass ", str(AprsPasswd), "\n"
    global Bake1
    Bake1 = "".join(Bake1Entwurf)
    
    Bake2Entwurf = str(Callsign),">WIDE1-1,TCPIP*:!", str(Koordinaten), str(Symbol), " ", str(Typ), "on Freq.: ", BandChannel, " -- ", PicqTyp, "\n"
    global Bake2
    Bake2 = "".join(Bake2Entwurf)
    
    Bake3Entwurf = str(Callsign), ">WIDE1-1,TCPIP*:>", str(Typ), "with Raspberry Pi, http://www.picq.network\n"
    global Bake3
    Bake3 = "".join(Bake3Entwurf)
    

def SendBake():
    try:
        print ("Loging in ...")
        sock = socket.socket(socket.AF_INET,
                             socket.SOCK_STREAM)
        sock.connect((AprsServ, int(AprsPort)))
        data = sock.recv(1024).decode('utf-8')
        print (data)
  
        out = Bake1, Bake2, Bake3
        output = "".join(out)
        print ("Transmit informations as: ", output)
        sock.sendall(output.encode('UTF-8'))
        data = sock.recv(1024).decode('utf-8')
        print ("Server response: ")
        print (data)
        
        sock.close()
        print ("... done ...")

    except:
        print ("APRS-Server not found. Is the Internetconnection broken?")


############################################################
#                    == Hauptprogramm ==                   #
############################################################

while True:
    LeseConfig()
    Enabled()
    ReadConnection()
    MatchAPRS()
    SendBake()
    time.sleep(300)

sys.exit(0)
