Пример #1
0
def run(typ,freq,data):
	"""
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
	try:
		if configHandler.checkConfig("template"): #read and debug the config (let empty if no config used)

			########## User Plugin CODE ##########
			if typ == "FMS":
				logging.warning("%s not supported", typ)
			elif typ == "ZVEI":
				logging.warning("%s not supported", typ)
			elif typ == "POC":
				logging.warning("%s not supported", typ)
			else:
				logging.warning("Invalid Typ: %s", typ)
			########## User Plugin CODE ##########

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #2
0
def run(typ,freq,data):
	"""
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("httpRequest"): #read and debug the config

			try:
				#
				# Create URL
				#
				if typ == "FMS":
					url = globalVars.config.get("httpRequest", "fms_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function
					url = url.replace(" ","%20") # replace space with %20 to be a vaild http request
				elif typ == "ZVEI":
					url = globalVars.config.get("httpRequest", "zvei_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function
					url = url.replace(" ","%20") # replace space with %20 to be a vaild http request
				elif typ == "POC":
					url = globalVars.config.get("httpRequest", "poc_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function
					url = url.replace(" ","%20") # replace space with %20 to be a vaild http request
				else:
					logging.warning("Invalid Typ: %s", typ)
					return

				#
				# HTTP-Request
				#
				logging.debug("send %s HTTP request", typ)

				try:
				    resp = urllib2.urlopen(url)
				except urllib2.HTTPError as e:
    					logging.warning("HTTP response: %s", e.code)
				except urllib2.URLError as e:
    					logging.warning("HTTP-specific error: %s", e.args)

			except:
				logging.error("cannot send HTTP request")
				logging.debug("cannot send HTTP request", exc_info=True)
				return
	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #3
0
def onLoad():
	"""
	While loading the plugins by pluginLoader.loadPlugins()
	this onLoad() routine is called one time for initialize the plugin
	@requires:  nothing
	@return:    nothing
	"""
	global BOTTokenAPIKey
	global BOTChatIDAPIKey
	global RICforLocationAPIKey
	global GoogleAPIKey

	configHandler.checkConfig("Telegram")
	BOTTokenAPIKey = globalVars.config.get("Telegram","BOTTokenAPIKey")
	BOTChatIDAPIKey = globalVars.config.get("Telegram","BOTChatIDAPIKey")
	RICforLocationAPIKey = globalVars.config.get("Telegram","RICforLocationAPIKey")
	GoogleAPIKey = globalVars.config.get("Telegram","GoogleAPIKey")

	return
Пример #4
0
def onLoad():
	"""
	While loading the plugins by pluginLoader.loadPlugins()
	this onLoad() routine is called one time for initialize the plugin
	@requires:  nothing
	@return:    nothing
	"""
	global BOTTokenAPIKey
	global BOTChatIDAPIKey
	global RICforLocationAPIKey
	global GoogleAPIKey

	configHandler.checkConfig("Telegram")
	BOTTokenAPIKey = globalVars.config.get("Telegram","BOTTokenAPIKey")
	BOTChatIDAPIKey = globalVars.config.get("Telegram","BOTChatIDAPIKey")
	RICforLocationAPIKey = globalVars.config.get("Telegram","RICforLocationAPIKey")
	GoogleAPIKey = globalVars.config.get("Telegram","GoogleAPIKey")

	return
Пример #5
0
def run(typ, freq, data):
    """
	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig(
                "gpiocontrol"
        ):  #read and debug the config (let empty if no config used)

            logging.debug(globalVars.config.get("gpiocontrol", "pin"))
            logging.debug(globalVars.config.get("gpiocontrol", "triggertime"))

            ########## User Plugin CODE ##########
            if typ == "FMS":
                th = threading.Thread(target=trigger)
                th.start()
                #logging.warning("%s not supported", typ)
            elif typ == "ZVEI":
                th = threading.Thread(target=trigger)
                th.start()
                #logging.warning("%s not supported", typ)
            elif typ == "POC":
                if globalVars.config.get("gpiocontrol", "activerics") == "":
                    th = threading.Thread(target=trigger)
                    th.start()
                else:
                    if data["ric"] in globalVars.config.get(
                            "gpiocontrol", "activerics"):
                        th = threading.Thread(target=trigger)
                        th.start()
                    else:
                        logging.info("Ric not in activerics")
            else:
                logging.warning("Invalid Typ: %s", typ)
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #6
0
def run(typ, freq, data):
    """
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig(
                "template"
        ):  #read and debug the config (let empty if no config used)

            logging.debug(globalVars.config.get("template", "test1"))
            logging.debug(globalVars.config.get("template", "test2"))

            ########## User Plugin CODE ##########
            if typ == "FMS":
                logging.warning("%s not supported", typ)
            elif typ == "ZVEI":
                logging.warning("%s not supported", typ)
            elif typ == "POC":
                logging.warning("%s not supported", typ)
            else:
                logging.warning("Invalid Typ: %s", typ)
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #7
0
def run(typ,freq,data):
	try:
		if configHandler.checkConfig("yowsup"):

			empfaenger = globalVars.config.get("yowsup", "empfaenger")
			sender = globalVars.config.get("yowsup", "sender")
			password = globalVars.config.get("yowsup", "password")
			devnull = open(os.devnull, "wb")

			if typ == "FMS":
					text = globalVars.config.get("yowsup","fms_message")
					text = wildcardHandler.replaceWildcards(text, data)
					cmd = 'yowsup-cli demos -l ' + sender + ':' + password + ' -s ' + empfaenger + ' "' + text + '" -M'
					subprocess.call(shlex.split(cmd), stdout=devnull, stderr=devnull)
					logging.debug("Message has been sent")
			elif typ == "ZVEI":
					text = globalVars.config.get("yowsup","zvei_message")
					text = wildcardHandler.replaceWildcards(text, data)
					cmd = 'yowsup-cli demos -l ' + sender + ':' + password + ' -s ' + empfaenger + ' "' + text + '" -M'
					subprocess.call(shlex.split(cmd), stdout=devnull, stderr=devnull)
					logging.debug("Message has been sent")
			elif typ == "POC":
				try:
					text = globalVars.config.get("yowsup","poc_message")
					text = wildcardHandler.replaceWildcards(text, data)
					cmd = 'yowsup-cli demos -l ' + sender + ':' + password + ' -s ' + empfaenger + ' "' + text + '" -M'
					subprocess.call(shlex.split(cmd), stdout=devnull, stderr=devnull)
					logging.debug("Message has been sent")
				except:
					logging.error("Message not send")
					logging.debug("Message not send")
					return
			else:
				logging.warning("Invalid Typ: %s", typ)

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #8
0
def run(typ, freq, data):
    """
	This function is the implementation of the BosMon-Plugin.
	It will send the data to an BosMon-Instance via http

	The configuration for the BosMon-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to BosMon
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to BosMon.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires:  BosMon-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("BosMon"):  #read and debug the config

            try:
                #
                # Initialize header an connect to BosMon-Server
                #
                headers = {}
                headers['Content-type'] = "application/x-www-form-urlencoded"
                headers['Accept'] = "text/plain"
                # if an user is set in the config.ini we will use HTTP-Authorization
                if globalVars.config.get("BosMon", "bosmon_user"):
                    # generate b64encoded autorization-token for HTTP-request
                    headers['Authorization'] = "Basic {0}".format(
                        base64.b64encode("{0}:{1}".format(
                            globalVars.config.get("BosMon", "bosmon_user"),
                            globalVars.config.get("BosMon",
                                                  "bosmon_password"))))
                logging.debug("connect to BosMon")
                # open connection to BosMon-Server
                httprequest = httplib.HTTPConnection(
                    globalVars.config.get("BosMon", "bosmon_server"),
                    globalVars.config.get("BosMon", "bosmon_port"),
                    timeout=5)
                # debug-level to shell (0=no debug|1)
                httprequest.set_debuglevel(0)
            except:
                logging.error("cannot connect to BosMon")
                logging.debug("cannot connect to BosMon", exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:
                #
                # Format given data-structure to compatible BosMon string
                #
                if typ == "FMS":
                    logging.debug("Start FMS to BosMon")
                    try:
                        # BosMon-Telegramin expected assembly group, direction and tsi in one field
                        # structure (binary as hex in base10):
                        #     Byte 1: assembly group; Byte 2: Direction; Byte 3+4: tactic short info
                        info = 0
                        # assembly group:
                        info = info + 1  # + b0001 (Assumption: is in every time 1 (no output from multimon-ng))
                        # direction:
                        if data["direction"] == "1":
                            info = info + 2  # + b0010
                        # tsi:
                        if "IV" in data["tsi"]:
                            info = info + 12  # + b1100
                        elif "III" in data["tsi"]:
                            info = info + 8  # + b1000
                        elif "II" in data["tsi"]:
                            info = info + 4  # + b0100
                        # "I" is nothing to do     + b0000

                        params = urllib.urlencode({
                            'type': 'fms',
                            'address': data["fms"],
                            'status': data["status"],
                            'info': info,
                            'flags': '0'
                        })
                        logging.debug(" - Params: %s", params)
                        # dispatch the BosMon-request
                        bosMonRequest(httprequest, params, headers)
                    except:
                        logging.error("FMS to BosMon failed")
                        logging.debug("FMS to BosMon failed", exc_info=True)
                        return

                elif typ == "ZVEI":
                    logging.debug("Start ZVEI to BosMon")
                    try:
                        params = urllib.urlencode({
                            'type': 'zvei',
                            'address': data["zvei"],
                            'flags': '0'
                        })
                        logging.debug(" - Params: %s", params)
                        # dispatch the BosMon-request
                        bosMonRequest(httprequest, params, headers)
                    except:
                        logging.error("ZVEI to BosMon failed")
                        logging.debug("ZVEI to BosMon failed", exc_info=True)
                        return

                elif typ == "POC":
                    logging.debug("Start POC to BosMon")
                    try:
                        # BosMon-Telegramin expected "a-d" as RIC-sub/function
                        params = urllib.urlencode({
                            'type':
                            'pocsag',
                            'address':
                            data["ric"],
                            'flags':
                            '0',
                            'function':
                            data["functionChar"],
                            'message':
                            data["msg"]
                        })
                        logging.debug(" - Params: %s", params)
                        # dispatch the BosMon-request
                        bosMonRequest(httprequest, params, headers)
                    except:
                        logging.error("POC to BosMon failed")
                        logging.debug("POC to BosMon failed", exc_info=True)
                        return

                else:
                    logging.warning("Invalid Typ: %s", typ)

            finally:
                logging.debug("close BosMon-Connection")
                try:
                    httprequest.close()
                except:
                    pass

    except:
        # something very mysterious
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #9
0
def run(typ,freq,data):
	"""
	This function is the implementation of the FFAgent-Plugin.
	It will send the data to FFAgent Webservice API

	Documentation here:
	http://free.ff-agent.com/app/public/docs/Dokumentation_WebAPI.pdf

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  FFAgent-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("FFAgent"): #read and debug the config

			try:
				#
				# FFAgent-Request
				#
				logging.debug("send FFAgent %s", typ)

				if globalVars.config.get("FFAgent", "live") == "1":
					url = "https://api.service.ff-agent.com/v1/WebService/triggerAlarm"
				else:
					url = "https://free.api.service.ff-agent.com/v1/WebService/triggerAlarm"

				serverCertFile = globalVars.config.get("FFAgent", "serverCertFile")
				clientCertFile = globalVars.config.get("FFAgent", "clientCertFile")
				clientCertPass = globalVars.config.get("FFAgent", "clientCertPass")
				webApiToken = globalVars.config.get("FFAgent", "webApiToken")
				webApiKey = globalVars.config.get("FFAgent", "webApiKey")
				accessToken = globalVars.config.get("FFAgent", "accessToken")
				selectiveCallCode = globalVars.config.get("FFAgent", "selectiveCallCode")

				# data["description"]
				msg_split = data["msg"].split(';')

				alarmData = {
					"alarmDate" : "",
					"keyword" : msg_split[0],
					"type" : "",
					"message" : data["msg"],
					"note" : msg_split[5],
					"operationResources" : "",
					"operationSchedule" : "",
					"object" : msg_split[2],
					"location" : msg_split[3] + " " + msg_split[4],
					"district" : msg_split[1],
					"lat" : "",
					"lng" : "",
					"easting" : "",
					"northing" : "",
					"alarmMessage" : ""
				}

				if globalVars.config.get("FFAgent", "test") == "1":
					alarmData = {
						"alarmDate" : "",
						"keyword" : "Test",
						"type" : "Test",
                                        	"message" : data["msg"],
                                	        "note" : msg_split[5],
                        	                "operationResources" : "",
                	                        "operationSchedule" : "",
        	                                "object" : msg_split[2],
	                                        "location" : msg_split[3] + " " + msg_split[4],
                                        	"district" : msg_split[1],
                                	        "lat" : "",
                        	                "lng" : "",
                	                        "easting" : "",
        	                                "northing" : "",
	                                        "alarmMessage" : ""
					}

				alarmData = json.dumps(alarmData)
				logging.debug(alarmData)

				alarmHeaders = {
					"Content-Type": "application/json",
					"webApiToken": webApiToken,
					"accessToken": accessToken,
					"selectiveCallCode": selectiveCallCode,
					"hmac": hmac.new(webApiKey, webApiToken + selectiveCallCode + accessToken + alarmData, digestmod=hashlib.sha256).hexdigest()
				}
				logging.debug(alarmHeaders)

				if globalVars.config.get("FFAgent", "live") == "1":
					r = requests.post(url, data=alarmData, headers=alarmHeaders, verify=serverCertFile, cert=(clientCertFile, clientCertPass))
				else:
					r = requests.post(url, data=alarmData, headers=alarmHeaders, verify=serverCertFile)

			except:
				logging.error("cannot send FFAgent request")
				logging.debug("cannot send FFAgent request", exc_info=True)
				return

			else:
				try:
					#
					# check FFAgent-Response
					#
					if r.status_code == requests.codes.ok: #Check FFAgent Response and print a Log or Error
						logging.debug("FFAgent response: %s" , str(r.status_code))
					else:
						logging.warning("FFAgent response: %s" , str(r.status_code))
				except: #otherwise
					logging.error("cannot get FFAgent response")
					logging.debug("cannot get FFAgent response", exc_info=True)
					return

			finally:
				logging.debug("close FFAgent-Connection")
				try:
					r.close()
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #10
0
def run(typ,freq,data):
	"""
	This function is the implementation of the MySQL-Plugin.
	It will store the data to an MySQL database

	The configuration for the MySQL-Connection is set in the config.ini.
	For DB- and tablestructure see boswatch.sql

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to BosMon
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to BosMon.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires: MySQL-Configuration has to be set in the config.ini
	@requires: Created Database/Tables, see boswatch.sql

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("MySQL"): #read and debug the config

			try:
				#
				# Connect to MySQL
				#
				logging.debug("connect to MySQL")
				connection = mysql.connector.connect(host = globalVars.config.get("MySQL","dbserver"), port = globalVars.config.get("MySQL","dbport"), user = globalVars.config.get("MySQL","dbuser"), passwd = globalVars.config.get("MySQL","dbpassword"), db = globalVars.config.get("MySQL","database"), charset = 'utf8mb4', collation = 'utf8mb4_general_ci')
				cursor = connection.cursor()
			except:
				logging.error("cannot connect to MySQL")
				logging.debug("cannot connect to MySQL", exc_info=True)
			else: # Without connection, plugin couldn't work
				try:
					#
					# Create and execute SQL-statement
					#
					logging.debug("Insert %s", typ)

					if typ == "FMS":
						cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableFMS")+" (`time`, `fms`, `status`, `direction`, `directionText`, `tsi`, `description`) VALUES (FROM_UNIXTIME(%s),%s,%s,%s,%s,%s,%s)", (data["timestamp"], data["fms"], data["status"], data["direction"], data["directionText"], data["tsi"], data["description"]))

					elif typ == "ZVEI":
						cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableZVEI")+" (`time`, `zvei`, `description`) VALUES (FROM_UNIXTIME(%s),%s,%s)", (data["timestamp"], data["zvei"], data["description"]))

					elif typ == "POC":
						if isSignal(data["ric"]):
							if globalVars.config.getint("POC","netIdent_history"):
								cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableSIG")+" (`time`,`ric`) VALUES (NOW(), '"+data["ric"]+"');")
							else:
								cursor.execute("UPDATE "+globalVars.config.get("MySQL","tableSIG")+" SET time = NOW() WHERE ric = '"+data["ric"]+"';")
								if cursor.rowcount == 0:
									cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableSIG")+" (`time`,`ric`) VALUES (NOW(), '"+data["ric"]+"');")
						else:
							cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tablePOC")+" (`time`, `ric`, `function`, `functionChar`, `msg`, `bitrate`, `description`) VALUES (FROM_UNIXTIME(%s),%s,%s,%s,%s,%s,%s)", (data["timestamp"], data["ric"], data["function"], data["functionChar"], data["msg"], data["bitrate"], data["description"]))

					else:
						logging.warning("Invalid Typ: %s", typ)
				except:
					logging.error("cannot Insert %s", typ)
					logging.debug("cannot Insert %s", typ, exc_info=True)
					return

			finally:
				logging.debug("close MySQL")
				try:
					cursor.close()
					connection.close() #Close connection in every case
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #11
0
def run(typ,freq,data):
	"""
	This function is the implementation of the jsonSocket-Plugin.
	It will send the data via UDP/TCP

	The configuration for the Connection is set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via UDP/TCP
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to UDP.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  jsonSocket-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("jsonSocket"): #read and debug the config

			try:
					#
				# initialize to socket-Server
				#
				# SOCK_DGRAM is the socket type to use for UDP sockets
				# SOCK_STREAM is the socket type to use for TCP sockets
				if globals.config.get("jsonSocket", "protocol") == "TCP":
					sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					sock.connect((globals.config.get("jsonSocket", "server"), globals.config.getint("jsonSocket", "port")))
				else:
					sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

			except:
				logging.error("cannot initialize %s-socket", globals.config.get("jsonSocket", "protocol"))
				logging.debug("cannot initialize %s-socket", globals.config.get("jsonSocket", "protocol"), exc_info=True)
				# Without connection, plugin couldn't work
				return

			else:
				# toDo is equals for all types, so only check if typ is supported
				supportedTypes = ["FMS", "ZVEI", "POC"]
				if typ in supportedTypes:
					logging.debug("Start %s to %s", typ, globals.config.get("jsonSocket", "protocol"))
					try:
						# dump data to json-string
						sendData = json.dumps(data)
						# send data
						sock.sendto(sendData, (globals.config.get("jsonSocket", "server"), globals.config.getint("jsonSocket", "port")))
					except:
						logging.error("%s to %s failed", typ, globals.config.get("jsonSocket", "protocol"))
						logging.debug("%s to %s failed", typ, globals.config.get("jsonSocket", "protocol"), exc_info=True)
						return

				else:
					logging.warning("Invalid Typ: %s", typ)

			finally:
				logging.debug("close %s-Connection", globals.config.get("jsonSocket", "protocol"))
				try:
					sock.close()
				except:
					pass

	except:
		# something very mysterious
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #12
0
def run(typ,freq,data):
	"""
	This function is the implementation of the Pushover-Plugin.
	It will send the data to Pushover API

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  Pushover-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("Pushover"): #read and debug the config

			try:
				#
				# Pushover-Request
				#
				logging.debug("send Pushover %s", typ)

			        if data["function"] == '1':
			                priority = globalVars.config.get("Pushover", "SubA")
			        elif data["function"] == '2':
			                priority = globalVars.config.get("Pushover", "SubB")
			        elif data["function"] == '3':
			                priority = globalVars.config.get("Pushover", "SubC")
			        elif data["function"] == '4':
			                priority = globalVars.config.get("Pushover", "SubD")
			        else:
			                priority = 0

				conn = httplib.HTTPSConnection("api.pushover.net:443")
				conn.request("POST", "/1/messages.json",
				urllib.urlencode({
					"token": globalVars.config.get("Pushover", "api_key"),
					"user": globalVars.config.get("Pushover", "user_key"),
					"message": "<b>"+data["description"]+"</b><br>"+data["msg"].replace(";", "<br>"),
					"html": globalVars.config.get("Pushover", "html"),
					"title": globalVars.config.get("Pushover", "title"),
					"priority": priority,
					"retry": globalVars.config.get("Pushover", "retry"),
					"expire": globalVars.config.get("Pushover", "expire")
				}),{"Content-type": "application/x-www-form-urlencoded"})

			except:
				logging.error("cannot send Pushover request")
				logging.debug("cannot send Pushover request", exc_info=True)
				return

			else:
				try:
					#
					# check Pushover-Response
					#
					response = conn.getresponse()
					if str(response.status) == "200": #Check Pushover Response and print a Log or Error
						logging.debug("Pushover response: %s - %s" , str(response.status), str(response.reason))
					else:
						logging.warning("Pushover response: %s - %s" , str(response.status), str(response.reason))
				except: #otherwise
					logging.error("cannot get Pushover response")
					logging.debug("cannot get Pushover response", exc_info=True)
					return

			finally:
				logging.debug("close Pushover-Connection")
				try:
					request.close()
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #13
0
def run(typ,freq,data):
	"""
	This function is the implementation of the Sms77-Plugin.
	It will send the data to Sms77 API

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  Sms77-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("Sms77"): #read and debug the config

			try:

				#
				# Sms77-Request
				#
				logging.debug("send Sms77 %s", typ)

				conn = httplib.HTTPSConnection("gateway.sms77.de:443")
				conn.request("POST", "",
				urllib.urlencode({
					"u": globalVars.config.get("Sms77", "user"),
					"p": globalVars.config.get("Sms77", "password"),
					"to": globalVars.config.get("Sms77", "to"),
					"from": globalVars.config.get("Sms77", "from"),
					"type": globalVars.config.get("Sms77", "type"),
					"text": data["description"]+"<br>"+data["msg"].replace(";", "<br>")
				}),{"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"})

			except:
				logging.error("cannot send SMS77 request")
				logging.debug("cannot send SMS77 request", exc_info=True)
				return

			else:
				try:
					#
					# check Sms77-Response
					#
					response = conn.getresponse()
					if str(response.status) == "200": #Check Sms77 Response and print a Log or Error
						logging.debug("SMS77 response: %s - %s" , str(response.status), str(response.reason))
					else:
						logging.warning("SMS77 response: %s - %s" , str(response.status), str(response.reason))
				except: #otherwise
					logging.error("cannot get SMS77 response")
					logging.debug("cannot get SMS77 response", exc_info=True)
					return

			finally:
				logging.debug("close Sms77-Connection")
				try:
					request.close()
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #14
0
def run(typ,freq,data):
	"""
	This function is the implementation of the BosMon-Plugin.
	It will send the data to an BosMon-Instance via http

	The configuration for the BosMon-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to BosMon
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to BosMon.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires:  BosMon-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("BosMon"): #read and debug the config

			try:
				#
				# Initialize header an connect to BosMon-Server
				#
				headers = {}
				headers['Content-type'] = "application/x-www-form-urlencoded"
				headers['Accept'] = "text/plain"
				# if an user is set in the config.ini we will use HTTP-Authorization
				if globalVars.config.get("BosMon", "bosmon_user"):
					# generate b64encoded autorization-token for HTTP-request
					headers['Authorization'] = "Basic {0}".format(base64.b64encode("{0}:{1}".format(globalVars.config.get("BosMon", "bosmon_user"), globalVars.config.get("BosMon", "bosmon_password"))))
				logging.debug("connect to BosMon")
				# open connection to BosMon-Server
				httprequest = httplib.HTTPConnection(globalVars.config.get("BosMon", "bosmon_server"), globalVars.config.get("BosMon", "bosmon_port"), timeout=5)
				# debug-level to shell (0=no debug|1)
				httprequest.set_debuglevel(0)
			except:
				logging.error("cannot connect to BosMon")
				logging.debug("cannot connect to BosMon", exc_info=True)
				# Without connection, plugin couldn't work
				return

			else:
				#
				# Format given data-structure to compatible BosMon string
				#
				if typ == "FMS":
					logging.debug("Start FMS to BosMon")
					try:
						# BosMon-Telegramin expected assembly group, direction and tsi in one field
						# structure (binary as hex in base10):
						#     Byte 1: assembly group; Byte 2: Direction; Byte 3+4: tactic short info
						info = 0
						# assembly group:
						info = info + 1          # + b0001 (Assumption: is in every time 1 (no output from multimon-ng))
						# direction:
						if data["direction"] == "1":
							info = info + 2      # + b0010
						# tsi:
						if "IV" in data["tsi"]:
							info = info + 12     # + b1100
						elif "III" in data["tsi"]:
							info = info + 8      # + b1000
						elif "II" in data["tsi"]:
							info = info + 4      # + b0100
						# "I" is nothing to do     + b0000

						params = urllib.urlencode({'type':'fms', 'address':data["fms"], 'status':data["status"], 'info':info, 'flags':'0'})
						logging.debug(" - Params: %s", params)
						# dispatch the BosMon-request
						bosMonRequest(httprequest, params, headers)
					except:
						logging.error("FMS to BosMon failed")
						logging.debug("FMS to BosMon failed", exc_info=True)
						return

				elif typ == "ZVEI":
					logging.debug("Start ZVEI to BosMon")
					try:
						params = urllib.urlencode({'type':'zvei', 'address':data["zvei"], 'flags':'0'})
						logging.debug(" - Params: %s", params)
						# dispatch the BosMon-request
						bosMonRequest(httprequest, params, headers)
					except:
						logging.error("ZVEI to BosMon failed")
						logging.debug("ZVEI to BosMon failed", exc_info=True)
						return

				elif typ == "POC":
					logging.debug("Start POC to BosMon")
					try:
						# BosMon-Telegramin expected "a-d" as RIC-sub/function
						params = urllib.urlencode({'type':'pocsag', 'address':data["ric"], 'flags':'0', 'function':data["functionChar"], 'message':data["msg"]})
						logging.debug(" - Params: %s", params)
						# dispatch the BosMon-request
						bosMonRequest(httprequest, params, headers)
					except:
						logging.error("POC to BosMon failed")
						logging.debug("POC to BosMon failed", exc_info=True)
						return

				else:
					logging.warning("Invalid Typ: %s", typ)

			finally:
				logging.debug("close BosMon-Connection")
				try:
					httprequest.close()
				except:
					pass

	except:
		# something very mysterious
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #15
0
def run(typ,freq,data):
	"""
	This function is the implementation of the MySQL-Plugin.
	It will store the data to an MySQL database

	The configuration for the MySQL-Connection is set in the config.ini.
	For DB- and tablestructure see boswatch.sql

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to BosMon
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to BosMon.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires: MySQL-Configuration has to be set in the config.ini
	@requires: Created Database/Tables, see boswatch.sql

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("MySQL"): #read and debug the config

			try:
					#
				# Connect to MySQL
				#
				logging.debug("connect to MySQL")
				connection = mysql.connector.connect(host = globalVars.config.get("MySQL","dbserver"), user = globalVars.config.get("MySQL","dbuser"), passwd = globalVars.config.get("MySQL","dbpassword"), db = globalVars.config.get("MySQL","database"), charset='utf8')
				cursor = connection.cursor()
			except:
				logging.error("cannot connect to MySQL")
				logging.debug("cannot connect to MySQL", exc_info=True)
			else: # Without connection, plugin couldn't work
				try:
					#
					# Create and execute SQL-statement
					#
					logging.debug("Insert %s", typ)

					if typ == "FMS":
						cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableFMS")+" (time, fms, status, direction, directionText, tsi, description) VALUES (FROM_UNIXTIME(%s),%s,%s,%s,%s,%s,%s)", (data["timestamp"], data["fms"], data["status"], data["direction"], data["directionText"], data["tsi"], data["description"]))

					elif typ == "ZVEI":
						cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableZVEI")+" (time, zvei, description) VALUES (FROM_UNIXTIME(%s),%s,%s)", (data["timestamp"], data["zvei"], data["description"]))

					elif typ == "POC":
						if isSignal(data["ric"]):
							cursor.execute("UPDATE "+globalVars.config.get("MySQL","tableSIG")+" SET time = NOW() WHERE ric = "+data["ric"])
							if cursor.rowcount == 0:
								cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tableSIG")+" (time,ric) VALUES (NOW(),"+data["ric"]+")")
						else:
						  cursor.execute("INSERT INTO "+globalVars.config.get("MySQL","tablePOC")+" (time, ric, function, functionChar, msg, bitrate, description) VALUES (FROM_UNIXTIME(%s),%s,%s,%s,%s,%s,%s)", (data["timestamp"], data["ric"], data["function"], data["functionChar"], data["msg"], data["bitrate"], data["description"]))

					else:
						logging.warning("Invalid Typ: %s", typ)
				except:
					logging.error("cannot Insert %s", typ)
					logging.debug("cannot Insert %s", typ, exc_info=True)
					return

			finally:
				logging.debug("close MySQL")
				try:
					cursor.close()
					connection.close() #Close connection in every case
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #16
0
def run(typ, freq, data):
    """
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig(
                "mqtt"
        ):  #read and debug the config (let empty if no config used)

            logging.debug(globalVars.config.get("mqtt", "brokeraddress"))
            logging.debug(globalVars.config.get("mqtt", "topic"))
            ########## User Plugin CODE ##########
            broker_address = globalVars.config.get("mqtt", "brokeraddress")
            topic = globalVars.config.get("mqtt", "topic")
            mqttClient = mqtt.Client()

            if typ == "FMS":
                x = {
                    "fms": data["fms"],
                    "status": data["status"],
                    "direction": data["direction"],
                    "directionText": data["directionText"],
                    "tsi": data["tsi"],
                    "description": data["description"],
                    "timestamp": timeHandler.curtime()
                }
            elif typ == "ZVEI":
                x = {
                    "zvei": data["zvei"],
                    "description": data["description"],
                    "timestamp": timeHandler.curtime()
                }
            elif typ == "POC":
                functionText = "%FUNCTEXT%"
                functionText = wildcardHandler.replaceWildcards(
                    functionText, data)
                x = {
                    "ric": data["ric"],
                    "function": data["function"],
                    "functionText": functionText,
                    "functionChar": data["functionChar"],
                    "msg": data["msg"],
                    "bitrate": data["bitrate"],
                    "description": data["description"],
                    "timestamp": timeHandler.curtime()
                }
            else:
                logging.warning("Invalid Typ: %s", typ)

            y = json.dumps(x)
            mqttClient.connect(broker_address)
            mqttClient.publish(topic, y)
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #17
0
def run(typ, freq, data):
    """
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig(
                "httpRequest"):  #read and debug the config

            try:
                #
                # Replace special characters in data Strings for URL
                #
                for key in data:
                    if isinstance(data[key], basestring):
                        data[key] = urllib.quote(data[key])
                #
                # Get URLs
                #
                if typ == "FMS":
                    urls = globalVars.config.get("httpRequest",
                                                 "fms_url").split(",")
                elif typ == "ZVEI":
                    urls = globalVars.config.get("httpRequest",
                                                 "zvei_url").split(",")
                elif typ == "POC":
                    urls = globalVars.config.get("httpRequest",
                                                 "poc_url").split(",")
                else:
                    logging.warning("Invalid Typ: %s", typ)
                    return

                #
                # replace wildcards
                #
                for (i, url) in enumerate(urls):
                    urls[i] = wildcardHandler.replaceWildcards(
                        urls[i].strip(), data)
                #
                # HTTP-Request
                #
                logging.debug("send %s HTTP requests", typ)

                for url in urls:
                    try:
                        urllib2.urlopen(url)
                    except urllib2.HTTPError as e:
                        logging.warning("HTTP response: %s", e.code)
                    except urllib2.URLError as e:
                        logging.warning("HTTP-specific error: %s", e.args)

            except:
                logging.error("cannot send HTTP request")
                logging.debug("cannot send HTTP request", exc_info=True)
                return
    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #18
0
def run(typ,freq,data):
	"""
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
	try:
		if configHandler.checkConfig("SMS"): #read and debug the config (let empty if no config used)
			if typ == "POC": # only available for POC!
				logging.debug("Plugin SMS enabled")

				# get number of cases and build a RIC-Array
				i = globalVars.config.get("SMS","quantity")
				aRic = []

				# build the array
				for x in range (1, int(i) + 1):
					# check the number of subrics
					subric = globalVars.config.get("SMS","subric" + str(x))
					if len(subric) > 1: # we have more than one subric
						subric_list = subric.split(",")
						for y in range (0, len(subric_list)):
							sric = subric_list[y].replace(' ','')
							full_ric = globalVars.config.get("SMS","ric" + str(x)) + sric
							case = x
							tmp = []
							tmp.append(full_ric)
							tmp.append(case)
							aRic.append(tmp)
					else:
						#get ric AND subric at once with ONE subric
						tmp = []
						tmp.append(globalVars.config.get("SMS","ric" + str(x)) + subric)
						tmp.append(x)
						aRic.append(tmp) # 2D-Array...

				# Debug: Display the multidimensional array aRic
				#logging.debug("aRic: %s", aRic)

				target = data["ric"] + data["functionChar"]

				#logging.debug("Searching for any occurences of %s", target)
				#if target in aRic:
				try:
					index = find(aRic, target)
				except:
					logging.error("RIC not found")

				logging.debug("Return from find: %s", index)
				if index != -1:
					case = aRic[index[0]][1]
					logging.debug("Enabling case %s", case)

					text = globalVars.config.get("SMS","text" + str(case))
					number = globalVars.config.get("SMS","phonenumber" + str(case))

					#just for debug
					logging.debug("Aktivierter Text: %s", text)
					logging.debug("Aktivierte Nummer: %s", number)

					# send sms
					try:
						sm = gammu.StateMachine()
						sm.ReadConfig()
						sm.Init()

						message = {
							'Text': text,
							'SMSC': {'Location': 1},
							'Number': number,
						}
						sm.SendSMS(message)
					except:
						logging.error("Failed to send SMS")
					else:
						logging.debug("Falsche SUB-RIC entdeckt - weiter gehts!")

			else:
				logging.warning("Invalid Typ: %s", typ)
			########## User Plugin CODE ##########

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #19
0
def run(typ, freq, data):
    """
    This function is the implementation of the Divera-Plugin.
    It will send the data to Divera API
    @type    typ:  string (FMS|ZVEI|POC)
    @param   typ:  Typ of the dataset
    @type    data: map of data (structure see readme.md in plugin folder)
    @param   data: Contains the parameter
    @type    freq: string
    @keyword freq: frequency of the SDR Stick
    @requires:  Divera-Configuration has to be set in the config.ini
    @return:    nothing
    """
    try:
        if configHandler.checkConfig("Divera"):  # read and debug the config

            if typ == "FMS":
                #
                # building message for FMS
                #
                text = globalVars.config.get("Divera", "fms_text")
                title = globalVars.config.get("Divera", "fms_title")
                priority = globalVars.config.get("Divera", "fms_prio")
                vehicle = globalVars.config.get("Divera", "fms_vehicle")

            elif typ == "ZVEI":
                #
                # building message for ZVEI
                #
                text = globalVars.config.get("Divera", "zvei_text")
                title = globalVars.config.get("Divera", "zvei_title")
                priority = globalVars.config.get("Divera", "zvei_prio")
                zvei_id = globalVars.config.get("Divera", "zvei_id")

            elif typ == "POC":
                if isSignal(data["ric"]):

                    logging.debug("RIC is net ident")
                    return
                else:
                    #
                    # building message for POC
                    #
                    if data["function"] == '1':
                        priority = globalVars.config.get("Divera", "SubA")
                    elif data["function"] == '2':
                        priority = globalVars.config.get("Divera", "SubB")
                    elif data["function"] == '3':
                        priority = globalVars.config.get("Divera", "SubC")
                    elif data["function"] == '4':
                        priority = globalVars.config.get("Divera", "SubD")
                    else:
                        priority = ''

                    text = globalVars.config.get("Divera", "poc_text")
                    title = globalVars.config.get("Divera", "poc_title")
                    ric = globalVars.config.get("Divera", "poc_ric")

            else:
                logging.warning("Invalid type: %s", typ)
                return

        try:
            #
            # Divera-Request
            #
            logging.debug("send Divera for %s", typ)

            # Replace wildcards & Logging data to send
            title = wildcardHandler.replaceWildcards(title, data)
            logging.debug("Title   : %s", title)
            text = wildcardHandler.replaceWildcards(text, data)
            logging.debug("Text    : %s", text)

            if typ == "FMS":
                vehicle = wildcardHandler.replaceWildcards(vehicle, data)
                logging.debug("Vehicle     : %s", vehicle)
            elif typ == "POC":
                ric = wildcardHandler.replaceWildcards(ric, data)
                logging.debug("RIC     : %s", ric)
            elif typ == "ZVEI":
                zvei_id = wildcardHandler.replaceWildcards(zvei_id, data)
                logging.debug("ZVEI_ID     : %s", zvei_id)
            else:
                logging.info("No wildcards to replace and no Typ selected!")

            # check priority value
            if (priority != 'false') and (priority != 'true'):
                logging.info(
                    "No Priority set for type '%s'! Skipping Divera-Alarm!",
                    typ)
                return

            # Check FMS
            if typ == "FMS":
                if (vehicle == ''):
                    logging.info("No Vehicle set!")

            # Check POC
            elif typ == "POC":
                if (ric == ''):
                    logging.info("No RIC set!")

            # Check ZVEI
            elif typ == "ZVEI":
                if (zvei_id == ''):
                    logging.info("No ZVEI_ID set!")

            else:
                logging.info("No ZVEI, FMS or POC alarm")

            # start connection to Divera
            if typ == "FMS":
                # start the connection FMS
                conn = httplib.HTTPSConnection("www.divera247.com:443")
                conn.request(
                    "GET", "/api/fms",
                    urllib.urlencode({
                        "accesskey":
                        globalVars.config.get("Divera", "accesskey"),
                        "vehicle_ric":
                        vehicle,
                        "status_id":
                        data["status"],
                        "status_note":
                        data["directionText"],
                        "title":
                        title,
                        "text":
                        text,
                        "priority":
                        priority,
                    }))

            elif typ == "ZVEI":
                # start connection ZVEI; zvei_id in Divera is alarm-RIC!
                conn = httplib.HTTPSConnection("www.divera247.com:443")
                conn.request(
                    "GET", "/api/alarm",
                    urllib.urlencode({
                        "accesskey":
                        globalVars.config.get("Divera", "accesskey"),
                        "title":
                        title,
                        "ric":
                        zvei_id,
                        "text":
                        text,
                        "priority":
                        priority,
                    }))

            elif typ == "POC":
                # start connection POC
                conn = httplib.HTTPSConnection("www.divera247.com:443")
                conn.request(
                    "GET", "/api/alarm",
                    urllib.urlencode({
                        "accesskey":
                        globalVars.config.get("Divera", "accesskey"),
                        "title":
                        title,
                        "ric":
                        ric,
                        "text":
                        text,
                        "priority":
                        priority,
                    }))

            else:
                loggin.debug("No Type is set", exc_info=True)
                return

        except:
            logging.error("cannot send Divera request")
            logging.debug("cannot send Divera request", exc_info=True)
            return

        try:
            #
            # check Divera-Response
            #
            response = conn.getresponse()
            if str(
                    response.status
            ) == "200":  # Check Divera Response and print a Log or Error
                logging.debug("Divera response: %s - %s", str(response.status),
                              str(response.reason))
            else:
                logging.warning("Divera response: %s - %s",
                                str(response.status), str(response.reason))
        except:  # otherwise
            logging.error("cannot get Divera response")
            logging.debug("cannot get Divera response", exc_info=True)
            return

        finally:
            logging.debug("close Divera-Connection")
            try:
                request.close()
            except:
                pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #20
0
def run(typ, freq, data):
    """
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig(
                "httpRequest"):  #read and debug the config

            try:
                #
                # Create URL
                #
                if typ == "FMS":
                    url = globals.config.get("httpRequest",
                                             "fms_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function
                elif typ == "ZVEI":
                    url = globals.config.get("httpRequest",
                                             "zvei_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function
                elif typ == "POC":
                    url = globals.config.get("httpRequest",
                                             "poc_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function

                else:
                    logging.warning("Invalid Typ: %s", typ)
                    return

                #
                # HTTP-Request
                #
                logging.debug("send %s HTTP request", typ)
                url = urlparse(url)  #split URL into path and querry
                httprequest = httplib.HTTPConnection(
                    url[2])  #connect to URL Path
                httprequest.request("GET", url[5])  #send URL Querry per GET

            except:
                logging.error("cannot send HTTP request")
                logging.debug("cannot send HTTP request", exc_info=True)
                return

            else:
                try:
                    #
                    # check HTTP-Response
                    #
                    httpresponse = httprequest.getresponse()
                    if str(
                            httpresponse.status
                    ) == "200":  #Check HTTP Response an print a Log or Error
                        logging.debug("HTTP response: %s - %s",
                                      str(httpresponse.status),
                                      str(httpresponse.reason))
                    else:
                        logging.warning("HTTP response: %s - %s",
                                        str(httpresponse.status),
                                        str(httpresponse.reason))
                except:  #otherwise
                    logging.error("cannot get HTTP response")
                    logging.debug("cannot get HTTP response", exc_info=True)
                    return

            finally:
                logging.debug("close HTTP-Connection")
                try:
                    httprequest.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #21
0
def run(typ,freq,data):
	"""
	This function is the implementation of the eMail-Plugin.
	It will send the data via eMail (SMTP)

	The configuration for the eMail-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via eMail
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to eMail.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  eMail-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("eMail"): #read and debug the config

			try:
				#
				# connect to SMTP-Server
				#
				try:
					server = smtplib.SMTP_SSL(globalVars.config.get("eMail", "smtp_server"), globalVars.config.get("eMail", "smtp_port"))
				except:
					server = smtplib.SMTP(globalVars.config.get("eMail", "smtp_server"), globalVars.config.get("eMail", "smtp_port"))
				# debug-level to shell (0=no debug|1)
				server.set_debuglevel(0)

				# if tls is enabled, starttls
				if globalVars.config.getboolean("eMail", "tls"):
					server.starttls()

				# if user is given, login
				if globalVars.config.get("eMail", "user"):
					server.login(globalVars.config.get("eMail", "user"), globalVars.config.get("eMail", "password"))

			except:
				logging.error("cannot connect to eMail")
				logging.debug("cannot connect to eMail", exc_info=True)
				# Without connection, plugin couldn't work
				return

			else:

				if typ == "FMS":
					logging.debug("Start FMS to eMail")
					try:
						# read subject-structure from config.ini
						subject = globalVars.config.get("eMail", "fms_subject")
						# replace wildcards with helper function
						subject = wildcardHandler.replaceWildcards(subject, data)

						# read mailtext-structure from config.ini
						mailtext = globalVars.config.get("eMail", "fms_message")
						# replace wildcards with helper function
						mailtext = wildcardHandler.replaceWildcards(mailtext, data)

						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				elif typ == "ZVEI":
					logging.debug("Start ZVEI to eMail")
					try:
						# read subject-structure from config.ini
						subject = globalVars.config.get("eMail", "zvei_subject")
						# replace wildcards with helper function
						subject = wildcardHandler.replaceWildcards(subject, data)

						# read mailtext-structure from config.ini
						mailtext = globalVars.config.get("eMail", "zvei_message")
						# replace wildcards with helper function
						mailtext = wildcardHandler.replaceWildcards(mailtext, data)

						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				elif typ == "POC":
					logging.debug("Start POC to eMail")
					try:
						# read subject-structure from config.ini
						subject = globalVars.config.get("eMail", "poc_subject")
						# replace wildcards with helper function
						subject = wildcardHandler.replaceWildcards(subject, data)

						# read mailtext-structure from config.ini
						mailtext = globalVars.config.get("eMail", "poc_message")
						# replace wildcards with helper function
						mailtext = wildcardHandler.replaceWildcards(mailtext, data)

						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				else:
					logging.warning("Invalid Type: %s", typ)

			finally:
				logging.debug("close eMail-Connection")
				try:
					server.quit()
				except:
					pass

	except:
		# something very mysterious
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #22
0
	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)

	#
	# Read config.ini
	#
	try:
		logging.debug("reading config file")
		globalVars.config = ConfigParser.ConfigParser()
		globalVars.config.read(globalVars.script_path+"/config/config.ini")
		# if given loglevel is debug:
		if globalVars.config.getint("BOSWatch","loglevel") == 10:
			configHandler.checkConfig("BOSWatch")
			configHandler.checkConfig("multicastAlarm")
			configHandler.checkConfig("Filters")
			configHandler.checkConfig("FMS")
			configHandler.checkConfig("ZVEI")
			configHandler.checkConfig("POC")
			configHandler.checkConfig("Plugins")
			configHandler.checkConfig("Filters")
			#NMAHandler is outputed below
	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)

Пример #23
0
def run(typ,freq,data):
	"""
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("httpRequest"): #read and debug the config

			try:
				#
				# Create URL
				#
				if typ == "FMS":
					url = globals.config.get("httpRequest", "fms_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function
				elif typ == "ZVEI":
					url = globals.config.get("httpRequest", "zvei_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function
				elif typ == "POC":
					url = globals.config.get("httpRequest", "poc_url") #Get URL
					url = wildcardHandler.replaceWildcards(url, data) # replace wildcards with helper function

				else:
					logging.warning("Invalid Typ: %s", typ)
					return


				#
				# HTTP-Request
				#
				logging.debug("send %s HTTP request", typ)
				url = urlparse(url) #split URL into path and querry
				httprequest = httplib.HTTPConnection(url[2]) #connect to URL Path
				httprequest.request("GET", url[5]) #send URL Querry per GET

			except:
				logging.error("cannot send HTTP request")
				logging.debug("cannot send HTTP request", exc_info=True)
				return

			else:
				try:
					#
					# check HTTP-Response
					#
					httpresponse = httprequest.getresponse()
					if str(httpresponse.status) == "200": #Check HTTP Response an print a Log or Error
						logging.debug("HTTP response: %s - %s" , str(httpresponse.status), str(httpresponse.reason))
					else:
						logging.warning("HTTP response: %s - %s" , str(httpresponse.status), str(httpresponse.reason))
				except: #otherwise
					logging.error("cannot get HTTP response")
					logging.debug("cannot get HTTP response", exc_info=True)
					return

			finally:
				logging.debug("close HTTP-Connection")
				try:
					httprequest.close()
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #24
0
def run(typ, freq, data):
    """
	This function is the implementation of the FFAgent-Plugin.
	It will send the data to FFAgent Webservice API

	Documentation here:
	http://free.ff-agent.com/app/public/docs/Dokumentation_WebAPI.pdf

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  FFAgent-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("FFAgent"):  #read and debug the config

            try:
                #
                # FFAgent-Request
                #
                logging.debug("send FFAgent %s", typ)

                if globalVars.config.get("FFAgent", "live") == "1":
                    url = "https://api.service.ff-agent.com/v1/WebService/triggerAlarm"
                else:
                    url = "https://free.api.service.ff-agent.com/v1/WebService/triggerAlarm"

                serverCertFile = globalVars.config.get("FFAgent",
                                                       "serverCertFile")
                clientCertFile = globalVars.config.get("FFAgent",
                                                       "clientCertFile")
                clientCertPass = globalVars.config.get("FFAgent",
                                                       "clientCertPass")
                webApiToken = globalVars.config.get("FFAgent", "webApiToken")
                webApiKey = globalVars.config.get("FFAgent", "webApiKey")
                accessToken = globalVars.config.get("FFAgent", "accessToken")
                selectiveCallCode = globalVars.config.get(
                    "FFAgent", "selectiveCallCode")

                # data["description"]
                msg_split = data["msg"].split(';')

                alarmData = {
                    "alarmDate": "",
                    "keyword": msg_split[0],
                    "type": "",
                    "message": data["msg"],
                    "note": msg_split[5],
                    "operationResources": "",
                    "operationSchedule": "",
                    "object": msg_split[2],
                    "location": msg_split[3] + " " + msg_split[4],
                    "district": msg_split[1],
                    "lat": "",
                    "lng": "",
                    "easting": "",
                    "northing": "",
                    "alarmMessage": ""
                }

                if globalVars.config.get("FFAgent", "test") == "1":
                    alarmData = {
                        "alarmDate": "",
                        "keyword": "Test",
                        "type": "Test",
                        "message": data["msg"],
                        "note": msg_split[5],
                        "operationResources": "",
                        "operationSchedule": "",
                        "object": msg_split[2],
                        "location": msg_split[3] + " " + msg_split[4],
                        "district": msg_split[1],
                        "lat": "",
                        "lng": "",
                        "easting": "",
                        "northing": "",
                        "alarmMessage": ""
                    }

                alarmData = json.dumps(alarmData)
                logging.debug(alarmData)

                alarmHeaders = {
                    "Content-Type":
                    "application/json",
                    "webApiToken":
                    webApiToken,
                    "accessToken":
                    accessToken,
                    "selectiveCallCode":
                    selectiveCallCode,
                    "hmac":
                    hmac.new(webApiKey,
                             webApiToken + selectiveCallCode + accessToken +
                             alarmData,
                             digestmod=hashlib.sha256).hexdigest()
                }
                logging.debug(alarmHeaders)

                if globalVars.config.get("FFAgent", "live") == "1":
                    r = requests.post(url,
                                      data=alarmData,
                                      headers=alarmHeaders,
                                      verify=serverCertFile,
                                      cert=(clientCertFile, clientCertPass))
                else:
                    r = requests.post(url,
                                      data=alarmData,
                                      headers=alarmHeaders,
                                      verify=serverCertFile)

            except:
                logging.error("cannot send FFAgent request")
                logging.debug("cannot send FFAgent request", exc_info=True)
                return

            else:
                try:
                    #
                    # check FFAgent-Response
                    #
                    if r.status_code == requests.codes.ok:  #Check FFAgent Response and print a Log or Error
                        logging.debug("FFAgent response: %s",
                                      str(r.status_code))
                    else:
                        logging.warning("FFAgent response: %s",
                                        str(r.status_code))
                except:  #otherwise
                    logging.error("cannot get FFAgent response")
                    logging.debug("cannot get FFAgent response", exc_info=True)
                    return

            finally:
                logging.debug("close FFAgent-Connection")
                try:
                    r.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #25
0
def run(typ, freq, data):
    """
	This function is the implementation of the Sms77-Plugin.
	It will send the data to Sms77 API

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  Sms77-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("Sms77"):  #read and debug the config

            try:

                #
                # Sms77-Request
                #
                logging.debug("send Sms77 %s", typ)

                conn = httplib.HTTPSConnection("gateway.sms77.de:443")
                conn.request(
                    "POST", "",
                    urllib.urlencode({
                        "u":
                        globalVars.config.get("Sms77", "user"),
                        "p":
                        globalVars.config.get("Sms77", "password"),
                        "to":
                        globalVars.config.get("Sms77", "to"),
                        "from":
                        globalVars.config.get("Sms77", "from"),
                        "type":
                        globalVars.config.get("Sms77", "type"),
                        "text":
                        data["description"] + "<br>" +
                        data["msg"].replace(";", "<br>")
                    }), {
                        "Content-type": "application/x-www-form-urlencoded",
                        "Accept": "text/plain"
                    })

            except:
                logging.error("cannot send SMS77 request")
                logging.debug("cannot send SMS77 request", exc_info=True)
                return

            else:
                try:
                    #
                    # check Sms77-Response
                    #
                    response = conn.getresponse()
                    if str(
                            response.status
                    ) == "200":  #Check Sms77 Response and print a Log or Error
                        logging.debug("SMS77 response: %s - %s",
                                      str(response.status),
                                      str(response.reason))
                    else:
                        logging.warning("SMS77 response: %s - %s",
                                        str(response.status),
                                        str(response.reason))
                except:  #otherwise
                    logging.error("cannot get SMS77 response")
                    logging.debug("cannot get SMS77 response", exc_info=True)
                    return

            finally:
                logging.debug("close Sms77-Connection")
                try:
                    request.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #26
0
def run(typ,freq,data):
	"""
	This function is the implementation of the eMail-Plugin.
	It will send the data via eMail (SMTP)

	The configuration for the eMail-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via eMail
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to eMail.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  eMail-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("eMail"): #read and debug the config

			try:
					#
				# connect to SMTP-Server
				#
				server = smtplib.SMTP(globals.config.get("eMail", "smtp_server"), globals.config.get("eMail", "smtp_port"))
				# debug-level to shell (0=no debug|1)
				server.set_debuglevel(0)

				# if tls is enabled, starttls
				if globals.config.get("eMail", "tls"):
					server.starttls()

				# if user is given, login
				if globals.config.get("eMail", "user"):
					server.login(globals.config.get("eMail", "user"), globals.config.get("eMail", "password"))

			except:
				logging.error("cannot connect to eMail")
				logging.debug("cannot connect to eMail", exc_info=True)
				# Without connection, plugin couldn't work
				return

			else:

				if typ == "FMS":
					logging.debug("Start FMS to eMail")
					try:
						# read subject-structure from config.ini
						subject = globals.config.get("eMail", "fms_subject")
						subject = subject.replace("%FMS%", data["fms"]).replace("%STATUS%", data["status"]) #replace Wildcards
						subject = subject.replace("%DIR%", data["direction"]).replace("%DIRT%", data["directionText"]) #replace Wildcards
						subject = subject.replace("%TSI%", data["tsi"]) #replace Wildcards
						subject = subject.replace("%DESCR%", data["description"]) # replace Wildcards
						subject = subject.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# read mailtext-structure from config.ini
						mailtext = globals.config.get("eMail", "fms_message")
						mailtext = mailtext.replace("%FMS%", data["fms"]).replace("%STATUS%", data["status"]) #replace Wildcards
						mailtext = mailtext.replace("%DIR%", data["direction"]).replace("%DIRT%", data["directionText"]) #replace Wildcards
						mailtext = mailtext.replace("%TSI%", data["tsi"]) #replace Wildcards
						mailtext = mailtext.replace("%DESCR%", data["description"]) # replace Wildcards
						mailtext = mailtext.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				elif typ == "ZVEI":
					logging.debug("Start ZVEI to eMail")
					try:
						# read subject-structure from config.ini
						subject = globals.config.get("eMail", "zvei_subject")
						subject = subject.replace("%ZVEI%", data["zvei"]) #replace Wildcards
						subject = subject.replace("%DESCR%", data["description"]) # replace Wildcards
						subject = subject.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# read mailtext-structure from config.ini
						mailtext = globals.config.get("eMail", "zvei_message")
						mailtext = mailtext.replace("%ZVEI%", data["zvei"]) #replace Wildcards
						mailtext = mailtext.replace("%DESCR%", data["description"]) # replace Wildcards
						mailtext = mailtext.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				elif typ == "POC":
					logging.debug("Start POC to eMail")
					try:
						# read subject-structure from config.ini
						subject = globals.config.get("eMail", "poc_subject")
						subject = subject.replace("%RIC%", data["ric"]) #replace Wildcards
						subject = subject.replace("%FUNC%", data["function"]).replace("%FUNCCHAR%", data["functionChar"]) #replace Wildcards
						subject = subject.replace("%MSG%", data["msg"]).replace("%BITRATE%", str(data["bitrate"])) #replace Wildcards
						subject = subject.replace("%DESCR%", data["description"]) # replace Wildcards
						subject = subject.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# read mailtext-structure from config.ini
						mailtext = globals.config.get("eMail", "poc_message")
						mailtext = mailtext.replace("%RIC%", data["ric"]) #replace Wildcards
						mailtext = mailtext.replace("%FUNC%", data["function"]).replace("%FUNCCHAR%", data["functionChar"]) #replace Wildcards
						mailtext = mailtext.replace("%MSG%", data["msg"]).replace("%BITRATE%", str(data["bitrate"])) #replace Wildcards
						mailtext = mailtext.replace("%DESCR%", data["description"]) # replace Wildcards
						mailtext = mailtext.replace("%TIME%", timeHandler.curtime("H:M:S")).replace("%DATE%", timeHandler.curtime("Y-m-d")) # replace Wildcards
						# send eMail
						doSendmail(server, subject, mailtext)
					except:
						logging.error("%s to eMail failed", typ)
						logging.debug("%s to eMail failed", typ, exc_info=True)
						return

				else:
					logging.warning("Invalid Typ: %s", typ)

			finally:
				logging.debug("close eMail-Connection")
				try:
					server.quit()
				except:
					pass

	except:
		# something very mysterious
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #27
0
def onLoad():
	"""
	While loading the plugins by pluginLoader.loadPlugins()
	this onLoad() routine is called one time for initialize the plugin

	@requires:  nothing

	@return:    nothing
	"""
	# local variables
	global application
	global APIKey
	global usecsv

	# load config:
	configHandler.checkConfig("notifyMyAndroid")
	application = stringConverter.convertToUnicode(globalVars.config.get("notifyMyAndroid","appName"))
	usecsv = globalVars.config.getboolean("notifyMyAndroid","usecsv")

	# if no csv should use, we take the APIKey directly
	if usecsv == False:
		APIKey = globalVars.config.get("notifyMyAndroid","APIKey")
	else:
		# import the csv-file
		try:
			logging.debug("-- loading nma.csv")
			with open(globalVars.script_path+'/csv/nma.csv') as csvfile:
				# DictReader expected structure described in first line of csv-file
				reader = csv.DictReader(csvfile)
				for row in reader:
					logging.debug(row)
					# only import rows with an supported types
					supportedTypes = ["FMS", "ZVEI", "POC"]
					if row['typ'] in supportedTypes:
						try:
							if "FMS" in row['typ']:
								# if len for id in mainList raise an KeyErrorException, we have to init it...
								try:
									if len(fmsAPIKeyList[row['id']]) > 0:
										pass
								except KeyError:
									fmsAPIKeyList[row['id']] = []
								# data structure: fmsAPIKeyList[fms][i] = (APIKey, priority)
								fmsAPIKeyList[row['id']].append((row['APIKey'], row['priority'], row['eventPrefix']))

							elif "ZVEI" in row['typ']:
								# if len for id in mainList raise an KeyErrorException, we have to init it...
								try:
									if len(zveiAPIKeyList[row['id']]) > 0:
										pass
								except KeyError:
									zveiAPIKeyList[row['id']] = []
								# data structure: zveiAPIKeyList[zvei][i] = (APIKey, priority)
								zveiAPIKeyList[row['id']].append((row['APIKey'], row['priority'], row['eventPrefix']))

							elif "POC" in row['typ']:
								# if len for id in mainList raise an KeyErrorException, we have to init it...
								try:
									if len(pocAPIKeyList[row['id']]) > 0:
										pass
								except KeyError:
									pocAPIKeyList[row['id']] = []
								# data structure: zveiAPIKeyList[ric][i] = (APIKey, priority)
								pocAPIKeyList[row['id']].append((row['APIKey'], row['priority'], row['eventPrefix']))

						except:
							# skip entry in case of an exception
							logging.debug("error in shifting...", exc_info=True)
					# if row['typ'] in supportedTypes
				# for row in reader:
			logging.debug("-- loading csv finished")
		except:
			logging.error("loading csvList for nma failed")
			logging.debug("loading csvList for nma failed", exc_info=True)
			raise
	# and if usecsv == True
	return
Пример #28
0
def run(typ, freq, data):
    """
	This function is the implementation of the firEmergency-Plugin.
	It will send the data to an firEmergency-Instance.

	The configuration for the firEmergency-Connection is set in the config.ini.

	@type    typ:  string (ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to firEmergency
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to firEmergency.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires:  firEmergency-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig(
                "firEmergency"):  #read and debug the config

            try:
                #
                # connect to firEmergency
                #
                firSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                firSocket.connect(
                    (globalVars.config.get("firEmergency", "firserver"),
                     globalVars.config.getint("firEmergency", "firport")))
            except:
                logging.error("cannot connect to firEmergency")
                logging.debug("cannot connect to firEmergency", exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:
                #
                # Format given data-structure to xml-string for firEmergency
                #
                if typ == "FMS":
                    logging.debug("FMS not supported by firEmgency")

                elif typ == "ZVEI":
                    logging.debug("ZVEI to firEmergency")
                    try:
                        description = stringConverter.convertToUTF8(
                            data["description"])
                        firXML = "<event>\n<address>" + data[
                            "zvei"] + "</address>\n<description>" + description + "</description>\n<message>" + data[
                                "zvei"] + "</message>\n</event>\n"
                        firSocket.send(firXML)
                    except:
                        logging.error("%s to firEmergency failed", typ)
                        logging.debug("%s to firEmergency failed",
                                      typ,
                                      exc_info=True)
                        # Without connection, plugin couldn't work
                        return

                elif typ == "POC":
                    logging.debug("POC to firEmergency")
                    try:
                        # !!! Subric+"XX" because of an Issuse in firEmergency !!!
                        description = stringConverter.convertToUTF8(
                            data["description"])
                        msg = stringConverter.convertToUTF8(data["msg"])
                        firXML = "<event>\n<address>" + data[
                            "ric"] + "</address>\n<status>" + data[
                                "function"] + "XX</status>\n<description>" + description + "</description>\n<message>" + msg + "</message>\n</event>\n"
                        firSocket.send(firXML)
                    except:
                        logging.error("%s to firEmergency failed", typ)
                        logging.debug("%s to firEmergency failed",
                                      typ,
                                      exc_info=True)
                        # Without connection, plugin couldn't work
                        return

                else:
                    logging.warning("Invalid Typ: %s", typ)

            finally:
                logging.debug("close firEmergency-Connection")
                try:
                    firSocket.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #29
0
def run(typ, freq, data):
    """
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig(
                "SMS"
        ):  #read and debug the config (let empty if no config used)
            if typ == "POC":  # only available for POC!
                logging.debug("Plugin SMS enabled")

                # get number of cases and build a RIC-Array
                i = globalVars.config.get("SMS", "quantity")
                aRic = []

                # build the array
                for x in range(1, int(i) + 1):
                    # check the number of subrics
                    subric = globalVars.config.get("SMS", "subric" + str(x))
                    if len(subric) > 1:  # we have more than one subric
                        subric_list = subric.split(",")
                        for y in range(0, len(subric_list)):
                            sric = subric_list[y].replace(' ', '')
                            full_ric = globalVars.config.get(
                                "SMS", "ric" + str(x)) + sric
                            case = x
                            tmp = []
                            tmp.append(full_ric)
                            tmp.append(case)
                            aRic.append(tmp)
                    else:
                        #get ric AND subric at once with ONE subric
                        tmp = []
                        tmp.append(
                            globalVars.config.get("SMS", "ric" + str(x)) +
                            subric)
                        tmp.append(x)
                        aRic.append(tmp)  # 2D-Array...

                # Debug: Display the multidimensional array aRic
                #logging.debug("aRic: %s", aRic)

                target = data["ric"] + data["functionChar"]

                #logging.debug("Searching for any occurences of %s", target)
                #if target in aRic:
                try:
                    index = find(aRic, target)
                except:
                    logging.error("RIC not found")

                logging.debug("Return from find: %s", index)
                if index != -1:
                    case = aRic[index[0]][1]
                    logging.debug("Enabling case %s", case)

                    text = globalVars.config.get("SMS", "text" + str(case))
                    number = globalVars.config.get("SMS",
                                                   "phonenumber" + str(case))

                    #just for debug
                    logging.debug("Aktivierter Text: %s", text)
                    logging.debug("Aktivierte Nummer: %s", number)

                    # send sms
                    try:
                        sm = gammu.StateMachine()
                        sm.ReadConfig()
                        sm.Init()

                        message = {
                            'Text': text,
                            'SMSC': {
                                'Location': 1
                            },
                            'Number': number,
                        }
                        sm.SendSMS(message)
                    except:
                        logging.error("Failed to send SMS")
                    else:
                        logging.debug(
                            "Falsche SUB-RIC entdeckt - weiter gehts!")

            else:
                logging.warning("Invalid Typ: %s", typ)
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #30
0
def run(typ, freq, data):
    """
    This function is the implementation of the Divera-Plugin.
    It will send the data to Divera API
    @type    typ:  string (FMS|ZVEI|POC)
    @param   typ:  Typ of the dataset
    @type    data: map of data (structure see readme.md in plugin folder)
    @param   data: Contains the parameter
    @type    freq: string
    @keyword freq: frequency of the SDR Stick
    @requires:  Divera-Configuration has to be set in the config.ini
    @return:    nothing
    """
    try:
        if configHandler.checkConfig("Divera"):  # read and debug the config

            if typ == "FMS":
                #
                # building message for FMS
                #
                text = globalVars.config.get("Divera", "fms_text")
                title = globalVars.config.get("Divera", "fms_title")
                priority = globalVars.config.get("Divera", "fms_prio")

            elif typ == "ZVEI":
                #
                # building message for ZVEI
                #
                text = globalVars.config.get("Divera", "zvei_text")
                title = globalVars.config.get("Divera", "zvei_title")
                priority = globalVars.config.get("Divera","zvei_std_prio")

            elif typ == "POC":
                #
                # building message for POC
                #
                if data["function"] == '1':
                    priority = globalVars.config.get("Divera", "SubA")
                elif data["function"] == '2':
                    priority = globalVars.config.get("Divera", "SubB")
                elif data["function"] == '3':
                    priority = globalVars.config.get("Divera", "SubC")
                elif data["function"] == '4':
                    priority = globalVars.config.get("Divera", "SubD")
                else:
                    priority = ''
                        
                text = globalVars.config.get("Divera", "poc_text")
                title = globalVars.config.get("Divera", "poc_title")

            else:
                logging.warning("Invalid type: %s", typ)
                return

        try:
            #
            # Divera-Request
            #
            logging.debug("send Divera for %s", typ)

            # replace the wildcards
            text = wildcardHandler.replaceWildcards(text, data)
            title = wildcardHandler.replaceWildcards(title, data)
            
            # Logging data to send
            logging.debug("Title   : %s", title)
            logging.debug("Text    : %s", text)
            logging.debug("Priority: %s", priority)
				
            # check priority value
            if (priority != 'false') and (priority != 'true'):
                logging.info("No Priority set for type '%s'! Skipping Divera-Alarm!", typ)
                return

            # start the connection
            conn = httplib.HTTPSConnection("www.divera247.com:443")
            conn.request("GET", "/api/alarm",
                        urllib.urlencode({
                            "accesskey": globalVars.config.get("Divera", "accesskey"),
                            "title": title,
                            "text": text,
                            "priority": priority,
                        }))

        except:
            logging.error("cannot send Divera request")
            logging.debug("cannot send Divera request", exc_info=True)
            return

        try:
            #
            # check Divera-Response
            #
            response = conn.getresponse()
            if str(response.status) == "200":  # Check Divera Response and print a Log or Error
                logging.debug("Divera response: %s - %s", str(response.status), str(response.reason))
            else:
                logging.warning("Divera response: %s - %s", str(response.status), str(response.reason))
        except:  # otherwise
            logging.error("cannot get Divera response")
            logging.debug("cannot get Divera response", exc_info=True)
            return

        finally:
            logging.debug("close Divera-Connection")
            try:
                request.close()
            except:
                pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #31
0
    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)

    #
    # Read config.ini
    #
    try:
        logging.debug("reading config file")
        globalVars.config = ConfigParser.ConfigParser()
        globalVars.config.read(globalVars.script_path + "/config/config.ini")
        # if given loglevel is debug:
        if globalVars.config.getint("BOSWatch", "loglevel") == 10:
            configHandler.checkConfig("BOSWatch")
            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)

    #
    # Set the loglevel and backupCount of the file handler
    #
    try:
        logging.debug("set loglevel of fileHandler to: %s",
                      globalVars.config.getint("BOSWatch", "loglevel"))
Пример #32
0
def run(typ, freq, data):
    """
	This function is the implementation of the jsonSocket-Plugin.
	It will send the data via UDP/TCP

	The configuration for the Connection is set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via UDP/TCP
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to UDP.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  jsonSocket-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("jsonSocket"):  #read and debug the config

            try:
                #
                # initialize to socket-Server
                #
                # SOCK_DGRAM is the socket type to use for UDP sockets
                # SOCK_STREAM is the socket type to use for TCP sockets
                if globals.config.get("jsonSocket", "protocol") == "TCP":
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect((globals.config.get("jsonSocket", "server"),
                                  globals.config.getint("jsonSocket", "port")))
                else:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            except:
                logging.error("cannot initialize %s-socket",
                              globals.config.get("jsonSocket", "protocol"))
                logging.debug("cannot initialize %s-socket",
                              globals.config.get("jsonSocket", "protocol"),
                              exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:
                # toDo is equals for all types, so only check if typ is supported
                supportedTypes = ["FMS", "ZVEI", "POC"]
                if typ in supportedTypes:
                    logging.debug("Start %s to %s", typ,
                                  globals.config.get("jsonSocket", "protocol"))
                    try:
                        # dump data to json-string
                        sendData = json.dumps(data)
                        # send data
                        sock.sendto(
                            sendData,
                            (globals.config.get("jsonSocket", "server"),
                             globals.config.getint("jsonSocket", "port")))
                    except:
                        logging.error(
                            "%s to %s failed", typ,
                            globals.config.get("jsonSocket", "protocol"))
                        logging.debug("%s to %s failed",
                                      typ,
                                      globals.config.get(
                                          "jsonSocket", "protocol"),
                                      exc_info=True)
                        return

                else:
                    logging.warning("Invalid Typ: %s", typ)

            finally:
                logging.debug("close %s-Connection",
                              globals.config.get("jsonSocket", "protocol"))
                try:
                    sock.close()
                except:
                    pass

    except:
        # something very mysterious
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #33
0
def onLoad():
    """
	While loading the plugins by pluginLoader.loadPlugins()
	this onLoad() routine is called one time for initialize the plugin

	@requires:  nothing

	@return:    nothing
	"""
    # local variables
    global application
    global APIKey
    global usecsv

    # load config:
    configHandler.checkConfig("notifyMyAndroid")
    application = stringConverter.convertToUnicode(
        globalVars.config.get("notifyMyAndroid", "appName"))
    usecsv = globalVars.config.getboolean("notifyMyAndroid", "usecsv")

    # if no csv should use, we take the APIKey directly
    if usecsv == False:
        APIKey = globalVars.config.get("notifyMyAndroid", "APIKey")
    else:
        # import the csv-file
        try:
            logging.debug("-- loading nma.csv")
            with open(globalVars.script_path + '/csv/nma.csv') as csvfile:
                # DictReader expected structure described in first line of csv-file
                reader = csv.DictReader(csvfile)
                for row in reader:
                    logging.debug(row)
                    # only import rows with an supported types
                    supportedTypes = ["FMS", "ZVEI", "POC"]
                    if row['typ'] in supportedTypes:
                        try:
                            if "FMS" in row['typ']:
                                # if len for id in mainList raise an KeyErrorException, we have to init it...
                                try:
                                    if len(fmsAPIKeyList[row['id']]) > 0:
                                        pass
                                except KeyError:
                                    fmsAPIKeyList[row['id']] = []
                                # data structure: fmsAPIKeyList[fms][i] = (APIKey, priority)
                                fmsAPIKeyList[row['id']].append(
                                    (row['APIKey'], row['priority'],
                                     row['eventPrefix']))

                            elif "ZVEI" in row['typ']:
                                # if len for id in mainList raise an KeyErrorException, we have to init it...
                                try:
                                    if len(zveiAPIKeyList[row['id']]) > 0:
                                        pass
                                except KeyError:
                                    zveiAPIKeyList[row['id']] = []
                                # data structure: zveiAPIKeyList[zvei][i] = (APIKey, priority)
                                zveiAPIKeyList[row['id']].append(
                                    (row['APIKey'], row['priority'],
                                     row['eventPrefix']))

                            elif "POC" in row['typ']:
                                # if len for id in mainList raise an KeyErrorException, we have to init it...
                                try:
                                    if len(pocAPIKeyList[row['id']]) > 0:
                                        pass
                                except KeyError:
                                    pocAPIKeyList[row['id']] = []
                                # data structure: zveiAPIKeyList[ric][i] = (APIKey, priority)
                                pocAPIKeyList[row['id']].append(
                                    (row['APIKey'], row['priority'],
                                     row['eventPrefix']))

                        except:
                            # skip entry in case of an exception
                            logging.debug("error in shifting...",
                                          exc_info=True)
                    # if row['typ'] in supportedTypes
                # for row in reader:
            logging.debug("-- loading csv finished")
        except:
            logging.error("loading csvList for nma failed")
            logging.debug("loading csvList for nma failed", exc_info=True)
            raise
    # and if usecsv == True
    return
Пример #34
0
def run(typ, freq, data):
    """
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig(
                "httpRequest"):  #read and debug the config

            try:
                #
                # Create URL
                #
                if typ == "FMS":
                    url = globalVars.config.get("httpRequest",
                                                "fms_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function
                    url = url.replace(
                        " ", "%20"
                    )  # replace space with %20 to be a vaild http request
                elif typ == "ZVEI":
                    url = globalVars.config.get("httpRequest",
                                                "zvei_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function
                    url = url.replace(
                        " ", "%20"
                    )  # replace space with %20 to be a vaild http request
                elif typ == "POC":
                    url = globalVars.config.get("httpRequest",
                                                "poc_url")  #Get URL
                    url = wildcardHandler.replaceWildcards(
                        url, data)  # replace wildcards with helper function
                    url = url.replace(
                        " ", "%20"
                    )  # replace space with %20 to be a vaild http request
                else:
                    logging.warning("Invalid Typ: %s", typ)
                    return

                #
                # HTTP-Request
                #
                logging.debug("send %s HTTP request", typ)

                try:
                    resp = urllib2.urlopen(url)
                except urllib2.HTTPError as e:
                    logging.warning("HTTP response: %s", e.code)
                except urllib2.URLError as e:
                    logging.warning("HTTP-specific error: %s", e.args)

            except:
                logging.error("cannot send HTTP request")
                logging.debug("cannot send HTTP request", exc_info=True)
                return
    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #35
0
def run(typ, freq, data):
    """
    This function is the implementation of the Pushover-Plugin.
    It will send the data to Pushover API

    @type    typ:  string (FMS|ZVEI|POC)
    @param   typ:  Typ of the dataset
    @type    data: map of data (structure see readme.md in plugin folder)
    @param   data: Contains the parameter
    @type    freq: string
    @keyword freq: frequency of the SDR Stick

    @requires:  Pushover-Configuration has to be set in the config.ini

    @return:    nothing
    """
    try:
        if configHandler.checkConfig("Pushover"):  # read and debug the config

            if typ == "FMS":
                #
                # building message for FMS
                #

                message = globalVars.config.get("Pushover", "fms_message")
                title = globalVars.config.get("Pushover", "fms_title")
                priority = globalVars.config.get("Pushover", "fms_prio")
                logging.debug("Sending message: %s", message)

            elif typ == "ZVEI":
                #
                # building message for ZVEI
                #
                if globalVars.config.get("Pushover", "zvei_sep_prio") == '1':
			if data["zvei"] in globalVars.config.get("Pushover", "zvei_prio2"):
				priority = '2'
			elif data["zvei"] in globalVars.config.get("Pushover","zvei_prio1"):
				priority = '1'
			elif data["zvei"] in globalVars.config.get("Pushover","zvei_prio0"):
				priority = '0'
			else:
				priority = '-1'
		else:
			priority = globalVars.config.get("Pushover","zvei_std_prio")

                message = globalVars.config.get("Pushover", "zvei_message")
                title = globalVars.config.get("Pushover", "zvei_title")
                logging.debug("Sending message: %s", message)

            elif typ == "POC":

                #
                # Pushover-Request
                #
                logging.debug("send Pushover for %s", typ)
                if globalVars.config.get("Pushover", "poc_spec_ric") == '0':
			if data["function"] == '1':
                        	priority = globalVars.config.get("Pushover", "SubA")
                    	elif data["function"] == '2':
                        	priority = globalVars.config.get("Pushover", "SubB")
                    	elif data["function"] == '3':
	                        priority = globalVars.config.get("Pushover", "SubC")
        	        elif data["function"] == '4':
                	        priority = globalVars.config.get("Pushover", "SubD")
                    	else:
                        	priority = 0
                else:
                    	if data["ric"] in globalVars.config.get("Pushover", "poc_prio2"):
                        	priority = 2
			elif data["ric"] in globalVars.config.get("Pushover","poc_prio1"):
			        priority = 1
                    	elif data["ric"] in globalVars.config.get("Pushover","poc_prio0"):
			        priority = 0
			else:
				priority = -1
                        
                message = globalVars.config.get("Pushover", "poc_message")
                title = globalVars.config.get("Pushover", "poc_title")

            else:
                logging.warning("Invalid type: %s", typ)

            try:
                # replace the wildcards
                message = wildcardHandler.replaceWildcards(message, data)
                title = wildcardHandler.replaceWildcards(title, data)
                sound = globalVars.config.get("Pushover", "sound")
                # set Default-Sound
                if not sound:
                        sound = "pushover"

                # start the connection
                conn = httplib.HTTPSConnection("api.pushover.net:443")
                conn.request("POST", "/1/messages.json",
                             urllib.urlencode({
                                 "token": globalVars.config.get("Pushover", "api_key"),
                                 "user": globalVars.config.get("Pushover", "user_key"),
                                 "message": message,
                                 "html": globalVars.config.get("Pushover", "html"),
                                 "title": title,
                                 "sound": sound,
                                 "priority": priority,
                                 "retry": globalVars.config.get("Pushover", "retry"),
                                 "expire": globalVars.config.get("Pushover", "expire")
                             }), {"Content-type": "application/x-www-form-urlencoded"})

            except:
                logging.error("cannot send Pushover request")
                logging.debug("cannot send Pushover request", exc_info=True)
                return

            try:
                #
                # check Pushover-Response
                #
                response = conn.getresponse()
                if str(response.status) == "200":  # Check Pushover Response and print a Log or Error
                    logging.debug("Pushover response: %s - %s", str(response.status), str(response.reason))
                else:
                    logging.warning("Pushover response: %s - %s", str(response.status), str(response.reason))
            except:  # otherwise
                logging.error("cannot get Pushover response")
                logging.debug("cannot get Pushover response", exc_info=True)
                return

            finally:
                logging.debug("close Pushover-Connection")
                try:
                    request.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #36
0
def run(typ, freq, data):
    """
	This function is the implementation of the Plugin.

	If necessary the configuration hast to be set in the config.ini.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  If necessary the configuration hast to be set in the config.ini.

	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig(
                "fhemCmd"
        ):  #read and debug the config (let empty if no config used)

            protocol = globalVars.config.get("fhemCmd", "protocol")
            logging.debug("protocol: %s", protocol)

            server = globalVars.config.get("fhemCmd", "server")
            logging.debug("server: %s", server)

            port = globalVars.config.get("fhemCmd", "port")
            logging.debug("port: %s", port)

            username = globalVars.config.get("fhemCmd", "username")
            logging.debug("username: %s", username)

            password = globalVars.config.get("fhemCmd", "password")
            logging.debug("password: %s", password)

            ########## User Plugin CODE ##########
            if typ == "FMS":
                fhemCommand = globalVars.config.get("fhemCmd", "commandFMS")
            elif typ == "ZVEI":
                fhemCommand = globalVars.config.get("fhemCmd", "commandZVEI")
            elif typ == "POC":
                fhemCommand = globalVars.config.get("fhemCmd", "commandPOC")
            else:
                logging.warning("Invalid Typ: %s", typ)
                return False

            fhemCommand = wildcardHandler.replaceWildcards(fhemCommand, data)
            logging.debug("fhemCommand: %s", fhemCommand)

            fh = fhem.Fhem(server=server,
                           protocol=protocol,
                           port=port,
                           username=username,
                           password=password)

            fh.send_cmd(fhemCommand)
            del fh
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #37
0
def run(typ, freq, data):
    """
	This function is the implementation of the Plugin.
	If necessary the configuration hast to be set in the config.ini.
	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch
	@type    freq: string
	@keyword freq: frequency of the SDR Stick
	@requires:  If necessary the configuration hast to be set in the config.ini.
	@return:    nothing
	@exception: nothing, make sure this function will never thrown an exception
	"""
    try:
        if configHandler.checkConfig("hue"):  #read and debug the config
            #for debugging
            """logging.debug(globalVars.config.get("hue", "bridgeip"))
			logging.debug(globalVars.config.get("hue", "deviceid"))
			logging.debug(globalVars.config.get("hue", "apikey"))
			logging.debug(globalVars.config.getint("hue", "repeat"))
			logging.debug(globalVars.config.getint("hue", "timeon"))
			logging.debug(globalVars.config.getint("hue", "timeoff"))
			logging.debug(globalVars.config.getint("hue", "keepon"))"""

            ########## User Plugin CODE ##########
            if typ == "FMS":
                logging.warning("%s not supported", typ)
            elif typ == "ZVEI":
                logging.warning("%s not supported", typ)
            elif typ == "POC":
                #logging.warning("%s not supported", typ)
                logging.debug("POC received")
                bridgeip = globalVars.config.get("hue", "bridgeip")
                deviceid = globalVars.config.get("hue", "deviceid")
                apikey = globalVars.config.get("hue", "apikey")
                repeat = globalVars.config.getint("hue", "repeat")
                timeon = globalVars.config.getint("hue", "timeon")
                timeoff = globalVars.config.getint("hue", "timeoff")
                keepon = globalVars.config.getint("hue", "keepon")
                data_on = '{"on":true}'
                data_off = '{"on":false}'
                url = "http://" + bridgeip + "/api/" + apikey + "/lights/" + deviceid + "/state"
                logging.debug("hue REST API URL: %s", url)

                #blinking
                for _ in xrange(repeat):
                    requests.put(url, data=data_on)
                    logging.debug("on for %s seconds", timeon)
                    time.sleep(timeon)
                    requests.put(url, data=data_off)
                    logging.debug("off for %s seconds", timeoff)
                    time.sleep(timeoff)
                if keepon > 0:
                    logging.debug("switch to on and wait for keepon to expire")
                    requests.put(url, data=data_on)
                    logging.debug("keep on for %s seconds", keepon)
                    time.sleep(keepon)
                    requests.put(url, data=data_off)
                else:
                    logging.debug("switch to on and exit plugin")
                    requests.put(url, data=data_on)
            else:
                logging.warning("Invalid Typ: %s", typ)
            ########## User Plugin CODE ##########

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #38
0
def run(typ,freq,data):
	"""
	This function is the implementation of the httpRequest-Plugin.
	It will send the data to an URL via http Request

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  httpRequest-Configuration has to be set in the config.ini

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("httpRequest"): #read and debug the config

			try:
				#
				# Make a copy of the data field to not overwrite the data in it
				# Replace special characters in dataCopy Strings for URL
				#
				dataCopy = dict(data)
				for key in dataCopy:
					if isinstance(dataCopy[key], basestring):
						dataCopy[key] = urllib.quote(dataCopy[key])
				#
				# Get URLs
				#
				if typ == "FMS":
					urls = globalVars.config.get("httpRequest", "fms_url").split(",")
				elif typ == "ZVEI":
					urls = globalVars.config.get("httpRequest", "zvei_url").split(",")
				elif typ == "POC":
					urls = globalVars.config.get("httpRequest", "poc_url").split(",")
				else:
					logging.warning("Invalid Typ: %s", typ)
					return

				#
				# replace wildcards
				#
				for (i, url) in enumerate(urls):
					urls[i] = wildcardHandler.replaceWildcards(urls[i].strip(), dataCopy)
				#
				# HTTP-Request
				#
				logging.debug("send %s HTTP requests", typ)

				for url in urls:
					try:
						urllib2.urlopen(url)
					except urllib2.HTTPError as e:
    						logging.warning("HTTP response: %s", e.code)
					except urllib2.URLError as e:
    						logging.warning("HTTP-specific error: %s", e.args)

			except:
				logging.error("cannot send HTTP request")
				logging.debug("cannot send HTTP request", exc_info=True)
				return
	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #39
0
	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)

	#
	# Read config.ini
	#
	try:
		logging.debug("reading config file")
		globalVars.config = ConfigParser.ConfigParser()
		globalVars.config.read(globalVars.script_path+"/config/config.ini")
		# if given loglevel is debug:
		if globalVars.config.getint("BOSWatch","loglevel") == 10:
			configHandler.checkConfig("BOSWatch")
			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)


	#
	# Set the loglevel and backupCount of the file handler
	#
	try:
		logging.debug("set loglevel of fileHandler to: %s",globalVars.config.getint("BOSWatch","loglevel"))
Пример #40
0
def run(typ,freq,data):
	"""
	This function is the implementation of the MySQL-Plugin.
	It will store the data to an MySQL database

	The configuration for the MySQL-Connection is set in the config.ini.
	For DB- and tablestructure see boswatch.sql

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to BosMon
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to BosMon.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires: MySQL-Configuration has to be set in the config.ini
	@requires: Created Database/Tables, see boswatch.sql

	@return:    nothing
	"""
	try:
		if configHandler.checkConfig("MySQL"): #read and debug the config

			try:
					#
				# Connect to MySQL
				#
				logging.debug("connect to MySQL")
				connection = mysql.connector.connect(host = globals.config.get("MySQL","dbserver"), user = globals.config.get("MySQL","dbuser"), passwd = globals.config.get("MySQL","dbpassword"), db = globals.config.get("MySQL","database"))
				cursor = connection.cursor()
			except:
				logging.error("cannot connect to MySQL")
				logging.debug("cannot connect to MySQL", exc_info=True)
			else: # Without connection, plugin couldn't work
				try:
					#
					# Create and execute SQL-statement
					#
					logging.debug("Insert %s", typ)

					if typ == "FMS":
						cursor.execute("INSERT INTO "+globals.config.get("MySQL","tableFMS")+" (time,fms,status,direction,directionText,tsi,description) VALUES (NOW(),%s,%s,%s,%s,%s,%s)",(data["fms"],data["status"],data["direction"],data["directionText"],data["tsi"],data["description"]))

					elif typ == "ZVEI":
						cursor.execute("INSERT INTO "+globals.config.get("MySQL","tableZVEI")+" (time,zvei,description) VALUES (NOW(),%s,%s)",(data["zvei"],data["description"]))

					elif typ == "POC":
						cursor.execute("INSERT INTO "+globals.config.get("MySQL","tablePOC")+" (time,ric,funktion,funktionChar,msg,bitrate,description) VALUES (NOW(),%s,%s,%s,%s,%s,%s)",(data["ric"],data["function"],data["functionChar"],data["msg"],data["bitrate"],data["description"]))

					else:
						logging.warning("Invalid Typ: %s", typ)
				except:
					logging.error("cannot Insert %s", typ)
					logging.debug("cannot Insert %s", typ, exc_info=True)
					return

			finally:
				logging.debug("close MySQL")
				try:
					cursor.close()
					connection.close() #Close connection in every case
				except:
					pass

	except:
		logging.error("unknown error")
		logging.debug("unknown error", exc_info=True)
Пример #41
0
def run(typ, freq, data):
    """
	This function is the implementation of the eMail-Plugin.
	It will send the data via eMail (SMTP)

	The configuration for the eMail-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via eMail
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to eMail.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  eMail-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("eMail"):  #read and debug the config

            try:
                #
                # connect to SMTP-Server
                #
                server = smtplib.SMTP(
                    globals.config.get("eMail", "smtp_server"),
                    globals.config.get("eMail", "smtp_port"))
                # debug-level to shell (0=no debug|1)
                server.set_debuglevel(0)

                # if tls is enabled, starttls
                if globals.config.get("eMail", "tls"):
                    server.starttls()

                # if user is given, login
                if globals.config.get("eMail", "user"):
                    server.login(globals.config.get("eMail", "user"),
                                 globals.config.get("eMail", "password"))

            except:
                logging.error("cannot connect to eMail")
                logging.debug("cannot connect to eMail", exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:

                if typ == "FMS":
                    logging.debug("Start FMS to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globals.config.get("eMail", "fms_subject")
                        subject = subject.replace(
                            "%FMS%", data["fms"]).replace(
                                "%STATUS%", data["status"])  #replace Wildcards
                        subject = subject.replace(
                            "%DIR%", data["direction"]).replace(
                                "%DIRT%",
                                data["directionText"])  #replace Wildcards
                        subject = subject.replace(
                            "%TSI%", data["tsi"])  #replace Wildcards
                        subject = subject.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        subject = subject.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # read mailtext-structure from config.ini
                        mailtext = globals.config.get("eMail", "fms_message")
                        mailtext = mailtext.replace(
                            "%FMS%", data["fms"]).replace(
                                "%STATUS%", data["status"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%DIR%", data["direction"]).replace(
                                "%DIRT%",
                                data["directionText"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%TSI%", data["tsi"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        mailtext = mailtext.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                elif typ == "ZVEI":
                    logging.debug("Start ZVEI to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globals.config.get("eMail", "zvei_subject")
                        subject = subject.replace(
                            "%ZVEI%", data["zvei"])  #replace Wildcards
                        subject = subject.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        subject = subject.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # read mailtext-structure from config.ini
                        mailtext = globals.config.get("eMail", "zvei_message")
                        mailtext = mailtext.replace(
                            "%ZVEI%", data["zvei"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        mailtext = mailtext.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                elif typ == "POC":
                    logging.debug("Start POC to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globals.config.get("eMail", "poc_subject")
                        subject = subject.replace(
                            "%RIC%", data["ric"])  #replace Wildcards
                        subject = subject.replace(
                            "%FUNC%", data["function"]).replace(
                                "%FUNCCHAR%",
                                data["functionChar"])  #replace Wildcards
                        subject = subject.replace(
                            "%MSG%", data["msg"]).replace(
                                "%BITRATE%",
                                str(data["bitrate"]))  #replace Wildcards
                        subject = subject.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        subject = subject.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # read mailtext-structure from config.ini
                        mailtext = globals.config.get("eMail", "poc_message")
                        mailtext = mailtext.replace(
                            "%RIC%", data["ric"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%FUNC%", data["function"]).replace(
                                "%FUNCCHAR%",
                                data["functionChar"])  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%MSG%", data["msg"]).replace(
                                "%BITRATE%",
                                str(data["bitrate"]))  #replace Wildcards
                        mailtext = mailtext.replace(
                            "%DESCR%",
                            data["description"])  # replace Wildcards
                        mailtext = mailtext.replace(
                            "%TIME%", timeHandler.curtime("H:M:S")).replace(
                                "%DATE%", timeHandler.curtime(
                                    "Y-m-d"))  # replace Wildcards
                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                else:
                    logging.warning("Invalid Typ: %s", typ)

            finally:
                logging.debug("close eMail-Connection")
                try:
                    server.quit()
                except:
                    pass

    except:
        # something very mysterious
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #42
0
def run(typ, freq, data):
    """
	This function is the implementation of the firEmergency-Plugin.
	It will send the data to an firEmergency-Instance.

	The configuration for the firEmergency-Connection is set in the config.ini.

	@type    typ:  string (ZVEI|POC)
	@param   typ:  Typ of the dataset for sending to firEmergency
	@type    data: map of data (structure see interface.txt)
	@param   data: Contains the parameter for dispatch to firEmergency.
	@type    freq: string
	@keyword freq: frequency is not used in this plugin

	@requires:  firEmergency-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("firEmergency"):  # read and debug the config

            try:
                #
                # connect to firEmergency
                #
                firSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                firSocket.connect(
                    (globals.config.get("firEmergency", "firserver"), globals.config.getint("firEmergency", "firport"))
                )
            except:
                logging.error("cannot connect to firEmergency")
                logging.debug("cannot connect to firEmergency", exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:
                #
                # Format given data-structure to xml-string for firEmergency
                #
                if typ == "FMS":
                    logging.debug("FMS not supported by firEmgency")

                elif typ == "ZVEI":
                    logging.debug("ZVEI to firEmergency")
                    try:
                        firXML = (
                            "<event>\n<address>"
                            + data["zvei"]
                            + "</address>\n<description>"
                            + data["description"]
                            + "</description>\n<message>"
                            + data["zvei"]
                            + " alarmiert.</message>\n</event>\n"
                        )
                        firSocket.send(firXML)
                    except:
                        logging.error("%s to firEmergency failed", typ)
                        logging.debug("%s to firEmergency failed", typ, exc_info=True)
                        # Without connection, plugin couldn't work
                        return

                elif typ == "POC":
                    logging.debug("POC to firEmergency")
                    try:
                        # !!! Subric+"XX" because of an Issuse in firEmergency !!!
                        firXML = (
                            "<event>\n<address>"
                            + data["ric"]
                            + "</address>\n<status>"
                            + data["function"]
                            + "XX</status>\n<description>"
                            + data["description"]
                            + "</description>\n<message>"
                            + data["msg"]
                            + "</message>\n</event>\n"
                        )
                        firSocket.send(firXML)
                    except:
                        logging.error("%s to firEmergency failed", typ)
                        logging.debug("%s to firEmergency failed", typ, exc_info=True)
                        # Without connection, plugin couldn't work
                        return

                else:
                    logging.warning("Invalid Typ: %s", typ)

            finally:
                logging.debug("close firEmergency-Connection")
                try:
                    firSocket.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #43
0
def run(typ, freq, data):
    """
	This function is the implementation of the eMail-Plugin.
	It will send the data via eMail (SMTP)

	The configuration for the eMail-Connection is set in the config.ini.
	If an user is set, the HTTP-Request is authenticatet.

	@type    typ:  string (FMS|ZVEI|POC)
	@param   typ:  Typ of the dataset for sending via eMail
	@type    data: map of data (structure see readme.md in plugin folder)
	@param   data: Contains the parameter for dispatch to eMail.
	@type    freq: string
	@keyword freq: frequency of the SDR Stick

	@requires:  eMail-Configuration has to be set in the config.ini

	@return:    nothing
	"""
    try:
        if configHandler.checkConfig("eMail"):  #read and debug the config

            try:
                #
                # connect to SMTP-Server
                #
                try:
                    server = smtplib.SMTP_SSL(
                        globalVars.config.get("eMail", "smtp_server"),
                        globalVars.config.get("eMail", "smtp_port"))
                except:
                    server = smtplib.SMTP(
                        globalVars.config.get("eMail", "smtp_server"),
                        globalVars.config.get("eMail", "smtp_port"))
                # debug-level to shell (0=no debug|1)
                server.set_debuglevel(0)

                # if tls is enabled, starttls
                if globalVars.config.getboolean("eMail", "tls"):
                    server.starttls()

                # if user is given, login
                if globalVars.config.get("eMail", "user"):
                    server.login(globalVars.config.get("eMail", "user"),
                                 globalVars.config.get("eMail", "password"))

            except:
                logging.error("cannot connect to eMail")
                logging.debug("cannot connect to eMail", exc_info=True)
                # Without connection, plugin couldn't work
                return

            else:

                if typ == "FMS":
                    logging.debug("Start FMS to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globalVars.config.get("eMail", "fms_subject")
                        # replace wildcards with helper function
                        subject = wildcardHandler.replaceWildcards(
                            subject, data)

                        # read mailtext-structure from config.ini
                        mailtext = globalVars.config.get(
                            "eMail", "fms_message")
                        # replace wildcards with helper function
                        mailtext = wildcardHandler.replaceWildcards(
                            mailtext, data)

                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                elif typ == "ZVEI":
                    logging.debug("Start ZVEI to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globalVars.config.get(
                            "eMail", "zvei_subject")
                        # replace wildcards with helper function
                        subject = wildcardHandler.replaceWildcards(
                            subject, data)

                        # read mailtext-structure from config.ini
                        mailtext = globalVars.config.get(
                            "eMail", "zvei_message")
                        # replace wildcards with helper function
                        mailtext = wildcardHandler.replaceWildcards(
                            mailtext, data)

                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                elif typ == "POC":
                    logging.debug("Start POC to eMail")
                    try:
                        # read subject-structure from config.ini
                        subject = globalVars.config.get("eMail", "poc_subject")
                        # replace wildcards with helper function
                        subject = wildcardHandler.replaceWildcards(
                            subject, data)

                        # read mailtext-structure from config.ini
                        mailtext = globalVars.config.get(
                            "eMail", "poc_message")
                        # replace wildcards with helper function
                        mailtext = wildcardHandler.replaceWildcards(
                            mailtext, data)

                        # send eMail
                        doSendmail(server, subject, mailtext)
                    except:
                        logging.error("%s to eMail failed", typ)
                        logging.debug("%s to eMail failed", typ, exc_info=True)
                        return

                else:
                    logging.warning("Invalid Type: %s", typ)

            finally:
                logging.debug("close eMail-Connection")
                try:
                    server.quit()
                except:
                    pass

    except:
        # something very mysterious
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)
Пример #44
0
def run(typ, freq, data):
    """
    This function is the implementation of the Pushover-Plugin.
    It will send the data to Pushover API

    @type    typ:  string (FMS|ZVEI|POC)
    @param   typ:  Typ of the dataset
    @type    data: map of data (structure see readme.md in plugin folder)
    @param   data: Contains the parameter
    @type    freq: string
    @keyword freq: frequency of the SDR Stick

    @requires:  Pushover-Configuration has to be set in the config.ini

    @return:    nothing
    """
    try:
        if configHandler.checkConfig("Pushover"):  # read and debug the config

            if typ == "FMS":
                #
                # building message for FMS
                #

                message = globalVars.config.get("Pushover", "fms_message")
                title = globalVars.config.get("Pushover", "fms_title")
                priority = globalVars.config.get("Pushover", "fms_prio")
                logging.debug("Sending message: %s", message)

            elif typ == "ZVEI":
                #
                # building message for ZVEI
                #
                if globalVars.config.get("Pushover", "zvei_sep_prio") == '1':
			if data["zvei"] in globalVars.config.get("Pushover", "zvei_prio2"):
				priority = '2'
			elif data["zvei"] in globalVars.config.get("Pushover","zvei_prio1"):
				priority = '1'
			elif data["zvei"] in globalVars.config.get("Pushover","zvei_prio0"):
				priority = '0'
			else:
				priority = '-1'
		else:
			priority = globalVars.config.get("Pushover","zvei_std_prio")

                message = globalVars.config.get("Pushover", "zvei_message")
                title = globalVars.config.get("Pushover", "zvei_title")
                logging.debug("Sending message: %s", message)

            elif typ == "POC":

                #
                # Pushover-Request
                #
                logging.debug("send Pushover for %s", typ)
                if globalVars.config.get("Pushover", "poc_spec_ric") == '0':
			if data["function"] == '1':
                        	priority = globalVars.config.get("Pushover", "SubA")
                    	elif data["function"] == '2':
                        	priority = globalVars.config.get("Pushover", "SubB")
                    	elif data["function"] == '3':
	                        priority = globalVars.config.get("Pushover", "SubC")
        	        elif data["function"] == '4':
                	        priority = globalVars.config.get("Pushover", "SubD")
                    	else:
                        	priority = 0
                else:
                    	if data["ric"] in globalVars.config.get("Pushover", "poc_prio2"):
                        	priority = 2
			elif data["ric"] in globalVars.config.get("Pushover","poc_prio1"):
			        priority = 1
                    	elif data["ric"] in globalVars.config.get("Pushover","poc_prio0"):
			        priority = 0
			else:
				priority = -1
                        
                message = globalVars.config.get("Pushover", "poc_message")
                title = globalVars.config.get("Pushover", "poc_title")

            else:
                logging.warning("Invalid type: %s", typ)

            try:
                # replace the wildcards
                message = wildcardHandler.replaceWildcards(message, data)
                title = wildcardHandler.replaceWildcards(title, data)

                # start the connection
                conn = httplib.HTTPSConnection("api.pushover.net:443")
                conn.request("POST", "/1/messages.json",
                             urllib.urlencode({
                                 "token": globalVars.config.get("Pushover", "api_key"),
                                 "user": globalVars.config.get("Pushover", "user_key"),
                                 "message": message,
                                 "html": globalVars.config.get("Pushover", "html"),
                                 "title": title,
                                 "priority": priority,
                                 "retry": globalVars.config.get("Pushover", "retry"),
                                 "expire": globalVars.config.get("Pushover", "expire")
                             }), {"Content-type": "application/x-www-form-urlencoded"})

            except:
                logging.error("cannot send Pushover request")
                logging.debug("cannot send Pushover request", exc_info=True)
                return

            try:
                #
                # check Pushover-Response
                #
                response = conn.getresponse()
                if str(response.status) == "200":  # Check Pushover Response and print a Log or Error
                    logging.debug("Pushover response: %s - %s", str(response.status), str(response.reason))
                else:
                    logging.warning("Pushover response: %s - %s", str(response.status), str(response.reason))
            except:  # otherwise
                logging.error("cannot get Pushover response")
                logging.debug("cannot get Pushover response", exc_info=True)
                return

            finally:
                logging.debug("close Pushover-Connection")
                try:
                    request.close()
                except:
                    pass

    except:
        logging.error("unknown error")
        logging.debug("unknown error", exc_info=True)