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)
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)
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)
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)
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: ########## User Plugin CODE ########## try: if typ in ("POC", "FMS", "ZVEI"): logging.debug("Read format and compose output for %s-message" % typ) # compose message content text = globalVars.config.get("Telegram", "%s_message" % typ) text = wildcardHandler.replaceWildcards(text, data) # Initiate Telegram Bot logging.debug("Initiate Telegram BOT") bot = telegram.Bot(token='%s' % BOTTokenAPIKey) # Send message to chat via Telegram BOT API logging.debug("Send message to chat via Telegram BOT API") bot.sendMessage('%s' % BOTChatIDAPIKey, text) # Generate location information only for specific RIC if typ == "POC" and data["ric"] == RICforLocationAPIKey: # Generate map logging.debug("Extract address from POCSAG message") address = "+".join(data["msg"].split(')')[0].split( '/', 1)[1].replace('(', ' ').split()) logging.debug("Retrieve maps from Google") url = "+".join([ "http://maps.googleapis.com/maps/api/staticmap?markers=", address, "&size=480x640&maptype=roadmap&zoom=16&key=", GoogleAPIKey ]) urllib.urlretrieve(url, "overview_map.png") url = "+".join([ "http://maps.googleapis.com/maps/api/staticmap?markers=", address, "&size=240x320&scale=2&maptype=hybrid&zoom=17&key=", GoogleAPIKey ]) urllib.urlretrieve(url, "detail_map.png") # Send message and map with Telegram logging.debug("Send message and maps via Telegram BOT") bot.sendPhoto('%s' % BOTChatIDAPIKey, open('overview_map.png', 'rb'), disable_notification='true') bot.sendPhoto('%s' % BOTChatIDAPIKey, open('detail_map.png', 'rb'), disable_notification='true') # Geocoding of address logging.debug("Geocode address") gcode = googlemaps.Client(key='%s' % GoogleAPIKey) gcode_result = gcode.geocode(address) logging.debug("Send location via Telegram BOT API") bot.sendLocation( '%s' % BOTChatIDAPIKey, gcode_result[0]['geometry']['location']['lat'], gcode_result[0]['geometry']['location']['lng'], disable_notification='true') else: logging.warning("Invalid Typ: %s", typ) except Unauthorized: logging.error("Telegram Error: Unauthorized") logging.debug("Telegram Error: Unauthorized", exc_info=True) except BadRequest: logging.error("Telegram Error: BadRequest") logging.debug("Telegram Error: BadRequest", exc_info=True) except NetworkError: logging.error("Telegram Error: NetworkError") logging.debug("Telegram Error: NetworkError", exc_info=True) except TelegramError: logging.error("Telegram Error: TelegramError") logging.debug("Telegram Error: TelegramError", exc_info=True) ########## User Plugin CODE ########## except: logging.error("unknown error") logging.debug("unknown error", exc_info=True)
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)
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)
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)
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)
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)
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: ########## User Plugin CODE ########## try: if typ in ("POC", "FMS", "ZVEI"): logging.debug("Read format and compose output for %s-message" % typ) # compose message content text = globalVars.config.get("Telegram", "%s_message" % typ) text = wildcardHandler.replaceWildcards(text, data) # Initiate Telegram Bot logging.debug("Initiate Telegram BOT") bot = telegram.Bot(token='%s' % BOTTokenAPIKey) # Send message to chat via Telegram BOT API logging.debug("Send message to chat via Telegram BOT API") bot.sendMessage('%s' % BOTChatIDAPIKey, text, parse_mode=telegram.ParseMode.HTML) # Generate location information only for specific RIC if typ == "POC" and data["ric"] == RICforLocationAPIKey: # Generate map logging.debug("Extract address from POCSAG message") address = "+".join(data["msg"].split(')')[0].split( '/', 1)[1].replace('(', ' ').split()) # Retrieve directions using Google API logging.debug("Retrieve polylines from Directions API") url = "".join([ "https://maps.googleapis.com/maps/api/directions/json?origin=", RoutingOrigin, "&destination=", address, "&mode=driving&key=", GoogleAPIKey ]) response = json.loads( requests.get(url).content.decode('utf-8')) logging.debug("Directions API return status: %s" % response['status']) # Retrieve static maps using Google API logging.debug("Retrieve maps from Google") url = "".join([ "https://maps.googleapis.com/maps/api/staticmap?&size=480x640&maptype=roadmap&path=enc:", response['routes'][0]['overview_polyline']['points'], "&language=de&key=", GoogleAPIKey ]) with open("overview_map.png", "wb") as img: img.write(requests.get(url).content) url = "".join([ "https://maps.googleapis.com/maps/api/staticmap?markers=", address, "&size=240x320&scale=2&maptype=hybrid&zoom=17&language=de&key=", GoogleAPIKey ]) with open("detail_map.png", "wb") as img: img.write(requests.get(url).content) # Send message and map with Telegram logging.debug("Send message and maps via Telegram BOT") bot.sendPhoto('%s' % BOTChatIDAPIKey, open('overview_map.png', 'rb'), disable_notification='true') bot.sendPhoto('%s' % BOTChatIDAPIKey, open('detail_map.png', 'rb'), disable_notification='true') # Geocoding of address logging.debug("Geocode address") url = "".join([ "https://maps.googleapis.com/maps/api/geocode/json?address=", address, "&language=de&key=", GoogleAPIKey ]) gcode_result = json.loads(requests.get(url).content) logging.debug("Geocoding API return status: %s" % gcode_result['status']) logging.debug("Send location via Telegram BOT API") bot.sendLocation('%s' % BOTChatIDAPIKey, gcode_result[results][0]['geometry'] ['location']['lat'], gcode_result[results][0]['geometry'] ['location']['lng'], disable_notification='true') else: logging.warning("Invalid Typ: %s", typ) except Unauthorized: logging.error("Telegram Error: Unauthorized") logging.debug("Telegram Error: Unauthorized", exc_info=True) except BadRequest: logging.error("Telegram Error: BadRequest") logging.debug("Telegram Error: BadRequest", exc_info=True) except NetworkError: logging.error("Telegram Error: NetworkError") logging.debug("Telegram Error: NetworkError", exc_info=True) except TelegramError: logging.error("Telegram Error: TelegramError") logging.debug("Telegram Error: TelegramError", exc_info=True) ########## User Plugin CODE ########## except: logging.error("unknown error") logging.debug("unknown error", exc_info=True)
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)
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)
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: ########## User Plugin CODE ########## try: if typ in ("POC", "FMS", "ZVEI"): logging.debug("Read format and compose output for %s-message" % typ) # compose message content text = globalVars.config.get("Telegram", "%s_message" % typ) text = wildcardHandler.replaceWildcards(text, data) # Initiate Telegram Bot logging.debug("Initiate Telegram BOT") bot = telegram.Bot(token='%s' % BOTTokenAPIKey) # Send message to chat via Telegram BOT API logging.debug("Send message to chat via Telegram BOT API") bot.sendMessage('%s' % BOTChatIDAPIKey, text) # Generate location information only for specific RIC if typ == "POC" and data["ric"] == RICforLocationAPIKey: # Generate map logging.debug("Extract address from POCSAG message") address = "+".join(data["msg"].split(')')[0].split('/',1)[1].replace('(',' ').split()) # Retrieve directions using Google API logging.debug("Retrieve polylines from Directions API") url = "".join(["https://maps.googleapis.com/maps/api/directions/json?origin=", RoutingOrigin, "&destination=", address, "&mode=driving&key=", GoogleAPIKey]) response = json.loads(requests.get(url).content.decode('utf-8')) logging.debug("Directions API return status: %s" % response['status']) # Retrieve static maps using Google API logging.debug("Retrieve maps from Google") url = "".join(["https://maps.googleapis.com/maps/api/staticmap?&size=480x640&maptype=roadmap&path=enc:", response['routes'][0]['overview_polyline']['points'], "&language=de&key=", GoogleAPIKey]) with open("overview_map.png", "wb") as img: img.write(requests.get(url).content) url = "".join(["https://maps.googleapis.com/maps/api/staticmap?markers=", address, "&size=240x320&scale=2&maptype=hybrid&zoom=17&language=de&key=", GoogleAPIKey]) with open("detail_map.png", "wb") as img: img.write(requests.get(url).content) # Send message and map with Telegram logging.debug("Send message and maps via Telegram BOT") bot.sendPhoto('%s' % BOTChatIDAPIKey, open('overview_map.png', 'rb'), disable_notification='true') bot.sendPhoto('%s' % BOTChatIDAPIKey, open('detail_map.png', 'rb'), disable_notification='true') # Geocoding of address logging.debug("Geocode address") url = "".join(["https://maps.googleapis.com/maps/api/geocode/json?address=", address, "&language=de&key=", GoogleAPIKey]) gcode_result = json.loads(requests.get(url).content) logging.debug("Geocoding API return status: %s" % gcode_result['status']) logging.debug("Send location via Telegram BOT API") bot.sendLocation('%s' % BOTChatIDAPIKey, gcode_result[results][0]['geometry']['location']['lat'], gcode_result[results][0]['geometry']['location']['lng'], disable_notification='true') else: logging.warning("Invalid Typ: %s", typ) except Unauthorized: logging.error("Telegram Error: Unauthorized") logging.debug("Telegram Error: Unauthorized", exc_info=True) except BadRequest: logging.error("Telegram Error: BadRequest") logging.debug("Telegram Error: BadRequest", exc_info=True) except NetworkError: logging.error("Telegram Error: NetworkError") logging.debug("Telegram Error: NetworkError", exc_info=True) except TelegramError: logging.error("Telegram Error: TelegramError") logging.debug("Telegram Error: TelegramError", exc_info=True) ########## User Plugin CODE ########## except: logging.error("unknown error") logging.debug("unknown error", exc_info=True)
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)
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)
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)
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)