BOSWatch/boswatch.py

458 lines
15 KiB
Python
Raw Permalink Normal View History

2015-04-03 15:55:10 +02:00
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
"""
2015-05-28 13:51:20 +02:00
BOSWatch
2015-06-14 20:21:21 +02:00
Python script to receive and decode German BOS information with rtl_fm and multimon-NG
2015-05-28 13:51:20 +02:00
Through a simple plugin system, data can easily be transferred to other applications
2015-06-14 20:21:21 +02:00
For more information see the README.md
2015-05-28 13:51:20 +02:00
2015-05-31 12:40:43 +02:00
@author: Bastian Schroll
2015-07-02 09:02:49 +02:00
@author: Jens Herrmann
Thanks to smith_fms and McBo from Funkmeldesystem.de - Forum for Inspiration and Groundwork!
2015-05-28 13:51:20 +02:00
GitHUB: https://github.com/Schrolli91/BOSWatch
"""
2015-04-03 15:55:10 +02:00
2015-05-20 13:29:16 +02:00
import logging
import logging.handlers
2015-04-03 15:55:10 +02:00
import argparse # for parse the args
import ConfigParser # for parse the config file
import os # for log mkdir
import time # for time.sleep()
import subprocess # for starting rtl_fm and multimon-ng
## New for reloading csv
import pyinotify
import threading
2015-04-03 15:55:10 +02:00
from includes import globalVars # Global variables
2015-07-02 09:02:49 +02:00
from includes import MyTimedRotatingFileHandler # extension of TimedRotatingFileHandler
from includes import checkSubprocesses # check startup of the subprocesses
from includes.helper import configHandler
from includes.helper import freqConverter
2015-07-02 09:02:49 +02:00
#
# Check for exisiting config/config.ini-file
#
if not os.path.exists(os.path.dirname(os.path.abspath(__file__))+"/config/config.ini"):
print "ERROR: No config.ini found"
exit(1)
#
2015-06-05 10:19:49 +02:00
# ArgParser
2015-06-14 20:21:21 +02:00
# Have to be before main program
#
2015-07-02 09:02:49 +02:00
try:
# With -h or --help you get the Args help
2015-07-02 09:02:49 +02:00
parser = argparse.ArgumentParser(prog="boswatch.py",
description="BOSWatch is a Python Script to recive and decode german BOS information with rtl_fm and multimon-NG",
epilog="More options you can find in the extern config.ini file in the folder /config")
# parser.add_argument("-c", "--channel", help="BOS Channel you want to listen")
2016-12-22 22:44:56 +01:00
parser.add_argument("-f", "--freq", help="Frequency you want to listen to", required=True)
parser.add_argument("-d", "--device", help="Device you want to use (check with rtl_test)", type=int, default=0)
parser.add_argument("-e", "--error", help="Frequency-error of your device in PPM", default=0)
parser.add_argument("-a", "--demod", help="Demodulation functions", choices=['FMS', 'ZVEI', 'POC512', 'POC1200', 'POC2400'], required=True, nargs="+")
parser.add_argument("-s", "--squelch", help="Level of squelch", type=int, default=0)
2016-07-03 17:33:10 +02:00
parser.add_argument("-g", "--gain", help="Level of gain", type=int, default=100)
parser.add_argument("-u", "--usevarlog", help="Use '/var/log/boswatch' for logfiles instead of subdir 'log' in BOSWatch directory", action="store_true")
2016-12-22 22:44:56 +01:00
parser.add_argument("-v", "--verbose", help="Show more information", action="store_true")
parser.add_argument("-q", "--quiet", help="Show no information. Only logfiles", action="store_true")
2015-07-02 09:02:49 +02:00
# We need this argument for testing (skip instantiate of rtl-fm and multimon-ng):
parser.add_argument("-t", "--test", help=argparse.SUPPRESS, action="store_true")
2015-07-02 09:02:49 +02:00
args = parser.parse_args()
except SystemExit:
2015-06-05 10:19:49 +02:00
# -h or --help called, exit right now
exit(0)
except:
# we couldn't work without arguments -> exit
print "ERROR: cannot parsing the arguments"
exit(1)
#
# define a function for observing csv-files
#
def csv_watch(dir):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_MODIFY
t = threading.currentThread()
logging.debug("CSV-Watch-Dir: %s", dir)
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
try:
logging.debug("Reloading csv...")
if globalVars.config.getboolean("FMS","idDescribed") or globalVars.config.getboolean("ZVEI","idDescribed") or globalVars.config.getboolean("POC","idDescribed"):
from includes import descriptionList
descriptionList.loadDescriptionLists()
except:
# It's an error, but we could work without that stuff...
logging.error("cannot reload description lists")
logging.debug("cannot reload description lists", exc_info=True)
def process_IN_MODIFY(self, event):
try:
logging.debug("Reloading csv...")
if globalVars.config.getboolean("FMS","idDescribed") or globalVars.config.getboolean("ZVEI","idDescribed") or globalVars.config.getboolean("POC","idDescribed"):
from includes import descriptionList
descriptionList.loadDescriptionLists()
except:
# It's an error, but we could work without that stuff...
logging.error("cannot reload description lists")
logging.debug("cannot reload description lists", exc_info=True)
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(dir, mask, rec=True)
notifier.loop()
2015-07-02 09:02:49 +02:00
#
2015-06-14 20:21:21 +02:00
# Main program
#
2015-04-19 19:21:35 +02:00
try:
# initialization:
rtl_fm = None
multimon_ng = None
nmaHandler = None
try:
#
# Script-pathes
#
2016-10-03 12:02:18 +02:00
globalVars.script_path = os.path.dirname(os.path.abspath(__file__))
#
# Set log_path
#
if args.usevarlog:
2016-10-03 12:02:18 +02:00
globalVars.log_path = "/var/log/BOSWatch/"
else:
2016-10-03 12:02:18 +02:00
globalVars.log_path = globalVars.script_path+"/log/"
#
2015-06-14 20:21:21 +02:00
# If necessary create log-path
#
2016-10-03 12:02:18 +02:00
if not os.path.exists(globalVars.log_path):
os.mkdir(globalVars.log_path)
except:
# we couldn't work without logging -> exit
print "ERROR: cannot initialize paths"
exit(1)
#
# Create new myLogger...
#
try:
myLogger = logging.getLogger()
myLogger.setLevel(logging.DEBUG)
2015-06-14 20:21:21 +02:00
# set log string format
#formatter = logging.Formatter('%(asctime)s - %(module)-15s %(funcName)-15s [%(levelname)-8s] %(message)s', '%d.%m.%Y %H:%M:%S')
formatter = logging.Formatter('%(asctime)s - %(module)-15s [%(levelname)-8s] %(message)s', '%d.%m.%Y %H:%M:%S')
2015-06-14 20:21:21 +02:00
# create a file logger
2016-10-03 12:02:18 +02:00
fh = MyTimedRotatingFileHandler.MyTimedRotatingFileHandler(globalVars.log_path+"boswatch.log", "midnight", interval=1, backupCount=999)
2015-06-14 20:21:21 +02:00
# Starts with log level >= Debug
# will be changed with config.ini-param later
2015-07-02 09:02:49 +02:00
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
myLogger.addHandler(fh)
2015-06-14 20:21:21 +02:00
# create a display logger
ch = logging.StreamHandler()
# log level for display: Default: info
if args.verbose:
2015-07-02 09:02:49 +02:00
ch.setLevel(logging.DEBUG)
elif args.quiet:
ch.setLevel(logging.CRITICAL)
else:
2015-07-02 09:02:49 +02:00
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
2015-07-02 09:02:49 +02:00
myLogger.addHandler(ch)
2015-05-15 20:54:42 +02:00
except:
# we couldn't work without logging -> exit
print "ERROR: cannot create logger"
exit(1)
2015-07-02 09:02:49 +02:00
2015-06-05 10:19:49 +02:00
# initialization of the logging was fine, continue...
try:
#
# Clear the logfiles
#
fh.doRollover()
2016-10-03 12:02:18 +02:00
rtl_log = open(globalVars.log_path+"rtl_fm.log", "w")
mon_log = open(globalVars.log_path+"multimon.log", "w")
rawMmOut = open(globalVars.log_path+"mm_raw.txt", "w")
rtl_log.write("")
mon_log.write("")
2016-07-12 16:46:30 +02:00
rawMmOut.write("")
rtl_log.close()
mon_log.close()
2016-07-12 16:46:30 +02:00
rawMmOut.close()
logging.debug("BOSWatch has started")
2015-07-02 09:02:49 +02:00
logging.debug("Logfiles cleared")
except:
# It's an error, but we could work without that stuff...
2015-07-02 09:02:49 +02:00
logging.error("cannot clear Logfiles")
logging.debug("cannot clear Logfiles", exc_info=True)
2015-07-02 09:02:49 +02:00
#
# start a new oberserver.thread
#
try:
thread = threading.Thread(target = csv_watch, args = (globalVars.script_path+'/csv/',))
thread.daemon = True # start it as daemon to avoid trouble when exiting Boswatch
thread.start()
logging.debug("Thread for csv-watch started")
except:
logging.error("Unable to start thread to observe csv-directory.", exc_info=True)
2015-06-29 23:32:55 +02:00
#
# For debug display/log args
#
2015-07-02 09:02:49 +02:00
try:
2016-10-03 12:02:18 +02:00
logging.debug("SW Version: %s",globalVars.versionNr)
logging.debug("Build Date: %s",globalVars.buildDate)
2015-06-30 12:38:52 +02:00
logging.debug("BOSWatch given arguments")
if args.test:
2015-06-30 12:38:52 +02:00
logging.debug(" - Test-Mode!")
2015-07-02 09:02:49 +02:00
logging.debug(" - Frequency: %s", freqConverter.freqToHz(args.freq))
logging.debug(" - Device: %s", args.device)
logging.debug(" - PPM Error: %s", args.error)
logging.debug(" - Squelch: %s", args.squelch)
2015-12-25 23:13:12 +01:00
logging.debug(" - Gain: %s", args.gain)
2015-07-02 09:02:49 +02:00
demodulation = ""
if "FMS" in args.demod:
demodulation += "-a FMSFSK "
logging.debug(" - Demod: FMS")
if "ZVEI" in args.demod:
2017-03-05 20:21:16 +01:00
demodulation += "-a ZVEI1 "
logging.debug(" - Demod: ZVEI")
if "POC512" in args.demod:
demodulation += "-a POCSAG512 "
logging.debug(" - Demod: POC512")
if "POC1200" in args.demod:
demodulation += "-a POCSAG1200 "
2015-07-02 09:02:49 +02:00
logging.debug(" - Demod: POC1200")
if "POC2400" in args.demod:
demodulation += "-a POCSAG2400 "
logging.debug(" - Demod: POC2400")
2015-07-02 09:02:49 +02:00
logging.debug(" - Use /var/log: %s", args.usevarlog)
logging.debug(" - Verbose Mode: %s", args.verbose)
logging.debug(" - Quiet Mode: %s", args.quiet)
if not args.quiet: #only if not quiet mode
from includes import shellHeader
2015-07-02 09:02:49 +02:00
shellHeader.printHeader(args)
if args.test:
logging.warning("!!! We are in Test-Mode !!!")
except:
# we couldn't work without config -> exit
logging.critical("cannot display/log args")
logging.debug("cannot display/log args", exc_info=True)
exit(1)
2015-06-29 23:32:55 +02:00
#
# Read config.ini
#
try:
logging.debug("reading config file")
2016-10-03 12:02:18 +02:00
globalVars.config = ConfigParser.ConfigParser()
globalVars.config.read(globalVars.script_path+"/config/config.ini")
# if given loglevel is debug:
2016-10-03 12:02:18 +02:00
if globalVars.config.getint("BOSWatch","loglevel") == 10:
configHandler.checkConfig("BOSWatch")
2017-09-24 12:01:15 +02:00
configHandler.checkConfig("multicastAlarm")
2017-09-20 06:31:47 +02:00
configHandler.checkConfig("Filters")
configHandler.checkConfig("FMS")
configHandler.checkConfig("ZVEI")
configHandler.checkConfig("POC")
except:
# we couldn't work without config -> exit
logging.critical("cannot read config file")
logging.debug("cannot read config file", exc_info=True)
exit(1)
2015-12-25 23:13:12 +01:00
#
# Set the loglevel and backupCount of the file handler
#
try:
2016-10-03 12:02:18 +02:00
logging.debug("set loglevel of fileHandler to: %s",globalVars.config.getint("BOSWatch","loglevel"))
fh.setLevel(globalVars.config.getint("BOSWatch","loglevel"))
logging.debug("set backupCount of fileHandler to: %s", globalVars.config.getint("BOSWatch","backupCount"))
fh.setBackupCount(globalVars.config.getint("BOSWatch","backupCount"))
except:
# It's an error, but we could work without that stuff...
logging.error("cannot set loglevel of fileHandler")
logging.debug("cannot set loglevel of fileHandler", exc_info=True)
2015-07-02 09:02:49 +02:00
# initialization was fine, continue with main program...
2015-12-25 23:13:12 +01:00
#
# Load plugins
#
2015-07-02 09:02:49 +02:00
try:
2015-06-29 23:32:55 +02:00
from includes import pluginLoader
pluginLoader.loadPlugins()
except:
# we couldn't work without plugins -> exit
2015-06-29 23:32:55 +02:00
logging.critical("cannot load Plugins")
logging.debug("cannot load Plugins", exc_info=True)
exit(1)
2015-07-02 09:02:49 +02:00
#
# Load filters
#
2015-07-02 09:02:49 +02:00
try:
2016-10-03 12:02:18 +02:00
if globalVars.config.getboolean("BOSWatch","useRegExFilter"):
from includes import regexFilter
regexFilter.loadFilters()
2015-06-29 23:32:55 +02:00
except:
# It's an error, but we could work without that stuff...
logging.error("cannot load filters")
logging.debug("cannot load filters", exc_info=True)
2015-07-02 09:02:49 +02:00
#
# Load description lists
#
2015-07-02 09:02:49 +02:00
try:
2016-10-03 12:02:18 +02:00
if globalVars.config.getboolean("FMS","idDescribed") or globalVars.config.getboolean("ZVEI","idDescribed") or globalVars.config.getboolean("POC","idDescribed"):
2015-06-29 23:32:55 +02:00
from includes import descriptionList
descriptionList.loadDescriptionLists()
except:
# It's an error, but we could work without that stuff...
logging.error("cannot load description lists")
logging.debug("cannot load description lists", exc_info=True)
2015-07-02 09:02:49 +02:00
2015-06-29 23:32:55 +02:00
#
# Start rtl_fm
#
2015-07-02 09:02:49 +02:00
try:
if not args.test:
logging.debug("starting rtl_fm")
command = ""
2016-10-03 12:02:18 +02:00
if globalVars.config.has_option("BOSWatch","rtl_path"):
command = globalVars.config.get("BOSWatch","rtl_path")
command = command+"rtl_fm -d "+str(args.device)+" -f "+str(freqConverter.freqToHz(args.freq))+" -M fm -p "+str(args.error)+" -E DC -F 0 -l "+str(args.squelch)+" -g "+str(args.gain)+" -s 22050"
rtl_fm = subprocess.Popen(command.split(),
#stdin=rtl_fm.stdout,
stdout=subprocess.PIPE,
2016-10-03 12:02:18 +02:00
stderr=open(globalVars.log_path+"rtl_fm.log","a"),
shell=False)
# rtl_fm doesn't self-destruct, when an error occurs
# wait a moment to give the subprocess a chance to write the logfile
time.sleep(3)
checkSubprocesses.checkRTL()
else:
logging.warning("!!! Test-Mode: rtl_fm not started !!!")
except:
# we couldn't work without rtl_fm -> exit
logging.critical("cannot start rtl_fm")
logging.debug("cannot start rtl_fm", exc_info=True)
exit(1)
2015-06-29 23:32:55 +02:00
#
# Start multimon
#
try:
if not args.test:
logging.debug("starting multimon-ng")
command = ""
2016-10-03 12:02:18 +02:00
if globalVars.config.has_option("BOSWatch","multimon_path"):
command = globalVars.config.get("BOSWatch","multimon_path")
command = command+"multimon-ng "+str(demodulation)+" -f alpha -t raw /dev/stdin - "
multimon_ng = subprocess.Popen(command.split(),
stdin=rtl_fm.stdout,
stdout=subprocess.PIPE,
2016-10-03 12:02:18 +02:00
stderr=open(globalVars.log_path+"multimon.log","a"),
2015-07-02 09:02:49 +02:00
shell=False)
# multimon-ng doesn't self-destruct, when an error occurs
# wait a moment to give the subprocess a chance to write the logfile
time.sleep(3)
checkSubprocesses.checkMultimon()
else:
logging.warning("!!! Test-Mode: multimon-ng not started !!!")
except:
# we couldn't work without multimon-ng -> exit
logging.critical("cannot start multimon-ng")
logging.debug("cannot start multimon-ng", exc_info=True)
exit(1)
2015-06-29 23:32:55 +02:00
#
# Get decoded data from multimon-ng and call BOSWatch-decoder
#
if not args.test:
logging.debug("start decoding")
while True:
decoded = str(multimon_ng.stdout.readline()) #Get line data from multimon stdout
from includes import decoder
decoder.decode(freqConverter.freqToHz(args.freq), decoded)
# write multimon-ng raw data
2016-10-03 12:02:18 +02:00
if globalVars.config.getboolean("BOSWatch","writeMultimonRaw"):
try:
2016-10-03 12:02:18 +02:00
rawMmOut = open(globalVars.log_path+"mm_raw.txt", "a")
rawMmOut.write(decoded)
except:
logging.warning("cannot write raw multimon data")
finally:
rawMmOut.close()
else:
logging.debug("start testing")
2017-02-21 09:00:12 +01:00
testFile = open(globalVars.script_path+"/citest/testdata.txt","r")
for testData in testFile:
if (len(testData.rstrip(' \t\n\r')) > 1) and ("#" not in testData[0]):
logging.info("Testdata: %s", testData.rstrip(' \t\n\r'))
from includes import decoder
decoder.decode(freqConverter.freqToHz(args.freq), testData)
time.sleep(5)
logging.debug("test finished")
2015-07-02 09:02:49 +02:00
2015-04-03 15:55:10 +02:00
except KeyboardInterrupt:
2015-07-02 09:02:49 +02:00
logging.warning("Keyboard Interrupt")
except SystemExit:
# SystemExitException is thrown if daemon was terminated
logging.warning("SystemExit received")
# only exit to call finally-block
exit()
except:
2015-05-20 13:29:16 +02:00
logging.exception("unknown error")
finally:
2015-05-15 20:54:42 +02:00
try:
2015-05-21 11:32:21 +02:00
logging.debug("BOSWatch shuting down")
if multimon_ng and multimon_ng.pid:
2015-07-02 09:02:49 +02:00
logging.debug("terminate multimon-ng (%s)", multimon_ng.pid)
multimon_ng.terminate()
multimon_ng.wait()
logging.debug("multimon-ng terminated")
if rtl_fm and rtl_fm.pid:
2015-07-02 09:02:49 +02:00
logging.debug("terminate rtl_fm (%s)", rtl_fm.pid)
rtl_fm.terminate()
rtl_fm.wait()
2015-07-02 09:02:49 +02:00
logging.debug("rtl_fm terminated")
logging.debug("exiting BOSWatch")
2015-05-15 20:54:42 +02:00
except:
2015-07-02 09:02:49 +02:00
logging.warning("failed in clean-up routine")
logging.debug("failed in clean-up routine", exc_info=True)
2015-07-02 09:02:49 +02:00
finally:
# Close Logging
2015-07-02 09:02:49 +02:00
logging.debug("close Logging")
# Waiting for all Threads to write there logs
2016-10-03 12:02:18 +02:00
if globalVars.config.getboolean("BOSWatch","processAlarmAsync") == True:
logging.debug("waiting 3s for threads...")
time.sleep(3)
2015-05-26 07:57:34 +02:00
logging.info("BOSWatch exit()")
logging.shutdown()
if nmaHandler:
nmaHandler.close()
fh.close()
2015-12-25 23:13:12 +01:00
ch.close()