Example #1
0
def send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist=[]):
	
	# mailtype option
	# "report"
	# "alert"
	if mailtype=="report":
		starttitle="Report:"
		showtable=True
		showpicture=True
		showlink=True

			
	elif mailtype=="alert":
		starttitle="Alert:"
		showtable=False
		showpicture=False
		showlink=True

	
	
	currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
	# got credentials here !
	user=emaildbmod.getaddress()
	pwd=emaildbmod.getpassword()
	recipient=address

	# check IP address
	iplocal=networkmod.get_local_ip()	
	ipext=networkmod.EXTERNALIPADDR
	if ipext=="":
		logger.info('Stored external IP address is empty, try to get it from network')
		ipext=networkmod.get_external_ip()
		
	print "Try to send mail"	
	# subject of the mail
	subject=starttitle +" " + title + "  " + currentdate
	htmlbody=create_htmlopen()
	htmlbody=htmlbody+create_htmlintro(intromessage)+create_htmlbody(bodytextlist)
	
	if showlink:
		if ipext=="":
			print "No external IP address available"
			logger.error('Unable to get external IP address')		
		else:		
			port=str(networkmod.PUBLICPORT)
			if cmd=="mail+info+link":
				htmlbody=htmlbody+create_htmladdresses(ipext, iplocal, port)
	if showtable:
		# table with information
		matrixinfo=sensordbmod.sensorsysinfomatrix()
		htmlbody=htmlbody+create_htmlmatrix(matrixinfo)
		matrixinfo=actuatordbmod.sensorsysinfomatrix()
		htmlbody=htmlbody+create_htmlmatrix(matrixinfo)
	htmlbody=htmlbody+create_htmlclose()
	issent=send_email_html(user, pwd, recipient, subject, htmlbody, showpicture)
	if (issent) and (showlink) and (ipext!=""):
		global IPEXTERNALSENT
		IPEXTERNALSENT=ipext
	return issent
Example #2
0
def send_email_main(address, title, cmd, mailtype, intromessage):

    # mailtype option
    # "report"
    # "alert"
    if mailtype == "report":
        starttitle = "Report:"
        showtable = True
        showpicture = True
        showlink = True

    elif mailtype == "alert":
        starttitle = "Alert:"
        showtable = False
        showpicture = False
        showlink = True

    currentdate = datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
    # got credentials here !
    user = emaildbmod.getaddress()
    pwd = emaildbmod.getpassword()
    recipient = address

    # check IP address
    iplocal = networkmod.get_local_ip()
    ipext = networkmod.get_external_ip()
    if ipext == "":
        print "No external IP address, mail is not sent"
        logger.error('Unable to get external IP address, mail is not sent')
        return False
    else:
        print "Try to send mail"
        # subject of the mail
        subject = starttitle + " " + title + "  " + currentdate
        htmlbody = create_htmlopen()
        htmlbody = htmlbody + create_htmlintro(intromessage)
        if showlink:
            port = str(networkmod.PUBLICPORT)
            if cmd == "mail+info+link":
                htmlbody = htmlbody + create_htmladdresses(
                    ipext, iplocal, port)
        if showtable:
            # table with information
            matrixinfo = sensordbmod.sensorsysinfomatrix()
            htmlbody = htmlbody + create_htmlmatrix(matrixinfo)
            matrixinfo = actuatordbmod.sensorsysinfomatrix()
            htmlbody = htmlbody + create_htmlmatrix(matrixinfo)
        htmlbody = htmlbody + create_htmlclose()
        issent = send_email_html(user, pwd, recipient, subject, htmlbody,
                                 showpicture)
        if issent:
            global IPEXTERNALSENT
            IPEXTERNALSENT = ipext
    return issent
Example #3
0
def network():
    #if not session.get('logged_in'):
    #	return render_template('login.html',error=None, change=False)
    wifilist = []
    savedssid = []
    filenamelist = "wifi networks"

    print("visualizzazione menu network:")

    iplocal = networkmod.get_local_ip()
    iplocallist = networkmod.get_local_ip_list()
    ipext = networkmod.get_external_ip()
    iplocalwifi = networkmod.IPADDRESS
    ipport = networkmod.PUBLICPORT
    hostname = networkmod.gethostname()
    connectedssidlist = networkmod.connectedssid()
    if len(connectedssidlist) > 0:
        connectedssid = connectedssidlist[0]
    else:
        connectedssid = ""

    localwifisystem = networkmod.localwifisystem
    #print " localwifisystem = ", localwifisystem , " connectedssid ", connectedssid
    message = networkmod.networkdbmod.getstoredmessage()

    return render_template('network.html',
                           filenamelist=filenamelist,
                           connectedssid=connectedssid,
                           localwifisystem=localwifisystem,
                           ipext=ipext,
                           iplocallist=iplocallist,
                           iplocal=iplocal,
                           iplocalwifi=iplocalwifi,
                           ipport=ipport,
                           hostname=hostname,
                           message=message)
Example #4
0
def heartbeat():
    print("start heartbeat check", " ", datetime.now())
    logger.info('Start heartbeat routine %s',
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # check wifi connection
    connectedssid = networkmod.connectedssid()
    connected = False
    if len(connectedssid) == 0:

        if not networkmod.WIFIENDIS == "Disabled":
            logger.warning(
                'Heartbeat check , no network connected -------------- try to connect'
            )
            print(
                'Heartbeat check , no network connected -------------- try to connect'
            )
            connected = networkmod.connect_network()
        else:
            logger.info('Heartbeat check , wifi disabled')
    else:
        logger.info('Heartbeat check , Connected Wifi Network: %s ',
                    connectedssid[0])
        if connectedssid[0] == networkmod.localwifisystem:
            logger.info(
                'Heartbeat check , Configured as wifi access point, check if possible to connect to wifi network'
            )
            connected = networkmod.connect_network()
            networkmod.DHCP_COUNTER = 0
        else:  # Connected to wifi network
            reachgoogle = networkmod.check_internet_connection(1)

            if not reachgoogle:
                logger.warning(
                    'Heartbeat check wifi SSID ok, but test ping not able to reach Google'
                )
                print('Heartbeat check , no IP connection')
                #connected=networkmod.connect_network() # use this in case you require the system to try connect wifi again in case no internet is reached
                #logger.warning('Heartbeat check , DHCP reset counter %s' , str(networkmod.DHCP_COUNTER))
                # DHCP reset
                #if (networkmod.DHCP_COUNTER % 16)==0: # try to reset every 16x15min =4 hours
                # try to reset DHCP
                #logger.warning('Heartbeat check , reset DHCP')
                #print 'Heartbeat check , reset DHCP'
                #networkmod.resetDHCP()

                #networkmod.DHCP_COUNTER=networkmod.DHCP_COUNTER+1

                goON, GWipaddr = networkmod.checkGWsubnet("wlan0")
                if GWipaddr == "":
                    logger.info(
                        'Gateway IP address NOT found, back to AP mode')
                    # back to AP mode! kind of risky business
                    networkmod.connect_AP()

                else:
                    logger.info('Gateway IP address found %s', GWipaddr)

                connected = False
            else:
                logger.info('Heartbeat check , wifi connection OK')
                print('Heartbeat check , wifi connection OK')
                #networkmod.DHCP_COUNTER=0
                connected = True

    if connected:
        # Check if remote IP address is changed compared to previous communication and in such case resend the mail
        ipext = networkmod.get_external_ip()
        logger.info(
            'Heartbeat check , Check IP address change -%s- and previously sent -%s-',
            ipext, emailmod.IPEXTERNALSENT)
        if (ipext != ""):
            if (emailmod.IPEXTERNALSENT != ""):
                if ipext != emailmod.IPEXTERNALSENT:
                    print(
                        "Heartbeat check, IP address change detected. Send email with updated IP address"
                    )
                    logger.info(
                        'Heartbeat check, IP address change detected. Send email with updated IP address'
                    )
                    emailmod.sendallmail(
                        "alert",
                        "System detected IP address change, below the updated links"
                    )
                else:
                    logger.info('Heartbeat check, IP address unchanged')
            else:
                # first mail has not been sent succesfully of IPEXTERNALSENT was not available by the time
                print("System has been reconnected")
                logger.info(
                    "System has been reconnected, IPEXTERNALSENT was empty")
                emailmod.sendallmail("alert", "System has been reconnected")

    else:
        print("not able to establish an internet connection")
        logger.warning("not able to establish an internet connection")

    # check clock with NTP and reset master scheduler in case of clock change
    if CheckNTPandAdjustClockandResetSched():
        return True

    #check the static IP address
    currentipaddr = networkmod.get_local_ip_raw()
    logger.info('Target IP address= %s. Current access point IP addresses= %s',
                networkmod.IPADDRESS, currentipaddr)
    if networkmod.IPADDRESS not in currentipaddr:
        #set IP address
        logger.warning(
            'Local Static IP address not in the list, Set Target IP address')
        networkmod.addIP("wlan0")
    else:
        logger.info('Local Statip IP address OK')

    # check master job has a next run"
    isok, datenextrun = SchedulerMod.get_next_run_time("master")
    if isok:
        datenow = datetime.utcnow()
        datenextrun = datenextrun.replace(tzinfo=None)
        print("Master Scheduler Next run ", datenextrun, " Now (UTC) ",
              datenow)
        if datenextrun > datenow:
            print("Masterschedule next RUN confirmed")
            logger.info('Heartbeat check , Master Scheduler OK')
        else:
            isok = False

    if not isok:
        print("No next run for master scheduler")
        logger.warning('Heartbeat check , Master Scheduler Interrupted')
        #emailmod.sendallmail("alert","Master Scheduler has been interrupted, try to restart scheduler")
        resetmastercallback()
        return True

    # check if there have been errors in Syslog
    if DEBUGMODE:
        logger.info('Heartbeat check , check errors in Syslog file')
        Errortextlist = debuggingmod.searchsyslogkeyword("error")
        if Errortextlist:
            print("found error in syslog")
            logger.warning(
                "ERROR: found error in syslog -------------------------")
            #send notification mail
            if debuggingmod.SENTERRORTEXT != Errortextlist[0]:
                emailmod.sendallmail("alert", "Error found in Syslog",
                                     Errortextlist)
                debuggingmod.SENTERRORTEXT = Errortextlist[0]
        else:
            print("No error found in syslog")
            logger.info('Heartbeat check , SYSLOG ok')

    # check if there have been errors in Schedulerlog
    if DEBUGMODE:
        logger.info('Heartbeat check , check errors in Sched log file')
        filename = "logfiles/apscheduler_hydrosystem.log"
        MYPATH = hardwaremod.get_path()
        filenameandpath = os.path.join(MYPATH, filename)
        Errortextlist = debuggingmod.searchLOGkeyword(filenameandpath, "error")
        if Errortextlist:
            print("found error in LOG ", filename)
            logger.warning(
                "ERROR: found error in LOG , %s -------------------------",
                filename)
            #send notification mail
            if debuggingmod.SENTERRORTEXT != Errortextlist[0]:
                emailmod.sendallmail("alert", "Error found in LOG",
                                     Errortextlist)
                debuggingmod.SENTERRORTEXT = Errortextlist[0]
        else:
            print("No error found in LOG", filename)
            logger.info('Heartbeat check , LOG ok')

    return True
Example #5
0
        cmd = hardwaremod.searchdata(hardwaremod.HW_INFO_NAME, hwname,
                                     hardwaremod.HW_CTRL_CMD)
        print "mail type ", cmd
        issent = send_email_main(address, title, cmd, mailtype, intromessage,
                                 bodytextlist)
        return issent
    else:
        print "No address specified"
        logger.error('No address specified')
        return False


if __name__ == '__main__':
    """
	prova email
	"""
    currentdate = datetime.datetime.now().strftime("%y-%m-%d,%H:%M")

    user = "******"
    pwd = "hydrosystem"
    recipient = "*****@*****.**"
    subject = "Today update " + currentdate
    body = "sono il testo prova 2"
    #send_email(user, pwd, recipient, subject, body)

    ipext = networkmod.get_external_ip()
    iplocal = networkmod.get_local_ip()
    htmlbody = create_html(ipext, iplocal, "5012")
    print htmlbody
    send_email_html(user, pwd, recipient, subject, htmlbody)
Example #6
0
def send_email_main(address,
                    title,
                    cmd,
                    mailtype,
                    intromessage,
                    bodytextlist=[]):

    # mailtype option
    # "report"
    # "alert"
    if mailtype == "report":
        starttitle = "Report:"
        showtable = True
        showpicture = True
        showlink = True

    elif mailtype == "alert":
        starttitle = "Alert:"
        showtable = False
        showpicture = False
        showlink = True

    elif mailtype == "info":
        starttitle = "Info:"
        showtable = False
        showpicture = False
        showlink = True

    currentdate = datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
    # got credentials here !
    user = emaildbmod.getaddress()
    pwd = emaildbmod.getpassword()
    recipient = address

    # check IP address
    iplocal = networkmod.get_local_ip()
    ipext = networkmod.EXTERNALIPADDR
    if ipext == "":
        logger.info(
            'Stored external IP address is empty, try to get it from network')
        ipext = networkmod.get_external_ip()

    print("Try to send mail")
    # subject of the mail
    subject = starttitle + " " + title + "  " + currentdate
    htmlbody = create_htmlopen()
    htmlbody = htmlbody + create_htmlintro(intromessage) + create_htmlbody(
        bodytextlist)

    if showlink:
        if ipext == "":
            print("No external IP address available")
            logger.error('Unable to get external IP address')
        else:
            port = str(networkmod.PUBLICPORT)
            if cmd == "mail+info+link":
                addresslist = []
                descriptionlist = []
                addresslist.append(iplocal)
                descriptionlist.append("Link for local Access")
                addresslist.append(ipext)
                descriptionlist.append("Link for Remote Access")
                customURL = networkmod.getCUSTOMURL()
                if not customURL == "":
                    addresslist.append(customURL)
                    descriptionlist.append("your Link")
                print("Mail url list ", addresslist)
                htmlbody = htmlbody + create_htmladdresses(
                    descriptionlist, addresslist, port)

    if showtable:
        # table with information
        matrixinfo = sensordbmod.sensorsysinfomatrix()
        htmlbody = htmlbody + create_htmlmatrix(matrixinfo)
        matrixinfo = actuatordbmod.sensorsysinfomatrix()
        htmlbody = htmlbody + create_htmlmatrix(matrixinfo)
    htmlbody = htmlbody + create_htmlclose()
    issent = send_email_html(user, pwd, recipient, subject, htmlbody,
                             showpicture)
    if (issent) and (showlink) and (ipext != ""):
        global IPEXTERNALSENT
        IPEXTERNALSENT = ipext
    return issent
Example #7
0
def heartbeat():
    print "start heartbeat check", " ", datetime.now()
    logger.info('Start heartbeat routine %s',
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    connectedssid = networkmod.connectedssid()
    connected = False
    if len(connectedssid) == 0:
        logger.warning(
            'Heartbeat check , no network connected -------------- try to connect'
        )
        print 'Heartbeat check , no network connected -------------- try to connect'
        connected = networkmod.connect_network()
    else:
        logger.info('Heartbeat check , Connected Wifi Network: %s ',
                    connectedssid[0])
        if connectedssid[0] == networkmod.localwifisystem:
            logger.info(
                'Heartbeat check , Configured as wifi access point, check if possible to connect to wifi network'
            )
            connected = networkmod.connect_network()
        else:
            reachgoogle = networkmod.check_internet_connection(3)

            if not reachgoogle:
                logger.warning(
                    'Heartbeat check , test ping not able to reach Google -------------- try to connect'
                )
                print 'Heartbeat check , no IP connection-------------- try to connect'
                connected = networkmod.connect_network()
            else:
                logger.info('Heartbeat check , wifi connection OK')
                print 'Heartbeat check , wifi connection OK'
                connected = True

    if connected:
        # Check if remote IP address is changed compared to previous communication and in such case resend the mail
        ipext = networkmod.get_external_ip()
        logger.info('Heartbeat check , Check IP address change %s', ipext)
        if ipext != "":
            if ipext != emailmod.IPEXTERNALSENT:
                print "Heartbeat check, IP address change detected. Send email with updated IP address"
                logger.info(
                    'Heartbeat check, IP address change detected. Send email with updated IP address'
                )
                emailmod.sendallmail(
                    "alert",
                    "System detected IP address change, below the updated links"
                )

        # Check current time is less than 60 second different from NTP information
        # try to get the clock from network
        print "check system clock"
        logger.info('Heartbeat check, check clock')
        networktime = clockmod.getNTPTime()
        logger.info('Heartbeat check , Network time NTP: %s ', networktime)
        systemtime = clockmod.readsystemdatetime()
        logger.info('Heartbeat check , System time NTP: %s ', systemtime)
        if not networktime == '':
            diffsec = clockmod.timediffinsec(networktime, systemtime)
            logger.info(
                'Heartbeat check , difference between system time and network time, diffsec =  %d ',
                diffsec)
            if diffsec > 60:
                print "Heartbeat check , warning difference between system time and network time >60 sec, diffsec = ", diffsec
                logger.warning(
                    'Heartbeat check , warning difference between system time and network time >60 sec, diffsec =  %d ',
                    diffsec)
                print "Heartbeat check , Apply network datetime to system"
                logger.warning(
                    'Heartbeat check , Apply network datetime to system ')
                clockmod.setHWclock(networktime)
                clockmod.setsystemclock(networktime)
            else:
                print "Heartbeat check , Clock OK"
                logger.info('Heartbeat check , Clock OK')
        else:
            print "not able to get network time"
            logger.warning('Heartbeat check , not able to get network time')
    else:
        print "not able to establish an internet connection"
        logger.warning("not able to establish an internet connection")

    # check master job has a next run"
    isok, datenextrun = SchedulerMod.get_next_run_time("master")
    if isok:
        datenow = datetime.utcnow()
        datenextrun = datenextrun.replace(tzinfo=None)
        print "Master Scheduler Next run ", datenextrun, " Now (UTC) ", datenow
        if datenextrun > datenow:
            print "Masterschedule next RUN confirmed"
            logger.info('Heartbeat check , Master Scheduler OK')
        else:
            isok = False

    if not isok:
        print "No next run for master scheduler"
        logger.warning('Heartbeat check , Master Scheduler Interrupted')
        emailmod.sendallmail(
            "alert",
            "Master Scheduler has been interrupted, try to restart scheduler")
        setmastercallback()

    return True
Example #8
0
def heartbeat():
	print "start heartbeat check", " " , datetime.now()
	logger.info('Start heartbeat routine %s', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
	connectedssid=networkmod.connectedssid()
	connected=False
	if len(connectedssid)==0:
		logger.warning('Heartbeat check , no network connected -------------- try to connect')
		print 'Heartbeat check , no network connected -------------- try to connect'
		connected=networkmod.connect_network()
	else:
		logger.info('Heartbeat check , Connected Wifi Network: %s ', connectedssid[0])
		if connectedssid[0]==networkmod.localwifisystem:
			logger.info('Heartbeat check , Configured as wifi access point, check if possible to connect to wifi network')
			connected=networkmod.connect_network()
		else:		
			reachgoogle=networkmod.check_internet_connection(1)

			if not reachgoogle:
				logger.warning('Heartbeat check , test ping not able to reach Google -------------- No action')
				print 'Heartbeat check , no IP connection-------------- No action'
				#connected=networkmod.connect_network() # use this in case you require the system to try connect wifi again in case no internet is reached
				connected=False
			else:
				logger.info('Heartbeat check , wifi connection OK')
				print 'Heartbeat check , wifi connection OK'
				connected=True			

	if connected:
		# Check if remote IP address is changed compared to previous communication and in such case resend the mail	
		ipext=networkmod.get_external_ip()
		logger.info('Heartbeat check , Check IP address change -%s- and previously sent -%s-', ipext , emailmod.IPEXTERNALSENT)
		if (ipext!=""):
			if (emailmod.IPEXTERNALSENT!=""):
				if ipext!=emailmod.IPEXTERNALSENT:
					print "Heartbeat check, IP address change detected. Send email with updated IP address"
					logger.info('Heartbeat check, IP address change detected. Send email with updated IP address')
					emailmod.sendallmail("alert","System detected IP address change, below the updated links")
				else:
					logger.info('Heartbeat check, IP address unchanged')	
			else:
				# first mail has not been sent succesfully of IPEXTERNALSENT was not available by the time
				print "System has been reconnected"
				logger.info("System has been reconnected, IPEXTERNALSENT was empty")
				emailmod.sendallmail("alert","System has been reconnected")							

		# Check current time is less than 60 second different from NTP information
		# try to get the clock from network
		print "check system clock"
		logger.info('Heartbeat check, check clock')
		networktime=clockmod.getNTPTime()
		logger.info('Heartbeat check , Network time NTP: %s ', networktime)
		systemtime=clockmod.readsystemdatetime()
		logger.info('Heartbeat check , System time NTP: %s ', systemtime)
		if not networktime=='':
			diffsec=clockmod.timediffinsec(networktime, systemtime)
			logger.info('Heartbeat check , difference between system time and network time, diffsec =  %d ', diffsec)
			if diffsec>60:
				print "Heartbeat check , warning difference between system time and network time >60 sec, diffsec = " , diffsec
				logger.warning('Heartbeat check , warning difference between system time and network time >60 sec, diffsec =  %d ', diffsec)
				print "Heartbeat check , Apply network datetime to system"
				logger.warning('Heartbeat check , Apply network datetime to system ')
				clockmod.setHWclock(networktime)
				clockmod.setsystemclock(networktime)
			else:
				print "Heartbeat check , Clock OK"
				logger.info('Heartbeat check , Clock OK')
		else:
			print "not able to get network time"
			logger.warning('Heartbeat check , not able to get network time')
	else:
		print "not able to establish an internet connection"
		logger.warning("not able to establish an internet connection")			
	
	# check master job has a next run"
	isok, datenextrun = SchedulerMod.get_next_run_time("master")
	if isok:
		datenow=datetime.utcnow()
		datenextrun = datenextrun.replace(tzinfo=None)
		print "Master Scheduler Next run " , datenextrun , " Now (UTC) ", datenow
		if datenextrun>datenow:
			print "Masterschedule next RUN confirmed"
			logger.info('Heartbeat check , Master Scheduler OK')
		else:
			isok=False
			
	if not isok:
		print "No next run for master scheduler"
		logger.warning('Heartbeat check , Master Scheduler Interrupted')
		emailmod.sendallmail("alert","Master Scheduler has been interrupted, try to restart scheduler")
		resetmastercallback()
	
	# check if there have been errors in Syslog
	if DEBUGMODE:
		Errortextlist=debuggingmod.searchsyslogkeyword("error")
		if Errortextlist:
			print "found error in syslog"
			logger.warning("ERROR: found error in syslog -------------------------")	
			#send notification mail 
			if debuggingmod.SENTERRORTEXT!=Errortextlist[0]:
				emailmod.sendallmail("alert","Error found in Syslog",Errortextlist)
				debuggingmod.SENTERRORTEXT=Errortextlist[0]
		else:
			print "No error found in syslog"
			logger.info('Heartbeat check , SYSLOG ok')		
			
	# check if there have been errors in Schedulerlog
	if DEBUGMODE:
		filename="logfiles/apscheduler_hydrosystem.log"
		MYPATH=hardwaremod.get_path()
		filenameandpath=os.path.join(MYPATH, filename)
		Errortextlist=debuggingmod.searchLOGkeyword(filenameandpath,"error")
		if Errortextlist:
			print "found error in LOG ",filename
			logger.warning("ERROR: found error in LOG , %s -------------------------",filename)	
			#send notification mail 
			if debuggingmod.SENTERRORTEXT!=Errortextlist[0]:
				emailmod.sendallmail("alert","Error found in LOG",Errortextlist)
				debuggingmod.SENTERRORTEXT=Errortextlist[0]
		else:
			print "No error found in LOG", filename
			logger.info('Heartbeat check , LOG ok')					
				
				
		
	return True
Example #9
0
def heartbeat():
    print "start heartbeat check", " ", datetime.now()
    logger.info('Start heartbeat routine %s',
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    connectedssid = networkmod.connectedssid()
    connected = False
    if len(connectedssid) == 0:
        logger.warning(
            'Heartbeat check , no network connected -------------- try to connect'
        )
        print 'Heartbeat check , no network connected -------------- try to connect'
        connected = networkmod.connect_network()
    else:
        logger.info('Heartbeat check , Connected Wifi Network: %s ',
                    connectedssid[0])
        if connectedssid[0] == networkmod.localwifisystem:
            logger.info(
                'Heartbeat check , Configured as wifi access point, check if possible to connect to wifi network'
            )
            connected = networkmod.connect_network()
        else:
            reachgoogle = networkmod.check_internet_connection(1)

            if not reachgoogle:
                logger.warning(
                    'Heartbeat check , test ping not able to reach Google -------------- No action'
                )
                print 'Heartbeat check , no IP connection-------------- No action'
                #connected=networkmod.connect_network() # use this in case you require the system to try connect wifi again in case no internet is reached
                connected = False
            else:
                logger.info('Heartbeat check , wifi connection OK')
                print 'Heartbeat check , wifi connection OK'
                connected = True

    if connected:
        # Check if remote IP address is changed compared to previous communication and in such case resend the mail
        ipext = networkmod.get_external_ip()
        logger.info(
            'Heartbeat check , Check IP address change -%s- and previously sent -%s-',
            ipext, emailmod.IPEXTERNALSENT)
        if (ipext != ""):
            if (emailmod.IPEXTERNALSENT != ""):
                if ipext != emailmod.IPEXTERNALSENT:
                    print "Heartbeat check, IP address change detected. Send email with updated IP address"
                    logger.info(
                        'Heartbeat check, IP address change detected. Send email with updated IP address'
                    )
                    emailmod.sendallmail(
                        "alert",
                        "System detected IP address change, below the updated links"
                    )
                else:
                    logger.info('Heartbeat check, IP address unchanged')
            else:
                # first mail has not been sent succesfully of IPEXTERNALSENT was not available by the time
                print "System has been reconnected"
                logger.info(
                    "System has been reconnected, IPEXTERNALSENT was empty")
                emailmod.sendallmail("alert", "System has been reconnected")

        # Check current time is less than 60 second different from NTP information
        # try to get the clock from network
        print "check system clock"
        logger.info('Heartbeat check, check clock')
        networktime = clockmod.getNTPTime()
        logger.info('Heartbeat check , Network time NTP: %s ', networktime)
        systemtime = clockmod.readsystemdatetime()
        logger.info('Heartbeat check , System time NTP: %s ', systemtime)
        if not networktime == '':
            diffsec = clockmod.timediffinsec(networktime, systemtime)
            logger.info(
                'Heartbeat check , difference between system time and network time, diffsec =  %d ',
                diffsec)
            if diffsec > 60:
                print "Heartbeat check , warning difference between system time and network time >60 sec, diffsec = ", diffsec
                logger.warning(
                    'Heartbeat check , warning difference between system time and network time >60 sec, diffsec =  %d ',
                    diffsec)
                print "Heartbeat check , Apply network datetime to system"
                logger.warning(
                    'Heartbeat check , Apply network datetime to system ')
                clockmod.setHWclock(networktime)
                clockmod.setsystemclock(networktime)
            else:
                print "Heartbeat check , Clock OK"
                logger.info('Heartbeat check , Clock OK')
        else:
            print "not able to get network time"
            logger.warning('Heartbeat check , not able to get network time')
    else:
        print "not able to establish an internet connection"
        logger.warning("not able to establish an internet connection")

    # check master job has a next run"
    isok, datenextrun = SchedulerMod.get_next_run_time("master")
    if isok:
        datenow = datetime.utcnow()
        datenextrun = datenextrun.replace(tzinfo=None)
        print "Master Scheduler Next run ", datenextrun, " Now (UTC) ", datenow
        if datenextrun > datenow:
            print "Masterschedule next RUN confirmed"
            logger.info('Heartbeat check , Master Scheduler OK')
        else:
            isok = False

    if not isok:
        print "No next run for master scheduler"
        logger.warning('Heartbeat check , Master Scheduler Interrupted')
        emailmod.sendallmail(
            "alert",
            "Master Scheduler has been interrupted, try to restart scheduler")
        resetmastercallback()

    # check if there have been errors in Syslog
    if DEBUGMODE:
        Errortextlist = debuggingmod.searchsyslogkeyword("error")
        if Errortextlist:
            print "found error in syslog"
            logger.warning(
                "ERROR: found error in syslog -------------------------")
            #send notification mail
            if debuggingmod.SENTERRORTEXT != Errortextlist[0]:
                emailmod.sendallmail("alert", "Error found in Syslog",
                                     Errortextlist)
                debuggingmod.SENTERRORTEXT = Errortextlist[0]
        else:
            print "No error found in syslog"
            logger.info('Heartbeat check , SYSLOG ok')

    # check if there have been errors in Schedulerlog
    if DEBUGMODE:
        filename = "logfiles/apscheduler_hydrosystem.log"
        MYPATH = hardwaremod.get_path()
        filenameandpath = os.path.join(MYPATH, filename)
        Errortextlist = debuggingmod.searchLOGkeyword(filenameandpath, "error")
        if Errortextlist:
            print "found error in LOG ", filename
            logger.warning(
                "ERROR: found error in LOG , %s -------------------------",
                filename)
            #send notification mail
            if debuggingmod.SENTERRORTEXT != Errortextlist[0]:
                emailmod.sendallmail("alert", "Error found in LOG",
                                     Errortextlist)
                debuggingmod.SENTERRORTEXT = Errortextlist[0]
        else:
            print "No error found in LOG", filename
            logger.info('Heartbeat check , LOG ok')

    return True
Example #10
0
		return issent
	else:
		print "No address specified"
		logger.error('No address specified')
		return False




if __name__ == '__main__':
	
	"""
	prova email
	"""
	currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M")
	
	user="******"
	pwd="hydrosystem"
	recipient="*****@*****.**"
	subject="Today update " + currentdate
	body="sono il testo prova 2"
	#send_email(user, pwd, recipient, subject, body)
	
	ipext=networkmod.get_external_ip()
	iplocal=networkmod.get_local_ip()
	htmlbody=create_html(ipext, iplocal, "5012")	
	print htmlbody
	send_email_html(user, pwd, recipient, subject, htmlbody)