remove trailing whitespaces

to improve codacy rating
This commit is contained in:
Bastian Schroll 2016-10-02 21:28:04 +02:00
parent bf27623839
commit 77fb7fb44f
13 changed files with 97 additions and 100 deletions

View file

@ -16,7 +16,7 @@ class MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def setBackupCount(self, backupCount):
"""Set/Change backupCount"""
self.backupCount = backupCount
def close(self):
"""Make shure logfile will be flushed"""
self.flush()

View file

@ -14,11 +14,11 @@ class NMAHandler(logging.Handler): # Inherit from logging.Handler
"""
Handler instances dispatch logging events to NotifyMyAndroid.
"""
def __init__(self, APIKey, application="BOSWatch", event="Logging-Handler"):
"""
Initializes the handler with NMA-specific parameters.
@param APIKey: might be a string containing 1 key or an array of keys
@param application: application name [256]
@param event: event name [1000]
@ -38,7 +38,7 @@ class NMAHandler(logging.Handler): # Inherit from logging.Handler
"""
# record.message is the log message
message = record.message
# if exist, add details as NMA event:
# record.module is the module- or filename
if (len(record.module) > 0):
@ -51,7 +51,7 @@ class NMAHandler(logging.Handler): # Inherit from logging.Handler
else:
# we have to set an event-text, use self.event now
event = self.event
# record.levelno is the log level
# loglevel: 10 = debug => priority: -2
# loglevel: 20 = info => priority: -1
@ -68,6 +68,6 @@ class NMAHandler(logging.Handler): # Inherit from logging.Handler
priority = -1
else:
priority = -2
# pynma.push(self, application="", event="", description="", url="", contenttype=None, priority=0, batch_mode=False, html=False)
self.nma.push(application=self.application, event=event, description=message, priority=priority)
self.nma.push(application=self.application, event=event, description=message, priority=priority)

View file

@ -47,7 +47,7 @@ def processAlarmHandler(typ, freq, data):
pass
else:
processAlarm(typ, freq, data)
##
#

View file

@ -42,7 +42,7 @@ def decodeString(inputString = ""):
pass
return decodedString
def convertToUnicode(inputString = ""):
"""
Returns given string as unicode
@ -53,10 +53,10 @@ def convertToUnicode(inputString = ""):
@return: string in unicode
@exception: Exception if converting to unicode failed
"""
decodedString = ""
logging.debug("call convertToUnicode('%s')", inputString)
# nothing to do if inputString is empty
if len(inputString) > 0:
# 1. check if integer
@ -68,12 +68,12 @@ def convertToUnicode(inputString = ""):
except ValueError:
# ... no integer is okay...
pass
# 2. Check if inputString is unicode...
if isinstance(inputString, unicode):
logging.debug("-- unicode")
return inputString
try:
# try to decoding:
decodedString = decodeString(inputString)
@ -83,9 +83,9 @@ def convertToUnicode(inputString = ""):
# no fixing possible, raise exception
raise
return decodedString
def convertToUTF8(inputString = ""):
"""
Returns given string in UTF-8
@ -99,7 +99,7 @@ def convertToUTF8(inputString = ""):
uft8String = ""
logging.debug("call convertToUTF8('%s')", inputString)
# nothing to do if inputString is empty
if len(inputString) > 0:
try:
@ -111,20 +111,20 @@ def convertToUTF8(inputString = ""):
return inputString
except ValueError:
pass
# 2. Check if inputString is unicode...
if isinstance(inputString, unicode):
logging.debug("-- unicode")
# ... then return it as UTF-8
uft8String = decodedString.encode('UTF-8')
return uft8String
# 2. check given inputString is already UTF-8...
decodedString = inputString.decode('UTF-8', 'strict')
# ... no UnicodeDecodeError exception, inputString ist UTF-8
logging.debug("-- UTF-8")
return inputString
except UnicodeDecodeError:
# inputString contains non-UTF-8 character
logging.debug("string contains non-UTF-8 characters: %s", inputString)
@ -137,9 +137,9 @@ def convertToUTF8(inputString = ""):
logging.debug("encoding string failed", exc_info=True)
# no fixing possible, raise exception
raise
# inputString should now decoded...
try:
# encode decodedString to UTF-8
uft8String = decodedString.encode('UTF-8')
@ -148,7 +148,7 @@ def convertToUTF8(inputString = ""):
logging.debug("encoding to UTF-8 failed", exc_info=True)
# no fixing possible, raise exception
raise
# Now we must have an utf8-string, check it:
try:
uft8String.decode('UTF-8', 'strict')
@ -158,7 +158,7 @@ def convertToUTF8(inputString = ""):
logging.debug("converting to UTF-8 failed", exc_info=True)
# no fixing possible, raise exception
raise
# End of exception UnicodeDecodeError: check given string is already UTF-8
pass
@ -168,4 +168,4 @@ def convertToUTF8(inputString = ""):
# no fixing possible, raise exception
raise
return uft8String
return uft8String

View file

@ -32,7 +32,7 @@ def replaceWildcards(text, data, lineBrakeAllowed=False):
try:
# replace date and time wildcards
text = text.replace("%TIME%", timeHandler.getTime(data["timestamp"])).replace("%DATE%", timeHandler.getDate(data["timestamp"]))
# replace some special chars
if lineBrakeAllowed == True:
text = text.replace("%BR%", "\r\n")

View file

@ -1,4 +1,3 @@
#!/usr/bin/python
from .pynma import PyNMA
from .pynma import PyNMA

View file

@ -14,7 +14,7 @@ except ImportError:
__version__ = "1.0"
API_SERVER = 'www.notifymyandroid.com'
API_SERVER = 'www.notifymyandroid.com'
ADD_PATH = '/publicapi/notify'
USER_AGENT="PyNMA/v%s"%__version__
@ -75,7 +75,7 @@ takes 2 optional arguments:
apikey = [apikey]
self._apikey = uniq(apikey)
return self.push(application, event, description, url, contenttype, priority, batch_mode, html)
def push(self, application="", event="", description="", url="", contenttype=None, priority=0, batch_mode=False, html=False):
"""Pushes a message on the registered API keys.
takes 5 arguments:
@ -99,10 +99,10 @@ Warning: using batch_mode will return error only if all API keys are bad
if url:
datas['url'] = url[:512]
if contenttype == "text/html" or html == True: # Currently only accepted content type
datas['content-type'] = "text/html"
if self._developerkey:
datas['developerkey'] = self._developerkey
@ -118,7 +118,7 @@ Warning: using batch_mode will return error only if all API keys are bad
res = self.callapi('POST', ADD_PATH, datas)
results[datas['apikey']] = res
return results
def callapi(self, method, path, args):
headers = { 'User-Agent': USER_AGENT }
if method == "POST":
@ -135,7 +135,7 @@ Warning: using batch_mode will return error only if all API keys are bad
'message': str(e)
}
pass
return res
def _parse_reponse(self, response):
@ -152,5 +152,3 @@ Warning: using batch_mode will return error only if all API keys are bad
res['message'] = elem.firstChild.nodeValue
res['type'] = elem.tagName
return res

View file

@ -26,7 +26,7 @@ SET time_zone = "+00:00";
--
CREATE DATABASE IF NOT EXISTS boswatch;
USE boswatch;
USE boswatch;
-- --------------------------------------------------------
@ -121,11 +121,11 @@ INSERT INTO `bos_weblogin` (`id`, `user`, `password`, `isadmin`) VALUES (NULL, '
--
-- Schedule für Tabelle `bos_pocsag`
--
CREATE EVENT IF NOT EXISTS `Delete POCSAG Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
CREATE EVENT IF NOT EXISTS `Delete POCSAG Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
DELETE FROM bos_pocsag WHERE time < DATE_SUB(NOW(),INTERVAL 3 MONTH);
-- --------------------------------------------------------
@ -134,11 +134,11 @@ CREATE EVENT IF NOT EXISTS `Delete POCSAG Entries > 3 Months`
-- Schedule für Tabelle `bos_fms`
--
CREATE EVENT IF NOT EXISTS `Delete FMS Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
CREATE EVENT IF NOT EXISTS `Delete FMS Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
DELETE FROM bos_fms WHERE time < DATE_SUB(NOW(),INTERVAL 3 MONTH);
-- --------------------------------------------------------
@ -146,15 +146,15 @@ CREATE EVENT IF NOT EXISTS `Delete FMS Entries > 3 Months`
--
-- Schedule für Tabelle `bos_zvei`
--
CREATE EVENT IF NOT EXISTS `Delete ZVEI Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
DELETE FROM bos_zvei WHERE time < DATE_SUB(NOW(),INTERVAL 3 MONTH);
CREATE EVENT IF NOT EXISTS `Delete ZVEI Entries > 3 Months`
ON SCHEDULE EVERY 1 DAY
STARTS '2016-01-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
DELETE FROM bos_zvei WHERE time < DATE_SUB(NOW(),INTERVAL 3 MONTH);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View file

@ -11,6 +11,6 @@ Daten eintragen
PIN-Abfrage deaktivieren mittels minicom
minicom -D /dev/ttyUSB0
ATI # alle infos
AT+CLCK="SC",0,"0000" # 0000 = PIN
AT+CLCK="SC",2 # Status-Check
AT+CLCK="SC",2 # Status-Check

View file

@ -2,9 +2,9 @@
# -*- coding: UTF-8 -*-
"""
This plugin enables the function of sendig SMS to
This plugin enables the function of sendig SMS to
a given number defined in config.ini
It is sensitive to ric and subric, also defined in
It is sensitive to ric and subric, also defined in
config.ini
@author: Jens Herrmann
@ -87,16 +87,16 @@ def run(typ,freq,data):
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 = globals.config.get("SMS","quantity")
aRic = []
# build the array
for x in range (1, int(i) + 1):
# check the number of subrics
subric = globals.config.get("SMS","subric" + str(x))
if len(subric) > 1: # we have more than one subric
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(' ','')
@ -112,37 +112,37 @@ def run(typ,freq,data):
tmp.append(globals.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 = globals.config.get("SMS","text" + str(case))
number = globals.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},
@ -153,7 +153,7 @@ def run(typ,freq,data):
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 ##########

View file

@ -46,7 +46,7 @@ def onLoad():
BOTChatIDAPIKey = globals.config.get("Telegram","BOTChatIDAPIKey")
RICforLocationAPIKey = globals.config.get("Telegram","RICforLocationAPIKey")
GoogleAPIKey = globals.config.get("Telegram","GoogleAPIKey")
return
@ -69,7 +69,7 @@ def run(typ,freq,data):
@return: nothing
@exception: nothing, make sure this function will never thrown an exception
"""
global BOTTokenKey
global BOTChatIDAPIKey
global RICforLocationAPIKey
@ -83,17 +83,17 @@ def run(typ,freq,data):
logging.debug("Compose output from POCSAG-message")
# compose message content
output = timeHandler.curtime()+"\n"+data["ric"]+"("+data["functionChar"]+")\n"+data["description"]+"\n"+data["msg"]
# Initiate Telegram Bot
logging.debug("Initiate Telegram BOT")
bot = telegram.Bot(token='%s' % BOTTokenAPIKey)
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, output)
# Generate location information only for specific RIC
if data["ric"] == RICforLocationAPIKey:
if data["ric"] == RICforLocationAPIKey:
# Generate map
logging.debug("Extract address from POCSAG message")
address = "+".join(data["msg"].split(')')[0].split('/',1)[1].replace('(',' ').split())

View file

@ -130,12 +130,12 @@ def run(typ,freq,data):
subject = globals.config.get("eMail", "fms_subject")
# replace wildcards with helper function
subject = wildcardHandler.replaceWildcards(subject, data)
# read mailtext-structure from config.ini
mailtext = globals.config.get("eMail", "fms_message")
# replace wildcards with helper function
mailtext = wildcardHandler.replaceWildcards(mailtext, data, lineBrakeAllowed=True)
# send eMail
doSendmail(server, subject, mailtext)
except:
@ -150,12 +150,12 @@ def run(typ,freq,data):
subject = globals.config.get("eMail", "zvei_subject")
# replace wildcards with helper function
subject = wildcardHandler.replaceWildcards(subject, data)
# read mailtext-structure from config.ini
mailtext = globals.config.get("eMail", "zvei_message")
# replace wildcards with helper function
mailtext = wildcardHandler.replaceWildcards(mailtext, data, lineBrakeAllowed=True)
# send eMail
doSendmail(server, subject, mailtext)
except:
@ -170,12 +170,12 @@ def run(typ,freq,data):
subject = globals.config.get("eMail", "poc_subject")
# replace wildcards with helper function
subject = wildcardHandler.replaceWildcards(subject, data)
# read mailtext-structure from config.ini
mailtext = globals.config.get("eMail", "poc_message")
# replace wildcards with helper function
mailtext = wildcardHandler.replaceWildcards(mailtext, data, lineBrakeAllowed=True)
# send eMail
doSendmail(server, subject, mailtext)
except:

View file

@ -66,7 +66,7 @@ def checkResponse(response, APIKey):
except:
logging.error("cannot read pynma response")
logging.debug("cannot read pynma response", exc_info=True)
return
return
##
@ -90,7 +90,7 @@ def onLoad():
global fmsAPIKeyList
global zveiAPIKeyList
global pocAPIKeyList
# load config:
configHandler.checkConfig("notifyMyAndroid")
application = stringConverter.convertToUnicode(globals.config.get("notifyMyAndroid","appName"))
@ -113,35 +113,35 @@ def onLoad():
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 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 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 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)
@ -165,7 +165,7 @@ def onLoad():
def run(typ,freq,data):
"""
This function is the implementation of the notifyMyAndroid-Plugin.
The configuration is set in the config.ini.
@type typ: string (FMS|ZVEI|POC)
@ -187,7 +187,7 @@ def run(typ,freq,data):
global fmsAPIKeyList
global zveiAPIKeyList
global pocAPIKeyList
try:
try:
#
@ -199,7 +199,7 @@ def run(typ,freq,data):
logging.debug("cannot initialize pyNMA", exc_info=True)
# Without class, plugin couldn't work
return
else:
# toDo is equals for all types, so only check if typ is supported
supportedTypes = ["FMS", "ZVEI", "POC"]
@ -213,7 +213,7 @@ def run(typ,freq,data):
if ("POC" in typ) and (len(data['msg']) > 0):
msg += "\n" + data['msg']
msg = stringConverter.convertToUnicode(msg)
# if not using csv-import, all is simple...
if usecsv == False:
response = nma.pushWithAPIKey(APIKey, application, event, msg, priority=globals.config.getint("notifyMyAndroid","priority"))
@ -234,7 +234,7 @@ def run(typ,freq,data):
except KeyError:
# nothing found
pass
elif "ZVEI" in typ:
# lets look for zvei in zveiAPIKeyList
xID = data['zvei']
@ -250,7 +250,7 @@ def run(typ,freq,data):
except KeyError:
# nothing found
pass
elif "POC" in typ:
xID = ""
# 1. lets look for ric+functionChar in pocAPIKeyList