diff --git a/CONF-IOB/Donati/1000_Pi1/IOB.cfg b/CONF-IOB/Donati/1000_Pi1/IOB.cfg new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1000_Pi1/IOB.cfg.donati b/CONF-IOB/Donati/1000_Pi1/IOB.cfg.donati new file mode 100644 index 0000000..ee07860 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/IOB.cfg.donati @@ -0,0 +1,24 @@ +[id] +idxMacchina = 1002 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 + diff --git a/CONF-IOB/Donati/1000_Pi1/IOB.cfg.steamware b/CONF-IOB/Donati/1000_Pi1/IOB.cfg.steamware new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/IOB.cfg.steamware @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1000_Pi1/MapoIOB b/CONF-IOB/Donati/1000_Pi1/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1000_Pi1/cleanPython.sh b/CONF-IOB/Donati/1000_Pi1/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1000_Pi1/crontab b/CONF-IOB/Donati/1000_Pi1/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1000_Pi1/logReboot.txt b/CONF-IOB/Donati/1000_Pi1/logReboot.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/logReboot.txt @@ -0,0 +1 @@ + diff --git a/CONF-IOB/Donati/1000_Pi1/logfile.txt b/CONF-IOB/Donati/1000_Pi1/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1000_Pi1/readParallela.py b/CONF-IOB/Donati/1000_Pi1/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1000_Pi1/sendReboot.py b/CONF-IOB/Donati/1000_Pi1/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1000_Pi1/sendRebootIOB b/CONF-IOB/Donati/1000_Pi1/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1000_Pi1/unix.py b/CONF-IOB/Donati/1000_Pi1/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi1/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1000_Pi3/IOB.cfg b/CONF-IOB/Donati/1000_Pi3/IOB.cfg new file mode 100644 index 0000000..ac044d0 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/IOB.cfg @@ -0,0 +1,35 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MP/IO/IOB/input/ +URLALIVE = http://10.74.82.219/MP/IO/IOB +URLENABLED = http://10.74.82.219/MP/IO/IOB/enabled/ +URLADV1 = ?valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.05 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.15 +NMAXSEND = 5 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 + +[blink] +MAX_COUNTER_BLINK = 30 +bit0 = 0 +bit1 = 0 +bit2 = 0 +bit3 = 1 +bit4 = 0 +bit5 = 0 +bit6 = 0 +bit7 = 0 diff --git a/CONF-IOB/Donati/1000_Pi3/IOB.cfg.donati b/CONF-IOB/Donati/1000_Pi3/IOB.cfg.donati new file mode 100644 index 0000000..a6408ee --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/IOB.cfg.donati @@ -0,0 +1,35 @@ +[id] +idxMacchina = 0 + +[web] +URLBASE = http://192.168.51.77/MP/IO/IOB/input/ +URLALIVE = http://192.168.51.77/MP/IO/IOB +URLENABLED = http://192.168.51.77/MP/IO/IOB/enabled/ +URLADV1 = ?valore= +URLREBO = http://192.168.51.77/MP/IO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.05 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.15 +NMAXSEND = 5 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 + +[blink] +MAX_COUNTER_BLINK = 30 +bit0 = 0 +bit1 = 0 +bit2 = 0 +bit3 = 1 +bit4 = 0 +bit5 = 0 +bit6 = 0 +bit7 = 0 diff --git a/CONF-IOB/Donati/1000_Pi3/IOB.cfg.steamware b/CONF-IOB/Donati/1000_Pi3/IOB.cfg.steamware new file mode 100644 index 0000000..ac044d0 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/IOB.cfg.steamware @@ -0,0 +1,35 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MP/IO/IOB/input/ +URLALIVE = http://10.74.82.219/MP/IO/IOB +URLENABLED = http://10.74.82.219/MP/IO/IOB/enabled/ +URLADV1 = ?valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.05 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.15 +NMAXSEND = 5 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 + +[blink] +MAX_COUNTER_BLINK = 30 +bit0 = 0 +bit1 = 0 +bit2 = 0 +bit3 = 1 +bit4 = 0 +bit5 = 0 +bit6 = 0 +bit7 = 0 diff --git a/CONF-IOB/Donati/1000_Pi3/MapoIOB b/CONF-IOB/Donati/1000_Pi3/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1000_Pi3/MapoIOB_logrot b/CONF-IOB/Donati/1000_Pi3/MapoIOB_logrot new file mode 100644 index 0000000..13410b9 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/MapoIOB_logrot @@ -0,0 +1,28 @@ +/var/log/MapoIOB.log { + size 8M + copytruncate + create 700 pi pi + dateext + rotate 100 + compress + maxage 366 + missingok +} +/var/log/logReboot.txt { + size 1M + copytruncate + create 700 pi pi + dateext + rotate 30 + compress + missingok +} +/var/log/logTemp.txt { + size 1M + copytruncate + create 700 pi pi + dateext + rotate 30 + compress + missingok +} diff --git a/CONF-IOB/Donati/1000_Pi3/checkAlive.sh b/CONF-IOB/Donati/1000_Pi3/checkAlive.sh new file mode 100644 index 0000000..aace73d --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB.log ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB.log' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1000_Pi3/cleanPython.sh b/CONF-IOB/Donati/1000_Pi3/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1000_Pi3/convertLogFile.py b/CONF-IOB/Donati/1000_Pi3/convertLogFile.py new file mode 100644 index 0000000..760c2a9 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/convertLogFile.py @@ -0,0 +1,46 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readFile v. 0.1 +# - single instance timer +# - invio multiplo x send eventi accodati +#--------------------------------------------------------------- +import os, sys +import argparse +#-------------------------------------------------------------- + +# gestione parser argomenti in input +parser = argparse.ArgumentParser() +parser.add_argument("inFile") +parser.add_argument("outFile") +args = parser.parse_args() + +#with open('logfile.txt', 'r') as inf, open('persMem.dat',"w") as outf: +with open(args.inFile, 'r') as inf, open(args.outFile,"w") as outf: + data = inf.readlines() + + lastDt = "" + lastMs = 0 + stepMs = 200 + + for line in data: + words = line.split() + if words[2] == 'queue': + # recupero dataOra + newDt = words[0].replace("-","") + words[1].replace(":","") + + # verifico se data/ora identica... + if (lastDt == newDt): + # --> aggiungo stepMs + lastMs += stepMs + else: + lastMs = 0 + + lastDt = newDt + + newDt = newDt + '{:03d}'.format(lastMs) #str(lastMs) + #print words[0].replace("-","") + words[1].replace(":","") + " | " + newDt + "\n" + + # print words + # outf.write(words[0].replace("-","") + words[1].replace(":","") + '#' + words[4].replace(">","") + '#' + words[5].replace("[","").replace("]","") +'\n') + outf.write(newDt + '#' + words[4].replace(">","") + '#' + words[5].replace("[","").replace("]","") +'\n') \ No newline at end of file diff --git a/CONF-IOB/Donati/1000_Pi3/crontab b/CONF-IOB/Donati/1000_Pi3/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1000_Pi3/install-RPI-IOB.sh b/CONF-IOB/Donati/1000_Pi3/install-RPI-IOB.sh new file mode 100644 index 0000000..7de1dc1 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/install-RPI-IOB.sh @@ -0,0 +1,51 @@ +#|/bin/bash + +#installa il necessario per RPI-3-IOB partendo dal contenuto della folder /home/pi/steamware + +#step 1: creo file di log nuovi +rm /var/log/log*.txt +rm /var/log/MapoIOB* +rm /home/pi/steamware/log*.txt + +touch /var/log/logReboot.txt +touch /var/log/logTemp.txt +touch /var/log/MapoIOB.log + +ln -sf /var/log/logReboot.txt /home/pi/steamware/logReboot.txt +ln -sf /var/log/logTemp.txt /home/pi/steamware/logTemp.txt +ln -sf /var/log/MapoIOB.log /home/pi/steamware/logfile.txt + +chown pi:pi /home/pi -R +chmod 666 /var/log/log*.txt +chmod 666 /var/log/MapoIOB.log + +#step 2: copio files in /usr/local/bin +cd /home/pi/steamware +chmod +x *.sh +cp *.sh /usr/local/bin/ + +#step 3: copio files x logrotate... +cd /home/pi/steamware +cp MapoIOB_logrot /etc/logrotate.d/ + +# step 4: copio target systemd in avvio... +cp -f sendRebootIOB /etc/init.d/sendRebootIOB +cp -f sendRebootIOB.service /etc/systemd/system/sendRebootIOB.service +echo "" +echo "-----------------------------------------------" +echo "Completare registrazione servizio avvio: digitare i seguenti comandi" +echo "systemctl enable sendRebootIOB" +echo "systemctl daemon-reload" +echo "systemctl status sendRebootIOB" +echo "-----------------------------------------------" +echo "" +echo "" +echo "" +echo "-----------------------------------------------" +echo "Infine creare voce crontab che salvi temperatura CPU/GPU ogni 20 minuti..." +echo "crontab -e" +echo "*/20 * * * * /usr/local/bin/saveTemp.sh" +echo "-----------------------------------------------" + + + diff --git a/CONF-IOB/Donati/1000_Pi3/logReboot.txt b/CONF-IOB/Donati/1000_Pi3/logReboot.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1000_Pi3/logfile.txt b/CONF-IOB/Donati/1000_Pi3/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1000_Pi3/mppar b/CONF-IOB/Donati/1000_Pi3/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1000_Pi3/mpser b/CONF-IOB/Donati/1000_Pi3/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1000_Pi3/readFile.py b/CONF-IOB/Donati/1000_Pi3/readFile.py new file mode 100644 index 0000000..887118d --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/readFile.py @@ -0,0 +1,152 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readFile v. 0.1 +# - single instance timer +# - invio multiplo x send eventi accodati + +#--------------------------------------------------------------- + +import time + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import Queue + +import argparse +#-------------------------------------------------------------- + +# gestione parser argomenti in input +parser = argparse.ArgumentParser() +parser.add_argument("memFile") +parser.add_argument("logFile") +args = parser.parse_args() + +#definizione variabili BASE +stepQueuePut=25000 +stepQueueGet=250 +NMAXSEND=500000 # limite invio file x fare prove... +idxMacchina = "2003" + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda illimitata" +Coda = Queue.Queue(0) + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(valore): + + try: + Coda.put(valore) + except Queue.Full: + logPro.error( "Queue full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#-------------------------------------------------------------- +# svuotaCoda x invio dati al server +def svuota_coda(): + + global NMAXSEND + + try: + if not Coda.empty(): + # invio SOLO i primi NMAXSEND eventi... SE minore del num eventi... + if NMAXSEND > Coda.qsize(): + NMAXSEND = Coda.qsize() + + + i = 0 + + with open(args.logFile,"w") as outf: + while i <= NMAXSEND: + if not Coda.empty(): + + # formatto dataOra corrente + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + + #prendo primo elemento dalla coda + resp = Coda.get() + + # recupero valori da elemento coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + + # registro chiamata + risposta + # outf.write(url + " --> " + answ3 + "\n") + + # incremento e controllo se mostrare output + i += 1 + if (i % stepQueueGet) == 0: + print "Inviati %d valori..." % i + + print "Inviati %d valori..." % i + except: + print "Errore in svuotamento coda!" + + +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + # NMAXSEND = config.getint ( 'time' , 'NMAXSEND' ) + # idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#--------------------------------------------------------------- + +dtCurr = datetime.utcnow().strftime('%H:%M:%S.%f')[:-3] +print "Inizio elaborazione: %s" % dtCurr + +# Leggo il file! +i = 0 +with open(args.memFile, 'r') as inf, open(args.logFile,"w") as outf: + data = inf.readlines() + + print "Trovate %d da processare..." % len(data) + +# leggo e metto in QUEUE... + for line in data: + accoda(line) + i += 1 + if (i % stepQueuePut) == 0: + print "Accodati %d valori..." % i + +print "Completata lettura file! %d righe accodate da trasmettere" % Coda.qsize() + +dtCurr = datetime.utcnow().strftime('%H:%M:%S.%f')[:-3] +print "Inizio invio: %s" % dtCurr + + +# chiamo procedura x svuotare coda... +svuota_coda() + +dtCurr = datetime.utcnow().strftime('%H:%M:%S.%f')[:-3] +print "Completato invio: %s" % dtCurr \ No newline at end of file diff --git a/CONF-IOB/Donati/1000_Pi3/readParallela.py b/CONF-IOB/Donati/1000_Pi3/readParallela.py new file mode 100644 index 0000000..a1e5489 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/readParallela.py @@ -0,0 +1,641 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 2.0 +# - single instance timer +# - invio multiplo x send eventi accodati +# - gestione segnali BLINKING + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue + +from array import * + +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# numero campioni filtraggio segnale ballerino +MAX_COUNTER_BLINK = 10 + +PROGRAM_NAME ="ReadPar IOB-pi v.2.0" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 +NMAXSEND = 5 # numero massimo di invii per singolo ciclo di svuotamento + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 9999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +# +# array per ingressi filtrati + +i_counters = array ( 'i',[0,0,0,0,0,0,0,0]) +B_blinking = array ( 'B',[0,0,0,0,0,0,0,0]) +B_previous = array ( 'B',[0,0,0,0,0,0,0,0]) +B_input = array ( 'B',[0,0,0,0,0,0,0,0]) +B_output = array ( 'B',[0,0,0,0,0,0,0,0]) + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda illimitata" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallelaFiltrata(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + + + try: + + if GPIO.input(in_0): + B_input[0] = 0 + else: + B_input[0] = 1 + + if GPIO.input(in_1): + B_input[1] = 0 + else: + B_input[1] = 1 + + if GPIO.input(in_2): + B_input[2] = 0 + else: + B_input[2] = 1 + + if GPIO.input(in_3): + B_input[3] = 0 + else: + B_input[3] = 1 + + if GPIO.input(in_4): + B_input[4] = 0 + else: + B_input[4] = 1 + + if GPIO.input(in_5): + B_input[5] = 0 + else: + B_input[5] = 1 + + if GPIO.input(in_6): + B_input[6] = 0 + else: + B_input[6] = 1 + + if GPIO.input(in_7): + B_input[7] = 0 + else: + B_input[7] = 1 + + + + #ciclo per ogni segnale + for i in xrange(8) : + + # print (i) + # se non blinking, copia ingresso + if ( B_blinking[i] == 0 ) : + B_output[i] = B_input[i] + else: + + # gestione segnale blinking + + # se fronte del segnale + if ( B_previous[i] != B_input[i] ) : + + B_previous[i] = B_input[i] + + # se fronte di salita + if ( B_input[i] == 1 ) : + # subito uscita = 1 + B_output[i] = 1 + i_counters[i] = MAX_COUNTER_BLINK + else : + # loggo che ho rilevato un blink... + if (LOGLEVEL > 5) : + logPro.info("Blink down on bit " + `i`) + else: + # no , segnale eguale a prima + # se input a 0 + if ( B_input[i] == 0 ) : + + # E CONTEGGIO IN CORSO + if ( i_counters[i] > 0 ) : + + i_counters[i] = i_counters[i] -1 + if ( i_counters[i] == 0 ) : + + B_output[i] = 0 + # loggo che ho CONFERMATO un cambio fronte... + if (LOGLEVEL > 5) : + logPro.info("END Blink on bit " + `i` ) + + #Rimettiamo insieme i bit + new_value = 0 + + if ( B_output[0] == 1 ) : + new_value = new_value + 1 + + if ( B_output[1] == 1 ) : + new_value = new_value + 2 + + if ( B_output[2] == 1 ) : + new_value = new_value + 4 + + if ( B_output[3] == 1 ) : + new_value = new_value + 8 + + if ( B_output[4] == 1 ) : + new_value = new_value + 16 + + if ( B_output[5] == 1 ) : + new_value = new_value + 32 + + if ( B_output[6] == 1 ) : + new_value = new_value + 64 + + if ( B_output[7] == 1 ) : + new_value = new_value + 128 + + current = hex( new_value ).replace ( "0x" , "" ).upper() + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Queue full" + `dtEve` + '#' + `value` + '#' + `cont` ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# svuotaCoda x invio dati al server +def svuota_coda(): + + global onLine + global sending + global timer_busy + global NMAXSEND + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # SAM 2016.12.23: modifica x invio FINO A nMaxSend ELEMENTI ad ogni ciclo di svuotamento + i = NMAXSEND + + while i >= 0: + if not Coda.empty(): + + # formatto dataOra corrente + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + + #prendo primo elemento dalla coda + resp = Coda.get() + + # recupero valori da elemento coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # tolgo 1 al contatore + i -= 1 + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 10000 # round robin 10000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + NMAXSEND = config.getint ( 'time' , 'NMAXSEND' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) + + B_blinking[0] = config.getint ( 'blink' , 'bit0' ) + B_blinking[1] = config.getint ( 'blink' , 'bit1' ) + B_blinking[2] = config.getint ( 'blink' , 'bit2' ) + B_blinking[3] = config.getint ( 'blink' , 'bit3' ) + B_blinking[4] = config.getint ( 'blink' , 'bit4' ) + B_blinking[5] = config.getint ( 'blink' , 'bit5' ) + B_blinking[6] = config.getint ( 'blink' , 'bit6' ) + B_blinking[7] = config.getint ( 'blink' , 'bit7' ) + + MAX_COUNTER_BLINK = config.getint ( 'blink' , 'MAX_COUNTER_BLINK' ) + + +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallelaFiltrata() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG diff --git a/CONF-IOB/Donati/1000_Pi3/readSeriale.py b/CONF-IOB/Donati/1000_Pi3/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1000_Pi3/saveTemp.sh b/CONF-IOB/Donati/1000_Pi3/saveTemp.sh new file mode 100644 index 0000000..a2cd2be --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/saveTemp.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +#salva la temperatura CPU e GPU su chiamata... + +# imposto logfile... +logFile="/var/log/logTemp.txt" + +cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp) +cpuTemp1=$(($cpuTemp0/1000)) +cpuTemp2=$(($cpuTemp0/100)) +cpuTempM=$(($cpuTemp2 % $cpuTemp1)) + +gpuTemp=`vcgencmd measure_temp` + +loadAvg=`cat /proc/loadavg` + +echo "$(date) | CPU: temp=$cpuTemp1.$cpuTempM ºC | GPU: $gpuTemp | LoadAvg: $loadAvg" >> $logFile diff --git a/CONF-IOB/Donati/1000_Pi3/sendReboot.py b/CONF-IOB/Donati/1000_Pi3/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1000_Pi3/sendRebootIOB b/CONF-IOB/Donati/1000_Pi3/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1000_Pi3/sendRebootIOB.service b/CONF-IOB/Donati/1000_Pi3/sendRebootIOB.service new file mode 100644 index 0000000..48e3690 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/sendRebootIOB.service @@ -0,0 +1,22 @@ +[Unit] +SourcePath=/etc/init.d/sendRebootIOB +Description=LSB: Steamware's IOB reboot signal +Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target shutdown.target +Wants=network-online.target +After=network.target network-online.target auditd.service +Conflicts=shutdown.target + +[Service] +Type=forking +Restart=no +TimeoutSec=5min +IgnoreSIGPIPE=no +KillMode=process +GuessMainPID=no +RemainAfterExit=yes +SysVStartPriority=2 +ExecStart=/etc/init.d/sendRebootIOB start +ExecStop=/etc/init.d/sendRebootIOB stop + +[Install] +WantedBy=multi-user.target diff --git a/CONF-IOB/Donati/1000_Pi3/setIobConf.sh b/CONF-IOB/Donati/1000_Pi3/setIobConf.sh new file mode 100644 index 0000000..30b4781 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/setIobConf.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# verifico se sia rete donati o rete steamware o offline... +netStatus=`cat /sys/class/net/eth0/operstate` +iaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1` + +cd /home/pi/steamware + +if [[ $netStatus != "up" ]] +then + echo "Siamo Offline, pagina demo!" +elif [[ $iaddr == "10.74.82"* ]] +then + cp IOB.cfg.steamware IOB.cfg -f + echo "Siamo in Steamware!" +elif [[ $iaddr == "192.168.51"* ]] +then + cp IOB.cfg.donati IOB.cfg -f + echo "Siamo a Passirano!" +else + echo "Siamo altrove, pagina demo!" +fi + +echo "$iaddr" + +chown pi:pi * \ No newline at end of file diff --git a/CONF-IOB/Donati/1000_Pi3/unix.py b/CONF-IOB/Donati/1000_Pi3/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1000_Pi3/unix.pyc b/CONF-IOB/Donati/1000_Pi3/unix.pyc new file mode 100644 index 0000000..e2189ce Binary files /dev/null and b/CONF-IOB/Donati/1000_Pi3/unix.pyc differ diff --git a/CONF-IOB/Donati/1000_Pi3/win.py b/CONF-IOB/Donati/1000_Pi3/win.py new file mode 100644 index 0000000..f679f60 --- /dev/null +++ b/CONF-IOB/Donati/1000_Pi3/win.py @@ -0,0 +1,32 @@ +import win32api +print " Running on WINDOWS\n" +import os +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + try: + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + except: + logga("Errore nel file WIN.PY per FD") + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + #fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + print " Dummy Method! Completa Lockfile\n" + except IOError: + return False + + return True +try: + if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) +except: + logga("if not lockfile NON RIUSCITO in file WIN.PY") + sys.exit(1) diff --git a/CONF-IOB/Donati/1000_Pi3/win.pyc b/CONF-IOB/Donati/1000_Pi3/win.pyc new file mode 100644 index 0000000..ae9a11e Binary files /dev/null and b/CONF-IOB/Donati/1000_Pi3/win.pyc differ diff --git a/CONF-IOB/Donati/1005_149/IOB.cfg b/CONF-IOB/Donati/1005_149/IOB.cfg new file mode 100644 index 0000000..c99d105 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1005_149/MapoIOB b/CONF-IOB/Donati/1005_149/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1005_149/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1005_149/MapoIOB_par b/CONF-IOB/Donati/1005_149/MapoIOB_par new file mode 100644 index 0000000..73410e5 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/MapoIOB_par @@ -0,0 +1,40 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1005_149/MapoIOB_ser b/CONF-IOB/Donati/1005_149/MapoIOB_ser new file mode 100644 index 0000000..514e7a4 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/MapoIOB_ser @@ -0,0 +1,40 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readSeriale" + cd /home/pi/steamware + /usr/bin/python ./readSeriale.py 2>&1 & + ;; + stop) + echo "Stopping readSeriale" + RS_PID=`ps auxwww | grep readSeriale.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1005_149/checkAlive.sh b/CONF-IOB/Donati/1005_149/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1005_149/cleanPython.sh b/CONF-IOB/Donati/1005_149/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1005_149/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1005_149/logfile.txt b/CONF-IOB/Donati/1005_149/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1005_149/mppar b/CONF-IOB/Donati/1005_149/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1005_149/mpser b/CONF-IOB/Donati/1005_149/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1005_149/python-serial_2.5-2.1_all.deb b/CONF-IOB/Donati/1005_149/python-serial_2.5-2.1_all.deb new file mode 100644 index 0000000..c52896c Binary files /dev/null and b/CONF-IOB/Donati/1005_149/python-serial_2.5-2.1_all.deb differ diff --git a/CONF-IOB/Donati/1005_149/readParallela.py b/CONF-IOB/Donati/1005_149/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1005_149/readSeriale.py b/CONF-IOB/Donati/1005_149/readSeriale.py new file mode 100644 index 0000000..909de6d --- /dev/null +++ b/CONF-IOB/Donati/1005_149/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1005_149/sendReboot.py b/CONF-IOB/Donati/1005_149/sendReboot.py new file mode 100644 index 0000000..814157a --- /dev/null +++ b/CONF-IOB/Donati/1005_149/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.6 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.6" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1005_149/unix.py b/CONF-IOB/Donati/1005_149/unix.py new file mode 100644 index 0000000..8167be6 --- /dev/null +++ b/CONF-IOB/Donati/1005_149/unix.py @@ -0,0 +1,30 @@ +import fcntl +import os + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1006_151/IOB.cfg b/CONF-IOB/Donati/1006_151/IOB.cfg new file mode 100644 index 0000000..3d03ee7 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1006 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1006_151/MapoIOB b/CONF-IOB/Donati/1006_151/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1006_151/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1006_151/MapoIOB.bak b/CONF-IOB/Donati/1006_151/MapoIOB.bak new file mode 100644 index 0000000..f3a37c4 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/MapoIOB.bak @@ -0,0 +1,40 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1006_151/checkAlive.sh b/CONF-IOB/Donati/1006_151/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1006_151/cleanPython.sh b/CONF-IOB/Donati/1006_151/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1006_151/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1006_151/old/IOB.cfg b/CONF-IOB/Donati/1006_151/old/IOB.cfg new file mode 100644 index 0000000..ba3ef61 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1006 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1006_151/old/readParallela.py b/CONF-IOB/Donati/1006_151/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1006_151/readParallela.py b/CONF-IOB/Donati/1006_151/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1006_151/sendReboot.py b/CONF-IOB/Donati/1006_151/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1006_151/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1006_151/unix.py b/CONF-IOB/Donati/1006_151/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1006_151/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1007_152/IOB.cfg b/CONF-IOB/Donati/1007_152/IOB.cfg new file mode 100644 index 0000000..0a79446 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1007 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1007_152/MapoIOB b/CONF-IOB/Donati/1007_152/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1007_152/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1007_152/checkAlive.sh b/CONF-IOB/Donati/1007_152/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1007_152/cleanPython.sh b/CONF-IOB/Donati/1007_152/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1007_152/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1007_152/logfile.txt b/CONF-IOB/Donati/1007_152/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1007_152/old/IOB.cfg b/CONF-IOB/Donati/1007_152/old/IOB.cfg new file mode 100644 index 0000000..39a8d52 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1007 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1007_152/old/readParallela.py b/CONF-IOB/Donati/1007_152/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1007_152/readParallela.py b/CONF-IOB/Donati/1007_152/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1007_152/sendReboot.py b/CONF-IOB/Donati/1007_152/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1007_152/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1007_152/unix.py b/CONF-IOB/Donati/1007_152/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1007_152/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1008_153/IOB.cfg b/CONF-IOB/Donati/1008_153/IOB.cfg new file mode 100644 index 0000000..421003b --- /dev/null +++ b/CONF-IOB/Donati/1008_153/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1008 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1008_153/MapoIOB b/CONF-IOB/Donati/1008_153/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1008_153/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1008_153/checkAlive.sh b/CONF-IOB/Donati/1008_153/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1008_153/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1008_153/cleanPython.sh b/CONF-IOB/Donati/1008_153/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1008_153/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1008_153/logfile.txt b/CONF-IOB/Donati/1008_153/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1008_153/old/IOB.cfg b/CONF-IOB/Donati/1008_153/old/IOB.cfg new file mode 100644 index 0000000..fd55446 --- /dev/null +++ b/CONF-IOB/Donati/1008_153/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1008 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1008_153/old/readParallela.py b/CONF-IOB/Donati/1008_153/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1008_153/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1008_153/readParallela.py b/CONF-IOB/Donati/1008_153/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1008_153/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1008_153/sendReboot.py b/CONF-IOB/Donati/1008_153/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1008_153/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1008_153/unix.py b/CONF-IOB/Donati/1008_153/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1008_153/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1009_154/IOB.cfg b/CONF-IOB/Donati/1009_154/IOB.cfg new file mode 100644 index 0000000..54b5db1 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1009 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1009_154/MapoIOB b/CONF-IOB/Donati/1009_154/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1009_154/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1009_154/checkAlive.sh b/CONF-IOB/Donati/1009_154/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1009_154/cleanPython.sh b/CONF-IOB/Donati/1009_154/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1009_154/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1009_154/logfile.txt b/CONF-IOB/Donati/1009_154/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1009_154/old/IOB.cfg b/CONF-IOB/Donati/1009_154/old/IOB.cfg new file mode 100644 index 0000000..072fa86 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1009 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1009_154/old/readParallela.py b/CONF-IOB/Donati/1009_154/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1009_154/readParallela.py b/CONF-IOB/Donati/1009_154/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1009_154/readSeriale.py b/CONF-IOB/Donati/1009_154/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1009_154/sendReboot.py b/CONF-IOB/Donati/1009_154/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1009_154/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1009_154/unix.py b/CONF-IOB/Donati/1009_154/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1009_154/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1010_155/IOB.cfg b/CONF-IOB/Donati/1010_155/IOB.cfg new file mode 100644 index 0000000..9e76f31 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1010 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1010_155/MapoIOB b/CONF-IOB/Donati/1010_155/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1010_155/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1010_155/checkAlive.sh b/CONF-IOB/Donati/1010_155/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1010_155/cleanPython.sh b/CONF-IOB/Donati/1010_155/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1010_155/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1010_155/logfile.txt b/CONF-IOB/Donati/1010_155/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1010_155/old/IOB.cfg b/CONF-IOB/Donati/1010_155/old/IOB.cfg new file mode 100644 index 0000000..9dc38c5 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1010 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1010_155/old/readParallela.py b/CONF-IOB/Donati/1010_155/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1010_155/readParallela.py b/CONF-IOB/Donati/1010_155/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1010_155/sendReboot.py b/CONF-IOB/Donati/1010_155/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1010_155/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1010_155/unix.py b/CONF-IOB/Donati/1010_155/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1010_155/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1011_156/IOB.cfg b/CONF-IOB/Donati/1011_156/IOB.cfg new file mode 100644 index 0000000..0851fb2 --- /dev/null +++ b/CONF-IOB/Donati/1011_156/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1011 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1011_156/MapoIOB b/CONF-IOB/Donati/1011_156/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1011_156/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1011_156/checkAlive.sh b/CONF-IOB/Donati/1011_156/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1011_156/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1011_156/logfile.txt b/CONF-IOB/Donati/1011_156/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1011_156/old/IOB.cfg b/CONF-IOB/Donati/1011_156/old/IOB.cfg new file mode 100644 index 0000000..e19a30e --- /dev/null +++ b/CONF-IOB/Donati/1011_156/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1011 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1011_156/old/readParallela.py b/CONF-IOB/Donati/1011_156/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1011_156/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1011_156/readParallela.py b/CONF-IOB/Donati/1011_156/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1011_156/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1011_156/sendReboot.py b/CONF-IOB/Donati/1011_156/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1011_156/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1011_156/unix.py b/CONF-IOB/Donati/1011_156/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1011_156/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1011_170/IOB.cfg b/CONF-IOB/Donati/1011_170/IOB.cfg new file mode 100644 index 0000000..aeab237 --- /dev/null +++ b/CONF-IOB/Donati/1011_170/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1011 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1011_170/MapoIOB b/CONF-IOB/Donati/1011_170/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1011_170/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1011_170/checkAlive.sh b/CONF-IOB/Donati/1011_170/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1011_170/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1011_170/cleanPython.sh b/CONF-IOB/Donati/1011_170/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1011_170/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1011_170/logfile.txt b/CONF-IOB/Donati/1011_170/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1011_170/old/IOB.cfg b/CONF-IOB/Donati/1011_170/old/IOB.cfg new file mode 100644 index 0000000..e19a30e --- /dev/null +++ b/CONF-IOB/Donati/1011_170/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1011 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1011_170/old/readParallela.py b/CONF-IOB/Donati/1011_170/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1011_170/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1011_170/readParallela.py b/CONF-IOB/Donati/1011_170/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1011_170/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1011_170/sendReboot.py b/CONF-IOB/Donati/1011_170/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1011_170/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1011_170/unix.py b/CONF-IOB/Donati/1011_170/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1011_170/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1012_157/IOB.cfg b/CONF-IOB/Donati/1012_157/IOB.cfg new file mode 100644 index 0000000..25071c7 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1012 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1012_157/MapoIOB b/CONF-IOB/Donati/1012_157/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1012_157/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1012_157/checkAlive.sh b/CONF-IOB/Donati/1012_157/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1012_157/cleanPython.sh b/CONF-IOB/Donati/1012_157/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1012_157/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1012_157/logfile.txt b/CONF-IOB/Donati/1012_157/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1012_157/old/IOB.cfg b/CONF-IOB/Donati/1012_157/old/IOB.cfg new file mode 100644 index 0000000..183aace --- /dev/null +++ b/CONF-IOB/Donati/1012_157/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1012 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1012_157/old/readParallela.py b/CONF-IOB/Donati/1012_157/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1012_157/readParallela.py b/CONF-IOB/Donati/1012_157/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1012_157/sendReboot.py b/CONF-IOB/Donati/1012_157/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1012_157/sendRebootIOB b/CONF-IOB/Donati/1012_157/sendRebootIOB new file mode 100644 index 0000000..fa28624 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/sendRebootIOB @@ -0,0 +1,29 @@ +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + echo "Starting sendReboot" + cd /home/pi/steamware + /usr/bin/python ./sendReboot.py 2>&1 & + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1012_157/unix.py b/CONF-IOB/Donati/1012_157/unix.py new file mode 100644 index 0000000..44cec83 --- /dev/null +++ b/CONF-IOB/Donati/1012_157/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os + + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1013_158/IOB.cfg b/CONF-IOB/Donati/1013_158/IOB.cfg new file mode 100644 index 0000000..ad18453 --- /dev/null +++ b/CONF-IOB/Donati/1013_158/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1013 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1013_158/MapoIOB b/CONF-IOB/Donati/1013_158/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1013_158/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1013_158/checkAlive.sh b/CONF-IOB/Donati/1013_158/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1013_158/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1013_158/cleanPython.sh b/CONF-IOB/Donati/1013_158/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1013_158/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1013_158/logfile.txt b/CONF-IOB/Donati/1013_158/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1013_158/old/IOB.cfg b/CONF-IOB/Donati/1013_158/old/IOB.cfg new file mode 100644 index 0000000..53061fb --- /dev/null +++ b/CONF-IOB/Donati/1013_158/old/IOB.cfg @@ -0,0 +1,19 @@ +[id] +idxMacchina = 1013 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.5 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 60 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1013_158/old/readParallela.py b/CONF-IOB/Donati/1013_158/old/readParallela.py new file mode 100644 index 0000000..7520b36 --- /dev/null +++ b/CONF-IOB/Donati/1013_158/old/readParallela.py @@ -0,0 +1,337 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.1" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + ##### convertire in HEX !!!! + + except: + pass + + return current + + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- +def avviaParallela(): + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logga("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1013_158/readParallela.py b/CONF-IOB/Donati/1013_158/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1013_158/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1013_158/sendReboot.py b/CONF-IOB/Donati/1013_158/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1013_158/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1013_158/unix.py b/CONF-IOB/Donati/1013_158/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1013_158/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1014_159/IOB.cfg b/CONF-IOB/Donati/1014_159/IOB.cfg new file mode 100644 index 0000000..6cc9f3e --- /dev/null +++ b/CONF-IOB/Donati/1014_159/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1014 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1014_159/MapoIOB b/CONF-IOB/Donati/1014_159/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1014_159/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1014_159/checkAlive.sh b/CONF-IOB/Donati/1014_159/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1014_159/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1014_159/cleanPython.sh b/CONF-IOB/Donati/1014_159/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1014_159/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1014_159/logfile.txt b/CONF-IOB/Donati/1014_159/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1014_159/readParallela.py b/CONF-IOB/Donati/1014_159/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1014_159/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1014_159/sendReboot.py b/CONF-IOB/Donati/1014_159/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1014_159/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1014_159/unix.py b/CONF-IOB/Donati/1014_159/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1014_159/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1015_162/IOB.cfg b/CONF-IOB/Donati/1015_162/IOB.cfg new file mode 100644 index 0000000..81cd593 --- /dev/null +++ b/CONF-IOB/Donati/1015_162/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1015 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1015_162/MapoIOB b/CONF-IOB/Donati/1015_162/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1015_162/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1015_162/checkAlive.sh b/CONF-IOB/Donati/1015_162/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1015_162/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1015_162/cleanPython.sh b/CONF-IOB/Donati/1015_162/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1015_162/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1015_162/logfile.txt b/CONF-IOB/Donati/1015_162/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1015_162/readParallela.py b/CONF-IOB/Donati/1015_162/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1015_162/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1015_162/sendReboot.py b/CONF-IOB/Donati/1015_162/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1015_162/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1015_162/sendRebootIOB b/CONF-IOB/Donati/1015_162/sendRebootIOB new file mode 100644 index 0000000..fa28624 --- /dev/null +++ b/CONF-IOB/Donati/1015_162/sendRebootIOB @@ -0,0 +1,29 @@ +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + echo "Starting sendReboot" + cd /home/pi/steamware + /usr/bin/python ./sendReboot.py 2>&1 & + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1015_162/unix.py b/CONF-IOB/Donati/1015_162/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1015_162/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1016_163/IOB.cfg b/CONF-IOB/Donati/1016_163/IOB.cfg new file mode 100644 index 0000000..4c98374 --- /dev/null +++ b/CONF-IOB/Donati/1016_163/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1016 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1016_163/MapoIOB b/CONF-IOB/Donati/1016_163/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1016_163/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1016_163/checkAlive.sh b/CONF-IOB/Donati/1016_163/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1016_163/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1016_163/cleanPython.sh b/CONF-IOB/Donati/1016_163/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1016_163/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1016_163/logfile.txt b/CONF-IOB/Donati/1016_163/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1016_163/readParallela.py b/CONF-IOB/Donati/1016_163/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1016_163/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1016_163/sendReboot.py b/CONF-IOB/Donati/1016_163/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1016_163/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1016_163/unix.py b/CONF-IOB/Donati/1016_163/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1016_163/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1017_164/IOB.cfg b/CONF-IOB/Donati/1017_164/IOB.cfg new file mode 100644 index 0000000..5407642 --- /dev/null +++ b/CONF-IOB/Donati/1017_164/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1017 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1017_164/MapoIOB b/CONF-IOB/Donati/1017_164/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1017_164/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1017_164/checkAlive.sh b/CONF-IOB/Donati/1017_164/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1017_164/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1017_164/cleanPython.sh b/CONF-IOB/Donati/1017_164/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1017_164/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1017_164/logfile.txt b/CONF-IOB/Donati/1017_164/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1017_164/readParallela.py b/CONF-IOB/Donati/1017_164/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1017_164/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1017_164/sendReboot.py b/CONF-IOB/Donati/1017_164/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1017_164/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1017_164/unix.py b/CONF-IOB/Donati/1017_164/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1017_164/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1018_168/IOB.cfg b/CONF-IOB/Donati/1018_168/IOB.cfg new file mode 100644 index 0000000..a86e699 --- /dev/null +++ b/CONF-IOB/Donati/1018_168/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1018 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1018_168/MapoIOB b/CONF-IOB/Donati/1018_168/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1018_168/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1018_168/checkAlive.sh b/CONF-IOB/Donati/1018_168/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1018_168/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1018_168/cleanPython.sh b/CONF-IOB/Donati/1018_168/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1018_168/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1018_168/logfile.txt b/CONF-IOB/Donati/1018_168/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1018_168/readParallela.py b/CONF-IOB/Donati/1018_168/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1018_168/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1018_168/sendReboot.py b/CONF-IOB/Donati/1018_168/sendReboot.py new file mode 100644 index 0000000..814157a --- /dev/null +++ b/CONF-IOB/Donati/1018_168/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.6 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.6" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1018_168/unix.py b/CONF-IOB/Donati/1018_168/unix.py new file mode 100644 index 0000000..8167be6 --- /dev/null +++ b/CONF-IOB/Donati/1018_168/unix.py @@ -0,0 +1,30 @@ +import fcntl +import os + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1019_169/IOB.cfg b/CONF-IOB/Donati/1019_169/IOB.cfg new file mode 100644 index 0000000..b6e5e45 --- /dev/null +++ b/CONF-IOB/Donati/1019_169/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1019 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1019_169/MapoIOB b/CONF-IOB/Donati/1019_169/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1019_169/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1019_169/checkAlive.sh b/CONF-IOB/Donati/1019_169/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1019_169/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1019_169/cleanPython.sh b/CONF-IOB/Donati/1019_169/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1019_169/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1019_169/logfile.txt b/CONF-IOB/Donati/1019_169/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1019_169/readParallela.py b/CONF-IOB/Donati/1019_169/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1019_169/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1019_169/sendReboot.py b/CONF-IOB/Donati/1019_169/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1019_169/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1019_169/unix.py b/CONF-IOB/Donati/1019_169/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1019_169/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1020_165/IOB.cfg b/CONF-IOB/Donati/1020_165/IOB.cfg new file mode 100644 index 0000000..77fbcfd --- /dev/null +++ b/CONF-IOB/Donati/1020_165/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1020 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1020_165/MapoIOB b/CONF-IOB/Donati/1020_165/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1020_165/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1020_165/checkAlive.sh b/CONF-IOB/Donati/1020_165/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1020_165/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1020_165/cleanPython.sh b/CONF-IOB/Donati/1020_165/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1020_165/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1020_165/logfile.txt b/CONF-IOB/Donati/1020_165/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1020_165/readParallela.py b/CONF-IOB/Donati/1020_165/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1020_165/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1020_165/sendReboot.py b/CONF-IOB/Donati/1020_165/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1020_165/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1020_165/unix.py b/CONF-IOB/Donati/1020_165/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1020_165/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1021_167/IOB.cfg b/CONF-IOB/Donati/1021_167/IOB.cfg new file mode 100644 index 0000000..d1e0658 --- /dev/null +++ b/CONF-IOB/Donati/1021_167/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1021 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1021_167/MapoIOB b/CONF-IOB/Donati/1021_167/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1021_167/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1021_167/checkAlive.sh b/CONF-IOB/Donati/1021_167/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1021_167/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1021_167/cleanPython.sh b/CONF-IOB/Donati/1021_167/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1021_167/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1021_167/logfile.txt b/CONF-IOB/Donati/1021_167/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1021_167/readParallela.py b/CONF-IOB/Donati/1021_167/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1021_167/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1021_167/sendReboot.py b/CONF-IOB/Donati/1021_167/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1021_167/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1021_167/unix.py b/CONF-IOB/Donati/1021_167/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1021_167/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1022_166/IOB.cfg b/CONF-IOB/Donati/1022_166/IOB.cfg new file mode 100644 index 0000000..8833201 --- /dev/null +++ b/CONF-IOB/Donati/1022_166/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1022 + +[web] +URLBASE = http://192.168.51.71/MPIO2/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO2/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO2/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO2/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1022_166/MapoIOB b/CONF-IOB/Donati/1022_166/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1022_166/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1022_166/checkAlive.sh b/CONF-IOB/Donati/1022_166/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1022_166/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1022_166/cleanPython.sh b/CONF-IOB/Donati/1022_166/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1022_166/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1022_166/logfile.txt b/CONF-IOB/Donati/1022_166/logfile.txt new file mode 100644 index 0000000..e69de29 diff --git a/CONF-IOB/Donati/1022_166/readParallela.py b/CONF-IOB/Donati/1022_166/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1022_166/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1022_166/sendReboot.py b/CONF-IOB/Donati/1022_166/sendReboot.py new file mode 100644 index 0000000..36dd316 --- /dev/null +++ b/CONF-IOB/Donati/1022_166/sendReboot.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.1 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME ="SendReboot IOB-pi v.1.3" + +# DA FILE CONF +idxMacchina = "99" + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + + try: + url = URLREBO + idxMacchina + urllib.urlopen ( url ) + except: + logging.info ( "NETWORK:Errore http-no com rete-timeout per url: " + url ) + print "Url aforte" , url + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma" + PROGRAM_NAME) + + +# lettura file configurazione + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + + +chiamaUrl() + diff --git a/CONF-IOB/Donati/1022_166/unix.py b/CONF-IOB/Donati/1022_166/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1022_166/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1024_177/IOB.cfg b/CONF-IOB/Donati/1024_177/IOB.cfg new file mode 100644 index 0000000..1c88599 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1024 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1024_177/IOB.cfg.donati b/CONF-IOB/Donati/1024_177/IOB.cfg.donati new file mode 100644 index 0000000..1c88599 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/IOB.cfg.donati @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1024 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1024_177/IOB.cfg.steamware b/CONF-IOB/Donati/1024_177/IOB.cfg.steamware new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1024_177/IOB.cfg.steamware @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1024_177/MapoIOB b/CONF-IOB/Donati/1024_177/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1024_177/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1024_177/checkAlive.sh b/CONF-IOB/Donati/1024_177/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1024_177/cleanPython.sh b/CONF-IOB/Donati/1024_177/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1024_177/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1024_177/crontab b/CONF-IOB/Donati/1024_177/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1024_177/install-RPI-IOB.sh b/CONF-IOB/Donati/1024_177/install-RPI-IOB.sh new file mode 100644 index 0000000..19491e1 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/install-RPI-IOB.sh @@ -0,0 +1,47 @@ +#|/bin/bash + +#installa il necessario per RPI-3-IOB partendo dal contenuto della folder /home/pi/steamware + +#step 1: creo file di log nuovi +rm /var/log/log*.txt +rm /var/log/MapoIOB +rm /home/pi/steamware/log*.txt + +touch /var/log/logReboot.txt +touch /var/log/logTemp.txt +touch /var/log/MapoIOB + +ln -sf /var/log/logReboot.txt /home/pi/steamware/logReboot.txt +ln -sf /var/log/logTemp.txt /home/pi/steamware/logTemp.txt +ln -sf /var/log/MapoIOB /home/pi/steamware/logfile.txt + +chown pi:pi /home/pi -R +chmod 666 /var/log/log*.txt +chmod 666 /var/log/MapoIOB + +#step 2: copio files in /usr/local/bin +cd /home/pi/steamware +chmod +x *.sh +cp *.sh /usr/local/bin/ + +# step 3: copio target systemd in avvio... +cp -f sendRebootIOB /etc/init.d/sendRebootIOB +cp -f sendRebootIOB.service /etc/systemd/system/sendRebootIOB.service +echo "" +echo "-----------------------------------------------" +echo "Completare registrazione servizio avvio: digitare i seguenti comandi" +echo "systemctl enable sendRebootIOB" +echo "systemctl daemon-reload" +echo "systemctl status sendRebootIOB" +echo "-----------------------------------------------" +echo "" +echo "" +echo "" +echo "-----------------------------------------------" +echo "Infine creare voce crontab che salvi temperatura CPU/GPU ogni 20 minuti..." +echo "crontab -e" +echo "*/20 * * * * /usr/local/bin/saveTemp.sh" +echo "-----------------------------------------------" + + + diff --git a/CONF-IOB/Donati/1024_177/mppar b/CONF-IOB/Donati/1024_177/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1024_177/mpser b/CONF-IOB/Donati/1024_177/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1024_177/readParallela.py b/CONF-IOB/Donati/1024_177/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1024_177/readSeriale.py b/CONF-IOB/Donati/1024_177/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1024_177/saveTemp.sh b/CONF-IOB/Donati/1024_177/saveTemp.sh new file mode 100644 index 0000000..a2cd2be --- /dev/null +++ b/CONF-IOB/Donati/1024_177/saveTemp.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +#salva la temperatura CPU e GPU su chiamata... + +# imposto logfile... +logFile="/var/log/logTemp.txt" + +cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp) +cpuTemp1=$(($cpuTemp0/1000)) +cpuTemp2=$(($cpuTemp0/100)) +cpuTempM=$(($cpuTemp2 % $cpuTemp1)) + +gpuTemp=`vcgencmd measure_temp` + +loadAvg=`cat /proc/loadavg` + +echo "$(date) | CPU: temp=$cpuTemp1.$cpuTempM ºC | GPU: $gpuTemp | LoadAvg: $loadAvg" >> $logFile diff --git a/CONF-IOB/Donati/1024_177/sendReboot.py b/CONF-IOB/Donati/1024_177/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1024_177/sendRebootIOB b/CONF-IOB/Donati/1024_177/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1024_177/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1024_177/sendRebootIOB.service b/CONF-IOB/Donati/1024_177/sendRebootIOB.service new file mode 100644 index 0000000..48e3690 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/sendRebootIOB.service @@ -0,0 +1,22 @@ +[Unit] +SourcePath=/etc/init.d/sendRebootIOB +Description=LSB: Steamware's IOB reboot signal +Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target shutdown.target +Wants=network-online.target +After=network.target network-online.target auditd.service +Conflicts=shutdown.target + +[Service] +Type=forking +Restart=no +TimeoutSec=5min +IgnoreSIGPIPE=no +KillMode=process +GuessMainPID=no +RemainAfterExit=yes +SysVStartPriority=2 +ExecStart=/etc/init.d/sendRebootIOB start +ExecStop=/etc/init.d/sendRebootIOB stop + +[Install] +WantedBy=multi-user.target diff --git a/CONF-IOB/Donati/1024_177/setIobConf.sh b/CONF-IOB/Donati/1024_177/setIobConf.sh new file mode 100644 index 0000000..30b4781 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/setIobConf.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# verifico se sia rete donati o rete steamware o offline... +netStatus=`cat /sys/class/net/eth0/operstate` +iaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1` + +cd /home/pi/steamware + +if [[ $netStatus != "up" ]] +then + echo "Siamo Offline, pagina demo!" +elif [[ $iaddr == "10.74.82"* ]] +then + cp IOB.cfg.steamware IOB.cfg -f + echo "Siamo in Steamware!" +elif [[ $iaddr == "192.168.51"* ]] +then + cp IOB.cfg.donati IOB.cfg -f + echo "Siamo a Passirano!" +else + echo "Siamo altrove, pagina demo!" +fi + +echo "$iaddr" + +chown pi:pi * \ No newline at end of file diff --git a/CONF-IOB/Donati/1024_177/test.py b/CONF-IOB/Donati/1024_177/test.py new file mode 100644 index 0000000..3145cbe --- /dev/null +++ b/CONF-IOB/Donati/1024_177/test.py @@ -0,0 +1,31 @@ +import logging + +# set up logging to file - see previous section for more details +logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + datefmt='%m-%d %H:%M', + filename='test.log', + filemode='w') +# define a Handler which writes INFO messages or higher to the sys.stderr +console = logging.StreamHandler() +console.setLevel(logging.INFO) +# set a format which is simpler for console use +formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') +# tell the handler to use this format +console.setFormatter(formatter) +# add the handler to the root logger +logging.getLogger('').addHandler(console) + +# Now, we can log to the root logger, or any other logger. First the root... +logging.info('Jackdaws love my big sphinx of quartz.') + +# Now, define a couple of other loggers which might represent areas in your +# application: + +logger1 = logging.getLogger('myapp.area1') +logger2 = logging.getLogger('myapp.area2') + +logger1.debug('Quick zephyrs blow, vexing daft Jim.') +logger1.info('How quickly daft jumping zebras vex.') +logger2.warning('Jail zesty vixen who grabbed pay from quack.') +logger2.error('The five boxing wizards jump quickly.') diff --git a/CONF-IOB/Donati/1024_177/unix.py b/CONF-IOB/Donati/1024_177/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1024_177/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1024_177/unix.pyc b/CONF-IOB/Donati/1024_177/unix.pyc new file mode 100644 index 0000000..a42c57d Binary files /dev/null and b/CONF-IOB/Donati/1024_177/unix.pyc differ diff --git a/CONF-IOB/Donati/1024_177/win.py b/CONF-IOB/Donati/1024_177/win.py new file mode 100644 index 0000000..f679f60 --- /dev/null +++ b/CONF-IOB/Donati/1024_177/win.py @@ -0,0 +1,32 @@ +import win32api +print " Running on WINDOWS\n" +import os +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + try: + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + except: + logga("Errore nel file WIN.PY per FD") + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + #fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + print " Dummy Method! Completa Lockfile\n" + except IOError: + return False + + return True +try: + if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) +except: + logga("if not lockfile NON RIUSCITO in file WIN.PY") + sys.exit(1) diff --git a/CONF-IOB/Donati/1024_177/win.pyc b/CONF-IOB/Donati/1024_177/win.pyc new file mode 100644 index 0000000..ae9a11e Binary files /dev/null and b/CONF-IOB/Donati/1024_177/win.pyc differ diff --git a/CONF-IOB/Donati/1025_178/IOB.cfg b/CONF-IOB/Donati/1025_178/IOB.cfg new file mode 100644 index 0000000..cc79c66 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1025 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1025_178/IOB.cfg.donati b/CONF-IOB/Donati/1025_178/IOB.cfg.donati new file mode 100644 index 0000000..cc79c66 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/IOB.cfg.donati @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1025 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1025_178/IOB.cfg.steamware b/CONF-IOB/Donati/1025_178/IOB.cfg.steamware new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1025_178/IOB.cfg.steamware @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1025_178/MapoIOB b/CONF-IOB/Donati/1025_178/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1025_178/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1025_178/checkAlive.sh b/CONF-IOB/Donati/1025_178/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1025_178/cleanPython.sh b/CONF-IOB/Donati/1025_178/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1025_178/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1025_178/crontab b/CONF-IOB/Donati/1025_178/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1025_178/install-RPI-IOB.sh b/CONF-IOB/Donati/1025_178/install-RPI-IOB.sh new file mode 100644 index 0000000..19491e1 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/install-RPI-IOB.sh @@ -0,0 +1,47 @@ +#|/bin/bash + +#installa il necessario per RPI-3-IOB partendo dal contenuto della folder /home/pi/steamware + +#step 1: creo file di log nuovi +rm /var/log/log*.txt +rm /var/log/MapoIOB +rm /home/pi/steamware/log*.txt + +touch /var/log/logReboot.txt +touch /var/log/logTemp.txt +touch /var/log/MapoIOB + +ln -sf /var/log/logReboot.txt /home/pi/steamware/logReboot.txt +ln -sf /var/log/logTemp.txt /home/pi/steamware/logTemp.txt +ln -sf /var/log/MapoIOB /home/pi/steamware/logfile.txt + +chown pi:pi /home/pi -R +chmod 666 /var/log/log*.txt +chmod 666 /var/log/MapoIOB + +#step 2: copio files in /usr/local/bin +cd /home/pi/steamware +chmod +x *.sh +cp *.sh /usr/local/bin/ + +# step 3: copio target systemd in avvio... +cp -f sendRebootIOB /etc/init.d/sendRebootIOB +cp -f sendRebootIOB.service /etc/systemd/system/sendRebootIOB.service +echo "" +echo "-----------------------------------------------" +echo "Completare registrazione servizio avvio: digitare i seguenti comandi" +echo "systemctl enable sendRebootIOB" +echo "systemctl daemon-reload" +echo "systemctl status sendRebootIOB" +echo "-----------------------------------------------" +echo "" +echo "" +echo "" +echo "-----------------------------------------------" +echo "Infine creare voce crontab che salvi temperatura CPU/GPU ogni 20 minuti..." +echo "crontab -e" +echo "*/20 * * * * /usr/local/bin/saveTemp.sh" +echo "-----------------------------------------------" + + + diff --git a/CONF-IOB/Donati/1025_178/mppar b/CONF-IOB/Donati/1025_178/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1025_178/mpser b/CONF-IOB/Donati/1025_178/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1025_178/readParallela.py b/CONF-IOB/Donati/1025_178/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1025_178/readSeriale.py b/CONF-IOB/Donati/1025_178/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1025_178/saveTemp.sh b/CONF-IOB/Donati/1025_178/saveTemp.sh new file mode 100644 index 0000000..a2cd2be --- /dev/null +++ b/CONF-IOB/Donati/1025_178/saveTemp.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +#salva la temperatura CPU e GPU su chiamata... + +# imposto logfile... +logFile="/var/log/logTemp.txt" + +cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp) +cpuTemp1=$(($cpuTemp0/1000)) +cpuTemp2=$(($cpuTemp0/100)) +cpuTempM=$(($cpuTemp2 % $cpuTemp1)) + +gpuTemp=`vcgencmd measure_temp` + +loadAvg=`cat /proc/loadavg` + +echo "$(date) | CPU: temp=$cpuTemp1.$cpuTempM ºC | GPU: $gpuTemp | LoadAvg: $loadAvg" >> $logFile diff --git a/CONF-IOB/Donati/1025_178/sendReboot.py b/CONF-IOB/Donati/1025_178/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1025_178/sendRebootIOB b/CONF-IOB/Donati/1025_178/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1025_178/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1025_178/sendRebootIOB.service b/CONF-IOB/Donati/1025_178/sendRebootIOB.service new file mode 100644 index 0000000..48e3690 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/sendRebootIOB.service @@ -0,0 +1,22 @@ +[Unit] +SourcePath=/etc/init.d/sendRebootIOB +Description=LSB: Steamware's IOB reboot signal +Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target shutdown.target +Wants=network-online.target +After=network.target network-online.target auditd.service +Conflicts=shutdown.target + +[Service] +Type=forking +Restart=no +TimeoutSec=5min +IgnoreSIGPIPE=no +KillMode=process +GuessMainPID=no +RemainAfterExit=yes +SysVStartPriority=2 +ExecStart=/etc/init.d/sendRebootIOB start +ExecStop=/etc/init.d/sendRebootIOB stop + +[Install] +WantedBy=multi-user.target diff --git a/CONF-IOB/Donati/1025_178/setIobConf.sh b/CONF-IOB/Donati/1025_178/setIobConf.sh new file mode 100644 index 0000000..30b4781 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/setIobConf.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# verifico se sia rete donati o rete steamware o offline... +netStatus=`cat /sys/class/net/eth0/operstate` +iaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1` + +cd /home/pi/steamware + +if [[ $netStatus != "up" ]] +then + echo "Siamo Offline, pagina demo!" +elif [[ $iaddr == "10.74.82"* ]] +then + cp IOB.cfg.steamware IOB.cfg -f + echo "Siamo in Steamware!" +elif [[ $iaddr == "192.168.51"* ]] +then + cp IOB.cfg.donati IOB.cfg -f + echo "Siamo a Passirano!" +else + echo "Siamo altrove, pagina demo!" +fi + +echo "$iaddr" + +chown pi:pi * \ No newline at end of file diff --git a/CONF-IOB/Donati/1025_178/test.py b/CONF-IOB/Donati/1025_178/test.py new file mode 100644 index 0000000..3145cbe --- /dev/null +++ b/CONF-IOB/Donati/1025_178/test.py @@ -0,0 +1,31 @@ +import logging + +# set up logging to file - see previous section for more details +logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + datefmt='%m-%d %H:%M', + filename='test.log', + filemode='w') +# define a Handler which writes INFO messages or higher to the sys.stderr +console = logging.StreamHandler() +console.setLevel(logging.INFO) +# set a format which is simpler for console use +formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') +# tell the handler to use this format +console.setFormatter(formatter) +# add the handler to the root logger +logging.getLogger('').addHandler(console) + +# Now, we can log to the root logger, or any other logger. First the root... +logging.info('Jackdaws love my big sphinx of quartz.') + +# Now, define a couple of other loggers which might represent areas in your +# application: + +logger1 = logging.getLogger('myapp.area1') +logger2 = logging.getLogger('myapp.area2') + +logger1.debug('Quick zephyrs blow, vexing daft Jim.') +logger1.info('How quickly daft jumping zebras vex.') +logger2.warning('Jail zesty vixen who grabbed pay from quack.') +logger2.error('The five boxing wizards jump quickly.') diff --git a/CONF-IOB/Donati/1025_178/unix.py b/CONF-IOB/Donati/1025_178/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1025_178/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1025_178/unix.pyc b/CONF-IOB/Donati/1025_178/unix.pyc new file mode 100644 index 0000000..a42c57d Binary files /dev/null and b/CONF-IOB/Donati/1025_178/unix.pyc differ diff --git a/CONF-IOB/Donati/1025_178/win.py b/CONF-IOB/Donati/1025_178/win.py new file mode 100644 index 0000000..f679f60 --- /dev/null +++ b/CONF-IOB/Donati/1025_178/win.py @@ -0,0 +1,32 @@ +import win32api +print " Running on WINDOWS\n" +import os +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + try: + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + except: + logga("Errore nel file WIN.PY per FD") + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + #fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + print " Dummy Method! Completa Lockfile\n" + except IOError: + return False + + return True +try: + if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) +except: + logga("if not lockfile NON RIUSCITO in file WIN.PY") + sys.exit(1) diff --git a/CONF-IOB/Donati/1025_178/win.pyc b/CONF-IOB/Donati/1025_178/win.pyc new file mode 100644 index 0000000..ae9a11e Binary files /dev/null and b/CONF-IOB/Donati/1025_178/win.pyc differ diff --git a/CONF-IOB/Donati/1026_180/IOB.cfg b/CONF-IOB/Donati/1026_180/IOB.cfg new file mode 100644 index 0000000..18a11f3 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1026 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1026_180/IOB.cfg.donati b/CONF-IOB/Donati/1026_180/IOB.cfg.donati new file mode 100644 index 0000000..18a11f3 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/IOB.cfg.donati @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1026 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1026_180/IOB.cfg.steamware b/CONF-IOB/Donati/1026_180/IOB.cfg.steamware new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1026_180/IOB.cfg.steamware @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1026_180/MapoIOB b/CONF-IOB/Donati/1026_180/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1026_180/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1026_180/checkAlive.sh b/CONF-IOB/Donati/1026_180/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1026_180/cleanPython.sh b/CONF-IOB/Donati/1026_180/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1026_180/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1026_180/crontab b/CONF-IOB/Donati/1026_180/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1026_180/install-RPI-IOB.sh b/CONF-IOB/Donati/1026_180/install-RPI-IOB.sh new file mode 100644 index 0000000..19491e1 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/install-RPI-IOB.sh @@ -0,0 +1,47 @@ +#|/bin/bash + +#installa il necessario per RPI-3-IOB partendo dal contenuto della folder /home/pi/steamware + +#step 1: creo file di log nuovi +rm /var/log/log*.txt +rm /var/log/MapoIOB +rm /home/pi/steamware/log*.txt + +touch /var/log/logReboot.txt +touch /var/log/logTemp.txt +touch /var/log/MapoIOB + +ln -sf /var/log/logReboot.txt /home/pi/steamware/logReboot.txt +ln -sf /var/log/logTemp.txt /home/pi/steamware/logTemp.txt +ln -sf /var/log/MapoIOB /home/pi/steamware/logfile.txt + +chown pi:pi /home/pi -R +chmod 666 /var/log/log*.txt +chmod 666 /var/log/MapoIOB + +#step 2: copio files in /usr/local/bin +cd /home/pi/steamware +chmod +x *.sh +cp *.sh /usr/local/bin/ + +# step 3: copio target systemd in avvio... +cp -f sendRebootIOB /etc/init.d/sendRebootIOB +cp -f sendRebootIOB.service /etc/systemd/system/sendRebootIOB.service +echo "" +echo "-----------------------------------------------" +echo "Completare registrazione servizio avvio: digitare i seguenti comandi" +echo "systemctl enable sendRebootIOB" +echo "systemctl daemon-reload" +echo "systemctl status sendRebootIOB" +echo "-----------------------------------------------" +echo "" +echo "" +echo "" +echo "-----------------------------------------------" +echo "Infine creare voce crontab che salvi temperatura CPU/GPU ogni 20 minuti..." +echo "crontab -e" +echo "*/20 * * * * /usr/local/bin/saveTemp.sh" +echo "-----------------------------------------------" + + + diff --git a/CONF-IOB/Donati/1026_180/mppar b/CONF-IOB/Donati/1026_180/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1026_180/mpser b/CONF-IOB/Donati/1026_180/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1026_180/readParallela.py b/CONF-IOB/Donati/1026_180/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1026_180/readSeriale.py b/CONF-IOB/Donati/1026_180/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1026_180/saveTemp.sh b/CONF-IOB/Donati/1026_180/saveTemp.sh new file mode 100644 index 0000000..a2cd2be --- /dev/null +++ b/CONF-IOB/Donati/1026_180/saveTemp.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +#salva la temperatura CPU e GPU su chiamata... + +# imposto logfile... +logFile="/var/log/logTemp.txt" + +cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp) +cpuTemp1=$(($cpuTemp0/1000)) +cpuTemp2=$(($cpuTemp0/100)) +cpuTempM=$(($cpuTemp2 % $cpuTemp1)) + +gpuTemp=`vcgencmd measure_temp` + +loadAvg=`cat /proc/loadavg` + +echo "$(date) | CPU: temp=$cpuTemp1.$cpuTempM ºC | GPU: $gpuTemp | LoadAvg: $loadAvg" >> $logFile diff --git a/CONF-IOB/Donati/1026_180/sendReboot.py b/CONF-IOB/Donati/1026_180/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1026_180/sendRebootIOB b/CONF-IOB/Donati/1026_180/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1026_180/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1026_180/sendRebootIOB.service b/CONF-IOB/Donati/1026_180/sendRebootIOB.service new file mode 100644 index 0000000..48e3690 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/sendRebootIOB.service @@ -0,0 +1,22 @@ +[Unit] +SourcePath=/etc/init.d/sendRebootIOB +Description=LSB: Steamware's IOB reboot signal +Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target shutdown.target +Wants=network-online.target +After=network.target network-online.target auditd.service +Conflicts=shutdown.target + +[Service] +Type=forking +Restart=no +TimeoutSec=5min +IgnoreSIGPIPE=no +KillMode=process +GuessMainPID=no +RemainAfterExit=yes +SysVStartPriority=2 +ExecStart=/etc/init.d/sendRebootIOB start +ExecStop=/etc/init.d/sendRebootIOB stop + +[Install] +WantedBy=multi-user.target diff --git a/CONF-IOB/Donati/1026_180/setIobConf.sh b/CONF-IOB/Donati/1026_180/setIobConf.sh new file mode 100644 index 0000000..30b4781 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/setIobConf.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# verifico se sia rete donati o rete steamware o offline... +netStatus=`cat /sys/class/net/eth0/operstate` +iaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1` + +cd /home/pi/steamware + +if [[ $netStatus != "up" ]] +then + echo "Siamo Offline, pagina demo!" +elif [[ $iaddr == "10.74.82"* ]] +then + cp IOB.cfg.steamware IOB.cfg -f + echo "Siamo in Steamware!" +elif [[ $iaddr == "192.168.51"* ]] +then + cp IOB.cfg.donati IOB.cfg -f + echo "Siamo a Passirano!" +else + echo "Siamo altrove, pagina demo!" +fi + +echo "$iaddr" + +chown pi:pi * \ No newline at end of file diff --git a/CONF-IOB/Donati/1026_180/test.py b/CONF-IOB/Donati/1026_180/test.py new file mode 100644 index 0000000..3145cbe --- /dev/null +++ b/CONF-IOB/Donati/1026_180/test.py @@ -0,0 +1,31 @@ +import logging + +# set up logging to file - see previous section for more details +logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + datefmt='%m-%d %H:%M', + filename='test.log', + filemode='w') +# define a Handler which writes INFO messages or higher to the sys.stderr +console = logging.StreamHandler() +console.setLevel(logging.INFO) +# set a format which is simpler for console use +formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') +# tell the handler to use this format +console.setFormatter(formatter) +# add the handler to the root logger +logging.getLogger('').addHandler(console) + +# Now, we can log to the root logger, or any other logger. First the root... +logging.info('Jackdaws love my big sphinx of quartz.') + +# Now, define a couple of other loggers which might represent areas in your +# application: + +logger1 = logging.getLogger('myapp.area1') +logger2 = logging.getLogger('myapp.area2') + +logger1.debug('Quick zephyrs blow, vexing daft Jim.') +logger1.info('How quickly daft jumping zebras vex.') +logger2.warning('Jail zesty vixen who grabbed pay from quack.') +logger2.error('The five boxing wizards jump quickly.') diff --git a/CONF-IOB/Donati/1026_180/unix.py b/CONF-IOB/Donati/1026_180/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1026_180/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1026_180/unix.pyc b/CONF-IOB/Donati/1026_180/unix.pyc new file mode 100644 index 0000000..a42c57d Binary files /dev/null and b/CONF-IOB/Donati/1026_180/unix.pyc differ diff --git a/CONF-IOB/Donati/1026_180/win.py b/CONF-IOB/Donati/1026_180/win.py new file mode 100644 index 0000000..f679f60 --- /dev/null +++ b/CONF-IOB/Donati/1026_180/win.py @@ -0,0 +1,32 @@ +import win32api +print " Running on WINDOWS\n" +import os +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + try: + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + except: + logga("Errore nel file WIN.PY per FD") + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + #fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + print " Dummy Method! Completa Lockfile\n" + except IOError: + return False + + return True +try: + if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) +except: + logga("if not lockfile NON RIUSCITO in file WIN.PY") + sys.exit(1) diff --git a/CONF-IOB/Donati/1026_180/win.pyc b/CONF-IOB/Donati/1026_180/win.pyc new file mode 100644 index 0000000..ae9a11e Binary files /dev/null and b/CONF-IOB/Donati/1026_180/win.pyc differ diff --git a/CONF-IOB/Donati/1027 - 185/IOB.cfg b/CONF-IOB/Donati/1027 - 185/IOB.cfg new file mode 100644 index 0000000..18a11f3 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/IOB.cfg @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1026 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1027 - 185/IOB.cfg.donati b/CONF-IOB/Donati/1027 - 185/IOB.cfg.donati new file mode 100644 index 0000000..18a11f3 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/IOB.cfg.donati @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1026 + +[web] +URLBASE = http://192.168.51.71/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://192.168.51.71/MPIO/Alive.aspx +URLENABLED = http://192.168.51.71/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.25 +TIMEOUTSHORT = 2 +TIMEOUTLONG = 50 +SENDURLTIME = 0.2 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = /var/log/logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1027 - 185/IOB.cfg.steamware b/CONF-IOB/Donati/1027 - 185/IOB.cfg.steamware new file mode 100644 index 0000000..6246b6a --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/IOB.cfg.steamware @@ -0,0 +1,23 @@ +[id] +idxMacchina = 1005 + +[web] +URLBASE = http://10.74.82.219/MPIO/inputIOB.aspx?idxMacchina= +URLALIVE = http://10.74.82.219/MPIO/Alive.aspx +URLENABLED = http://10.74.82.219/MPIO/Enabled.aspx?idxMacchina= +URLADV1 = &valore= +URLREBO = http://10.74.82.219/MPIO/sendReboot.aspx?idxMacchina= + +[time] +SAMPLETIME = 0.20 +TIMEOUTSHORT = 0.30 +TIMEOUTLONG = 50 +SENDURLTIME = 0.50 + +[log] +LOGLEVEL = 10 +LOGFILE = logfile.txt +LOGREBO = logReboot.txt + +[comm] +port = /dev/ttyAMA0 diff --git a/CONF-IOB/Donati/1027 - 185/MapoIOB b/CONF-IOB/Donati/1027 - 185/MapoIOB new file mode 100644 index 0000000..c49ec0a --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/MapoIOB @@ -0,0 +1,41 @@ +### BEGIN INIT INFO +# Provides: MapoIOB: script Steamware per avvio driver IOB +# Required-Start: $remote_fs $syslog ramlog +# Required-Stop: $remote_fs $syslog ramlog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's MapoIOB driver +# Description: Steamware's MapoIOB driver, versione lettura porta parallela +### END INIT INFO + +#! /bin/sh +# /etc/init.d/MapoIOB + +export HOME +case "$1" in + start) + echo "Starting readParallela" + cd /home/pi/steamware + /usr/bin/python ./readParallela.py 2>&1 & + ;; + stop) + echo "Stopping readParallela" + RS_PID=`ps auxwww | grep readParallela.py | head -1 | awk '{print $2}'` + kill -9 $RS_PID + cd /home/pi/steamware + rm .lockfile + ;; + restart) + ## Stop the service and regardless of whether it was + ## running or not, start it again. + $0 stop + killall python + $0 start + ;; + *) + echo "Usage: /etc/init.d/MapoIOB {start|stop|restart}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1027 - 185/checkAlive.sh b/CONF-IOB/Donati/1027 - 185/checkAlive.sh new file mode 100644 index 0000000..92bc816 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/checkAlive.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# controlla se il logfile è correntemente scritto (quindi MapoIOB è alive) altrimenti riavvia! + +DATE=`date +%Y-%m-%d` +cd /var/log +if [ -f MapoIOB ] + then + # controllo SE sia stato acceduto da meno di 2 minuti (=alive da log...) + trovato=`find . -name 'MapoIOB*' -cmin -1` + if [[ $trovato != './MapoIOB' ]] + then + /etc/init.d/MapoIOB restart + echo $date + "riavvio!" + fi +else + # in questo caso AVVIO il processo MapoIOB + /etc/init.d/MapoIOB start + echo $date + "file non trovato, avvio!" +fi diff --git a/CONF-IOB/Donati/1027 - 185/cleanPython.sh b/CONF-IOB/Donati/1027 - 185/cleanPython.sh new file mode 100644 index 0000000..c4f616a --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/cleanPython.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +DATE=`date +%Y-%m-%d_%T` +# log inizio pulizia +echo $DATE " - INIZIO pulizia processi python" >> clean.log +# effettua pulizia processi: killa tutti i processi python +killall python + +# avvia MapoIob +/etc/init.d/MapoIOB start + +# log fatto! +DATE=`date +%Y-%m-%d_%T` +echo $DATE " - FINE pulizia processi python + riavvio MapoIOB" >> clean.log diff --git a/CONF-IOB/Donati/1027 - 185/crontab b/CONF-IOB/Donati/1027 - 185/crontab new file mode 100644 index 0000000..74fe381 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/crontab @@ -0,0 +1 @@ +* * * * * /bin/bash /home/pi/steamware/checkAlive.sh >> /home/pi/stdout 2>> /home/pi/stderr diff --git a/CONF-IOB/Donati/1027 - 185/install-RPI-IOB.sh b/CONF-IOB/Donati/1027 - 185/install-RPI-IOB.sh new file mode 100644 index 0000000..19491e1 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/install-RPI-IOB.sh @@ -0,0 +1,47 @@ +#|/bin/bash + +#installa il necessario per RPI-3-IOB partendo dal contenuto della folder /home/pi/steamware + +#step 1: creo file di log nuovi +rm /var/log/log*.txt +rm /var/log/MapoIOB +rm /home/pi/steamware/log*.txt + +touch /var/log/logReboot.txt +touch /var/log/logTemp.txt +touch /var/log/MapoIOB + +ln -sf /var/log/logReboot.txt /home/pi/steamware/logReboot.txt +ln -sf /var/log/logTemp.txt /home/pi/steamware/logTemp.txt +ln -sf /var/log/MapoIOB /home/pi/steamware/logfile.txt + +chown pi:pi /home/pi -R +chmod 666 /var/log/log*.txt +chmod 666 /var/log/MapoIOB + +#step 2: copio files in /usr/local/bin +cd /home/pi/steamware +chmod +x *.sh +cp *.sh /usr/local/bin/ + +# step 3: copio target systemd in avvio... +cp -f sendRebootIOB /etc/init.d/sendRebootIOB +cp -f sendRebootIOB.service /etc/systemd/system/sendRebootIOB.service +echo "" +echo "-----------------------------------------------" +echo "Completare registrazione servizio avvio: digitare i seguenti comandi" +echo "systemctl enable sendRebootIOB" +echo "systemctl daemon-reload" +echo "systemctl status sendRebootIOB" +echo "-----------------------------------------------" +echo "" +echo "" +echo "" +echo "-----------------------------------------------" +echo "Infine creare voce crontab che salvi temperatura CPU/GPU ogni 20 minuti..." +echo "crontab -e" +echo "*/20 * * * * /usr/local/bin/saveTemp.sh" +echo "-----------------------------------------------" + + + diff --git a/CONF-IOB/Donati/1027 - 185/mppar b/CONF-IOB/Donati/1027 - 185/mppar new file mode 100644 index 0000000..b433a73 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/mppar @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/pi/steamware/readParallela.py diff --git a/CONF-IOB/Donati/1027 - 185/mpser b/CONF-IOB/Donati/1027 - 185/mpser new file mode 100644 index 0000000..444b459 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/mpser @@ -0,0 +1,2 @@ +#!/bin/bash +/usr/bin/python /home/steamware/readSeriale.py diff --git a/CONF-IOB/Donati/1027 - 185/readParallela.py b/CONF-IOB/Donati/1027 - 185/readParallela.py new file mode 100644 index 0000000..5a38f21 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/readParallela.py @@ -0,0 +1,530 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# readParallela v. 1.8 +# versione estetica di Carlo + single instance timer + +#--------------------------------------------------------------- +# levare locking +# timer semplificata +# GPIO global + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging +import logging.handlers +import threading +import Queue +#-------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +PROGRAM_NAME ="ReadPar IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "1001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) +SENDURLTIME = 0.08 + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +# VAR + +out_0 = 24 +out_1 = 26 + +in_0 = 11 +in_1 = 12 +in_2 = 13 +in_3 = 15 +in_4 = 16 +in_5 = 18 +in_6 = 22 +in_7 = 7 + +# contatore: serve x match tra accoda ed invia x possibile controllo a posteriori... ogni volta che accodo incremento di 1, va da 0 a 999 +cont = '0' + +# variabile stato online/offline della macchina +onLine = '1' + +# variabile stato seinding/waiting x la parte invio URL +sending = '0' + +# variabile stato timer thread busy +timer_busy = False + +#-------------------------------------------------------------- +# Gestione coda (condivisa) x registrazione eventi ed invio URL +#print "Creazione coda 1000 elementi" + +Coda = Queue.Queue(0) + +#queueLock = threading.Lock() + +#--------------------------------------------------------------- +# lettura parallela +# ritorna il byte letto pulito ( due char hex ) + +def readParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + current = '' + +# print "input : " + + # ritorna '' se non ci sono abbastanza caratteri + try: + num_value = 255 + +# print "num_value : " , num_value , in_0 + + if GPIO.input(in_0): + num_value = num_value - 1 + + if GPIO.input(in_1): + num_value = num_value - 2 + + if GPIO.input(in_2): + num_value = num_value - 4 + + if GPIO.input(in_3): + num_value = num_value - 8 + + if GPIO.input(in_4): + num_value = num_value - 16 + + if GPIO.input(in_5): + num_value = num_value - 32 + + if GPIO.input(in_6): + num_value = num_value - 64 + + if GPIO.input(in_7): + num_value = num_value - 128 + + current = hex( num_value ).replace ( "0x" , "" ).upper() + +# print "\n\n\n\n\n" , num_value , current + + except: + pass + + return current + + +#-------------------------------------------------------------- +# MARCO: cambiare: chiama URL NON deve chiamare url MA METTERE IN CODA (riempiCoda!!!) +# la parte URL vera va messa in svuotaCoda, PARAMETRICA + +#--------------------------------------------------------------- +#Funzione di scrittura su coda con try-except + +def accoda(): + + try: +# url = URLBASE + idxMacchina + URLADV1 + value +# urllib.urlopen ( url ) + #dtEve = time.strftime("%y%m%d%H%M%S")+"000" + dtEve = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + #logPro.debug( "Nuovo valore inserito in coda: " + dtEve + "#" + value + '#' + cont) + #print(dtEve) + #queueLock.acquire() + Coda.put(dtEve + '#' + value + '#' + cont) + #queueLock.release() + #print "Nuovo valore inserito in coda: " + dtEve + "#", value + + except Queue.Full: + logPro.error( "Quque full" + dtEve + '#' + value + '#' + cont ) + except: + logPro.error( "NETWORK:Errore http-no com rete-timeout" + url ) +# print "Url aforte" , url + + +#-------------------------------------------------------------- +# MARCO: scrivere svuotaCoda come thread etc... +def svuota_coda(): + + global onLine + global sending + global timer_busy + + #print "start timer " + + if ( timer_busy == False ): + timer_busy = True + #print "start timer ok " + + try: + if not Coda.empty(): + #print "coda da svuotare!" + response = urllib.urlopen(URLALIVE) + answ = response.read() + if answ == 'OK': + #print "OK alive" + response2 = urllib.urlopen(URLENABLED + idxMacchina) + answ2 = response2.read() + if answ2 == 'OK': + # aggiorno stato ad online + if onLine == '0': + logPro.info("IOB ONLINE!") + #print("IOB ONLINE") + + onLine = '1' # imposto comunque online + else: + if onLine == '1': + logPro.error("IOB offline") + #print("IOB offline") + + onLine = '0' + else: + if onLine == '1': + logPro.error("Server offline") + #print("Server offline") + + onLine = '0' + + # ora verifico SE si possa inviare (ovvero sia online server e NON ci siano altri send attivi...) + if onLine == '1': + if sending == '0': + #segnalo che sono in sending! + sending = '1' + + # formatto dataOra corrente + #dtCurr = time.strftime("%y%m%d%H%M%S")+"000" + dtCurr = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3] + # prendo 1 valore dalla coda... + #queueLock.acquire() + resp = Coda.get() + # RILASCIO SUBITO la coda x nuovi insert... + #queueLock.release() + + + # recupero valori da coda! + dtEve = resp.split("#")[0] + value = resp.split("#")[1] + cnt = resp.split("#")[2] + url = URLBASE + idxMacchina + URLADV1 + value + url = url + '&dtCurr=' + dtCurr + '&dtEve=' + dtEve + '&cnt=' + cnt + # CHIAMO URL + response3 = urllib.urlopen ( url ) + answ3 = response3.read() + #print(url) + #logPro.debug(url) + + + # log valore inviato! + logSnd.info( value + ' ['+ cnt +']' + ' R:' + answ3 ) + #print "Valore smaltito dalla coda" + + # completato invio, riporto sending a zero! + sending = '0' + else: + logPro.info("WAIT active send to complete") + + else: + pass + + else: + pass + + except: + if onLine == '1': + logPro.error("Server Non raggiungibile") + #print "Non raggiungibile" + + onLine = '0' + +# in ogni caso + + timer_busy = False + #print "end timer ok" + + + #print "end timer " + + +#--------------------------------------------------------------- +# funzione timer thread +#--------------------------------------------------------------- +def do_every (interval, worker_func, iterations = 0): + if iterations != 1: + threading.Timer ( + interval, + do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] + ).start (); + + worker_func (); + +#--------------------------------------------------------------- +# gestione contatore +#--------------------------------------------------------------- +def contatore(): + + try: + global cont + ctr = int(cont) + ctr +=1 + ctr = ctr % 1000 # round robin 1000 eventi x track + cont = str(ctr) + except: + print("errore incremento contatore") + +#--------------------------------------------------------------- +# avvia porta parallela +#--------------------------------------------------------------- +def avviaParallela(): + + global in_0 + global in_1 + global in_2 + global in_3 + global in_4 + global in_5 + global in_6 + global in_7 + + global GPIO + + try: + + GPIO.setmode(GPIO.BOARD) + + GPIO.setwarnings(False) + + #GPIO.setup(out_0, GPIO.OUT) # output 0 + #GPIO.setup(out_1, GPIO.OUT) # output 1 + + GPIO.setup(in_0, GPIO.IN) # input 0 + GPIO.setup(in_1, GPIO.IN) # input 1 + GPIO.setup(in_2, GPIO.IN) # input 2 + GPIO.setup(in_3, GPIO.IN) # input 3 + GPIO.setup(in_4, GPIO.IN) # input 4 + GPIO.setup(in_5, GPIO.IN) # input 5 + GPIO.setup(in_6, GPIO.IN) # input 6 + GPIO.setup(in_7, GPIO.IN) # input 7 + + except: + print( "\n\n" + PROGRAM_NAME + " - Error 3 on RPi.GPIO ! \n\n") + sys.exit(1) + + + print( "\n\n" + PROGRAM_NAME + " - init ok \n\n") + + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + SENDURLTIME = config.getfloat ( 'time' , 'SENDURLTIME' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLENABLED = config.get('web' , 'URLENABLED') + URLALIVE = config.get ('web' , 'URLALIVE') + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a' + ) + + # aggiungo 2 logger specifici x queue e send... + logQue = logging.getLogger('queue') + logSnd = logging.getLogger('sendUrl') + logPro = logging.getLogger('program') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logPro.info("Avvio Programma" + PROGRAM_NAME) + +## Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logPro.info( "Start " + PROGRAM_NAME ) + + +# lettura file configurazione + +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + + +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' SENDURLTIME = %4.2f' % ( SENDURLTIME ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + +#-------------------------------------------------------------- +# apertura parallela + +try: + import RPi.GPIO as GPIO +except RuntimeError: + print( "\n\n" + PROGRAM_NAME + " - Error 1 - you need superuser privileges") +except: + print( "\n\n" + PROGRAM_NAME + " - Error 2 - you need superuser privileges. USE 'sudo' to run your script\n\n") + sys.exit(1) + + +avviaParallela() + + +#-------------------------------------------------------------- +# MARCO: qui inserire avvio thread di "svuotaCoda" + +# avviaSvuotaCoda +#print "Avvia svuota coda" + +do_every ( SENDURLTIME , svuota_coda ); + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +#print "Avvio ciclo" +logPro.info("Avvio loop principale") +while 1: + + try: + time.sleep (SAMPLETIME) + except: + logPro.info("First_SLEEP: errore attesa sampletime") + + # lettura dati da IOB + value = readParallela() + + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logQue.info( value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logQue.info( '>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_short") + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logQue.info( '>>' + value + ' ['+ cont +']') + errormsglen = 0 + accoda() + contatore() + except: + logPro.error("URLBROWSER: errore registrazione valore e accoda TO_long") + pass + to_long = TIMEOUTLONG + + + + diff --git a/CONF-IOB/Donati/1027 - 185/readSeriale.py b/CONF-IOB/Donati/1027 - 185/readSeriale.py new file mode 100644 index 0000000..3c00644 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/readSeriale.py @@ -0,0 +1,363 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------- + +import serial +import time +import sys +import datetime +import urllib +import ConfigParser +import os, sys + +#--------------------------------------------------------------- + +# COSTANTI +MSGLEN = 9 +TIMEOUTSERIALE = 10 +MAXRETRY = 3 + +# DA FILE CONF +idxMacchina = "2001" +SAMPLETIME = 0.1 +TIMEOUTSHORT = (SAMPLETIME*20) +TIMEOUTLONG = (SAMPLETIME*600) + +# VAR +to_enable = False +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG +to_serial = TIMEOUTSERIALE +to_retry = MAXRETRY +errormsglen = 0 + +#--------------------------------------------------------------- +# classe logger + +class Logger: + def __init__(self, filename): + try: + self.filename = filename + except: + logga("LOGGER: errore try su self.filename") + sys.exit(1) + def __call__(self, string): + try: + file = open(self.filename, 'a') + file.write('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ') + file.write(string + '\n') + file.close() + except: + logga("LOGGER: errore try su scrittura") + sys.exit(1) + +#--------------------------------------------------------------- +# lettura buffer seriale e pulizia caratteri non stampabili +# ritorna '' se non c'è un messaggio buono o il messaggio pulito ( due bytes hex ) +# il messaggio ha il formato xxi00 00xxx + +def readSeriale(): + + global to_serial + global to_retry + global errormsglen + + ret = '' + current = '' + i = 0 + + # ritorna '' se non ci sono abbastanza caratteri + try: + if ser.inWaiting() < MSGLEN : +# +# to_serial = to_serial - 1 # se non mi risponde, faccio un ' altra richiesta.... +# if to_serial <= 0: +# try: +# requestData () +# except: +# logga("SERIALE: errore su requestData") +# sys.exit(1) +# to_serial = TIMEOUTSERIALE # ripristino timer +# to_retry = to_retry - 1 # contatore retry +# if to_retry <= 0: +# logga ( 'IOB not responding' ) +# return ret + logga("SERIALE: errore msglen < 9 char - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + except: + if startstatus == 0: + logga ("Porta SERIALE non disponibile - ser.inWaiting error - exit... - Errore no. " + str(errormsglen)) + errormsglen = errormsglen +1 + avviaSeriale() + time.sleep(.2) + if errormsglen > 30: + sys.exit(1) + + # finchè c'è robba .. leggi e tieni i buoni + to_serial = TIMEOUTSERIALE + to_retry = MAXRETRY + try: + while ser.inWaiting() > 0 : + try: + c = ser.read(1) + except: + logga("SERIALE: errore su try ser.read") + sys.exit(1) + # filtra caratteri non stampabili + if c > ' ' : + current += c + #sys.stdout.write(current + '<<<<\n') + # ora il messaggio ha il formato xxxxxi00 00xxx : cerco la 'i' iniziale + try: + while i < len(current) and current[i] != 'i': + i = i + 1 + except: + logga("SERIALE: errore su ricerca i iniziale") + sys.exit(1) + # se non ho trovato la 'i' restituisco '' + if i == len(current)-1: + return ret + else: + current = current[i+1:i+3] + # richiesta dati ad IOB + requestData() + #sys.stdout.write ( current + '\n') + except: + if startstatus == 0: + logga ('Porta SERIALE non disponibile - ser.inWaiting e filtraggio error...exit') + sys.exit(1) + return current +#--------------------------------------------------------------- +# richiesta dati ad IOB : scrittura su seriale + +def requestData (): + try : + ser.write ("$i" + '\r\n') + ser.flush() + except : + if startstatus == 0: + logga ( "SERIAL: Errore di scrittura/flush") + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except + +def chiamaUrl(): + try: + url = URLBASE + idxMacchina + URLADV1 + value + urllib.urlopen ( url ) + except: + logga ( "NETWORK:Errore http-no com rete-timeout" + url ) + + +#--------------------------------------------------------------- +# Funzione che verifica possibilità di creare log e include testo corrente + +def logga(message) : + try: + log(message) + except : + pass + +#--------------------------------------------------------------- + + +def avviaSeriale(): + global ser + + try: + ser = serial.Serial( + port = comm_port , + baudrate = 9600 , + parity = serial.PARITY_NONE , + stopbits = serial.STOPBITS_ONE , + bytesize = serial.EIGHTBITS + ) + startstatus = 0 + except serial.serialutil.SerialException , e : + try: + if startstatus == 0: + logga ( "SERIAL:Errore apertura seriale - " + comm_port) + except: + pass + sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) + if errormsglen > 30: + sys.exit (1) + +#--------------------------------------------------------------- +#--------------------------------------------------------------- +# MAIN + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'readSeriale.cfg' ) + + SAMPLETIME = config.getfloat ( 'time' , 'SAMPLETIME' ) + TIMEOUTSHORT = config.getfloat ( 'time' , 'TIMEOUTSHORT' ) + TIMEOUTLONG = config.getfloat ( 'time' , 'TIMEOUTLONG' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + comm_port = config.get ( 'comm' , 'port' ) + + URLBASE = config.get ( 'web' , 'URLBASE' ) + URLADV1 = config.get ( 'web' , 'URLADV1' ) + + LOGFILE = config.get ( 'log' , 'LOGFILE' ) + LOGLEVEL = config.get ( 'log' , 'LOGLEVEL' ) +except: + sys.exit(1) + +# oggetto Logger +try: + log = Logger(LOGFILE) +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) + +print '\n\n Read seriale IOB v.0.2 !!!!\n' + +global startstatus +startstatus = 1 + +if startstatus == 1: + logga("Avvio Programma") + +# Verifica l'OS e di conseguenza carica il file relativo con metodo di lockfile appropriato + check singola istanza +if os.name == 'posix': + import unix +else: + import win + +logga ( "Start Read seriale IOB v.0.2") + + +# lettura file configurazione + +# [comm] +# port = /dev/ttyS0 +# [id] +# idxMacchina = 2001 +# [time] +# SAMPLETIME = 0.1 +# TIMEOUTSHORT = 200 +# TIMEOUTLONG = 6000 + +print ( ' comm_port = %s' % ( comm_port ) ) +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' SAMPLETIME = %4.2f' % ( SAMPLETIME ) ) +print ( ' TIMEOUTSHORT = %4.2f' % ( TIMEOUTSHORT ) ) +print ( ' TIMEOUTLONG = %4.2f' % ( TIMEOUTLONG ) ) +print ( ' URLBASE = %s' % ( URLBASE ) ) +print ( ' URLADV1 = %s' % ( URLADV1 ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) +print ( ' LOGLEVEL = %s' % ( LOGLEVEL ) ) + +# -sys.stdout.write ( 'idxMacchina ?' + idxMacchina + '\n') + +to_short = TIMEOUTSHORT +to_long = TIMEOUTLONG + + + +#-------------------------------------------------------------- + + +#--------------------------------------------------------------- +# apertura seriale + +avviaSeriale() + +#try: +# ser = serial.Serial( +# port = comm_port , +# baudrate = 9600 , +# parity = serial.PARITY_NONE , +# stopbits = serial.STOPBITS_ONE , +# bytesize = serial.EIGHTBITS +# ) +# print "Initialized!" +#except serial.serialutil.SerialException , e : +# try: +# logga ( "SERIAL:Errore apertura seriale - " + comm_port) +# except: +# pass +# sys.stdout.write ( '\nErrore apertura seriale\n\n%s\n\n' % e ) +# sys.exit (1) + +#--------------------------------------------------------------- +# ciclo forever and ever + +old = '' + +# richiesta dati ad IOB +try: + requestData() +except: + logga("SERIALE: errore sul try di requestData") + sys.exit(1) + + +while 1: + try: + time.sleep (SAMPLETIME) + except: + logga("SERIALE_SLEEP: errore attesa sampletime") + # lettura dati da IOB + try: + value = readSeriale() + except: + if startstatus == 0: + logga("errore PRIMA LETTURA SERIALE") + sys.exit(1) + if ( value != '' ) : + if value != old : + #loggo e invio dati + try: + logga ( value ) + errormsglen = 0 + chiamaUrl() + except: + logga("URLBROWSER: errore registrazione valore e chiamaUrl") + pass + #enable e reset timer + to_enable = True + to_short = TIMEOUTSHORT + to_long = TIMEOUTLONG + + old = value + + + # gestione timeout breve + if ( to_enable ) : + to_short = to_short - SAMPLETIME + if to_short <= 0: + #loggo e invio dati + try: + logga ( '>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_short = TIMEOUTSHORT + to_enable = False # dopo un colpo il timer breve viene disabilitato + to_long = TIMEOUTLONG + + # gestione timeout lungo + to_long = to_long - SAMPLETIME + if to_long <= 0: + #loggo e invio dati + try: + logga ( '>>' + value ) + errormsglen = 0 + chiamaUrl() + except: + pass + to_long = TIMEOUTLONG + + diff --git a/CONF-IOB/Donati/1027 - 185/saveTemp.sh b/CONF-IOB/Donati/1027 - 185/saveTemp.sh new file mode 100644 index 0000000..a2cd2be --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/saveTemp.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +#salva la temperatura CPU e GPU su chiamata... + +# imposto logfile... +logFile="/var/log/logTemp.txt" + +cpuTemp0=$(cat /sys/class/thermal/thermal_zone0/temp) +cpuTemp1=$(($cpuTemp0/1000)) +cpuTemp2=$(($cpuTemp0/100)) +cpuTempM=$(($cpuTemp2 % $cpuTemp1)) + +gpuTemp=`vcgencmd measure_temp` + +loadAvg=`cat /proc/loadavg` + +echo "$(date) | CPU: temp=$cpuTemp1.$cpuTempM ºC | GPU: $gpuTemp | LoadAvg: $loadAvg" >> $logFile diff --git a/CONF-IOB/Donati/1027 - 185/sendReboot.py b/CONF-IOB/Donati/1027 - 185/sendReboot.py new file mode 100644 index 0000000..021c400 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/sendReboot.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# sendReboot v. 1.8 + +#--------------------------------------------------------------- + + +import time +import sys + + +from datetime import datetime + +import urllib +import ConfigParser +import os, sys + +import logging + +import time + +#--------------------------------------------------------------- + +# COSTANTI +PROGRAM_NAME = "SendReboot IOB-pi v.1.8" + +# DA FILE CONF +idxMacchina = "99" + +# registro se ho fatto chiamata +global numTry +numTry = 1 + + +#--------------------------------------------------------------- +#Funzione di scrittura su url con try-except +#--------------------------------------------------------------- + +def chiamaUrl(numTry): + + try: + urllib.urlopen ( url ) + numTry = numTry + 10 + except Exception, e: + print e + logging.info ( e ) + print "Url aforte" , url + return numTry + + +#--------------------------------------------------------------- +# Funzione di recupero mac address per poterlo inviare a MPIO +#--------------------------------------------------------------- +def getMAC(interface): + # Return the MAC address of interface + try: + str = open('/sys/class/net/' + interface + '/address').read() + except: + str = "00:00:00:00:00:00" + return str[0:17] + +#--------------------------------------------------------------- +# MAIN +#--------------------------------------------------------------- + +try: + config = ConfigParser.RawConfigParser() + config.read ( 'IOB.cfg' ) + + idxMacchina = config.get ( 'id' , 'idxMacchina' ) + + + URLREBO = config.get ( 'web' , 'URLREBO' ) + + LOGFILE = config.get ( 'log' , 'LOGREBO' ) +except: + print "\n\n" + PROGRAM_NAME + ' - Error 4 - in config file ' 'IOB.cfg' + sys.exit(1) + + +#-------------------------------------------- +# oggetto Logger +#-------------------------------------------- +try: +# log = Logger(LOGFILE) + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-8s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + filename=LOGFILE, + filemode='a') + +except: + # manda mail o simili - FARE!!! + print "LOG: Impossibile creare file log con nome " + print (LOGFILE) +#-------------------------------------------- + + +print "\n\n" + PROGRAM_NAME + "\n\n" + +global startstatus +startstatus = 1 + +if startstatus == 1: + logging.info("Avvio Programma " + PROGRAM_NAME) + + +# lettura file configurazione +print ( ' idxMacchina = %s' % ( idxMacchina ) ) +print ( ' URLREBO = %s' % ( URLREBO ) ) +print ( ' LOGFILE = %s' % ( LOGFILE ) ) + +# lettura mac address +myMac = getMAC('eth0') +print ( ' MAC Address = %s' % ( myMac ) ) + +# configuro URL da inviare +url = URLREBO + idxMacchina + "&mac=" + myMac + +# modifica: cerco se ho inviato segnale altrimenti ritento invio... +while (numTry < 11): + logging.info("Tentativo invio URL: " + `numTry` ) + numTry = chiamaUrl(numTry) + time.sleep(3) + numTry = numTry + 1 + + +# registro che ho inviato! +logging.info("Inviato segnale di reboot!: " + url ) diff --git a/CONF-IOB/Donati/1027 - 185/sendRebootIOB b/CONF-IOB/Donati/1027 - 185/sendRebootIOB new file mode 100644 index 0000000..191bfff --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/sendRebootIOB @@ -0,0 +1,33 @@ +#!/bin/sh - +# +### BEGIN INIT INFO +# Provides: sendReboot +# Required-Start: $network $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Steamware's IOB reboot signal +# Description: Steamware's sendReboot segnalazione reboot dispositivo +### END INIT INFO + +#! /bin/sh +# /etc/init.d/sendReboot + + + +export HOME +case "$1" in + start) + cd /home/pi/steamware + echo "Starting sendReboot" + /usr/bin/python ./sendReboot.py 2>&1 & + echo "Verifica Rete e file IOB" + /usr/local/bin/setIobConf.sh + ;; + *) + echo "Usage: /etc/init.d/sendReboot {start}" + exit 1 + ;; +esac +exit 0 + diff --git a/CONF-IOB/Donati/1027 - 185/sendRebootIOB.service b/CONF-IOB/Donati/1027 - 185/sendRebootIOB.service new file mode 100644 index 0000000..48e3690 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/sendRebootIOB.service @@ -0,0 +1,22 @@ +[Unit] +SourcePath=/etc/init.d/sendRebootIOB +Description=LSB: Steamware's IOB reboot signal +Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target shutdown.target +Wants=network-online.target +After=network.target network-online.target auditd.service +Conflicts=shutdown.target + +[Service] +Type=forking +Restart=no +TimeoutSec=5min +IgnoreSIGPIPE=no +KillMode=process +GuessMainPID=no +RemainAfterExit=yes +SysVStartPriority=2 +ExecStart=/etc/init.d/sendRebootIOB start +ExecStop=/etc/init.d/sendRebootIOB stop + +[Install] +WantedBy=multi-user.target diff --git a/CONF-IOB/Donati/1027 - 185/setIobConf.sh b/CONF-IOB/Donati/1027 - 185/setIobConf.sh new file mode 100644 index 0000000..30b4781 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/setIobConf.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# verifico se sia rete donati o rete steamware o offline... +netStatus=`cat /sys/class/net/eth0/operstate` +iaddr=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1` + +cd /home/pi/steamware + +if [[ $netStatus != "up" ]] +then + echo "Siamo Offline, pagina demo!" +elif [[ $iaddr == "10.74.82"* ]] +then + cp IOB.cfg.steamware IOB.cfg -f + echo "Siamo in Steamware!" +elif [[ $iaddr == "192.168.51"* ]] +then + cp IOB.cfg.donati IOB.cfg -f + echo "Siamo a Passirano!" +else + echo "Siamo altrove, pagina demo!" +fi + +echo "$iaddr" + +chown pi:pi * \ No newline at end of file diff --git a/CONF-IOB/Donati/1027 - 185/test.py b/CONF-IOB/Donati/1027 - 185/test.py new file mode 100644 index 0000000..3145cbe --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/test.py @@ -0,0 +1,31 @@ +import logging + +# set up logging to file - see previous section for more details +logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', + datefmt='%m-%d %H:%M', + filename='test.log', + filemode='w') +# define a Handler which writes INFO messages or higher to the sys.stderr +console = logging.StreamHandler() +console.setLevel(logging.INFO) +# set a format which is simpler for console use +formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') +# tell the handler to use this format +console.setFormatter(formatter) +# add the handler to the root logger +logging.getLogger('').addHandler(console) + +# Now, we can log to the root logger, or any other logger. First the root... +logging.info('Jackdaws love my big sphinx of quartz.') + +# Now, define a couple of other loggers which might represent areas in your +# application: + +logger1 = logging.getLogger('myapp.area1') +logger2 = logging.getLogger('myapp.area2') + +logger1.debug('Quick zephyrs blow, vexing daft Jim.') +logger1.info('How quickly daft jumping zebras vex.') +logger2.warning('Jail zesty vixen who grabbed pay from quack.') +logger2.error('The five boxing wizards jump quickly.') diff --git a/CONF-IOB/Donati/1027 - 185/unix.py b/CONF-IOB/Donati/1027 - 185/unix.py new file mode 100644 index 0000000..12fb3dc --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/unix.py @@ -0,0 +1,31 @@ +import fcntl +import os +import logging + +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + except IOError: + return False + + return True + +if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logging.error( "LOCK: Piu istanze aperte") + #sys.exit ( 0 ) + +#- print '\n running alone ...\n' + + diff --git a/CONF-IOB/Donati/1027 - 185/unix.pyc b/CONF-IOB/Donati/1027 - 185/unix.pyc new file mode 100644 index 0000000..a42c57d Binary files /dev/null and b/CONF-IOB/Donati/1027 - 185/unix.pyc differ diff --git a/CONF-IOB/Donati/1027 - 185/win.py b/CONF-IOB/Donati/1027 - 185/win.py new file mode 100644 index 0000000..f679f60 --- /dev/null +++ b/CONF-IOB/Donati/1027 - 185/win.py @@ -0,0 +1,32 @@ +import win32api +print " Running on WINDOWS\n" +import os +#--------------------------------------------------------------- +# meccanismo di file lock per evitare multiple instances +# The function will try to lock the file specified , if it success, return True, else return False. +# The nice thing is that the lock will be dropped when the program terminates. +# >>>Use : +# if not lockFile(".lock.pod"): +# sys.exit(0) + +def lockFile ( lockfile ) : + try: + fd = os.open ( lockfile , os.O_CREAT | os.O_TRUNC | os.O_WRONLY ) + except: + logga("Errore nel file WIN.PY per FD") + try: + # Request exclusive (EX) non-blocking (NB) advisory lock. + #fcntl.lockf ( fd , fcntl.LOCK_EX | fcntl.LOCK_NB ) + print " Dummy Method! Completa Lockfile\n" + except IOError: + return False + + return True +try: + if not lockFile ( ".lockfile" ) : + print '\n noi non siamo soli ...\n' + logga ( "LOCK: Piu istanze aperte") + sys.exit ( 0 ) +except: + logga("if not lockfile NON RIUSCITO in file WIN.PY") + sys.exit(1) diff --git a/CONF-IOB/Donati/1027 - 185/win.pyc b/CONF-IOB/Donati/1027 - 185/win.pyc new file mode 100644 index 0000000..ae9a11e Binary files /dev/null and b/CONF-IOB/Donati/1027 - 185/win.pyc differ diff --git a/CONF-IOB/Donati/1501_172/IOB.cfg b/CONF-IOB/Donati/1501_172/IOB.cfg new file mode 100644 index 0000000..b14a649 --- /dev/null +++ b/CONF-IOB/Donati/1501_172/IOB.cfg @@ -0,0 +1,10 @@ +[id] +idxMacchina = 1501 + +[web] +URLREBO = http://10.74.82.218/MPIO/sendReboot.aspx?idxMacchina= +#URLREBO = http://192.168.51.71/MPIO/sendReboot.aspx?idxMacchina= + +[log] +LOGLEVEL = 10 +LOGREBO = /var/log/logReboot.txt diff --git a/CONF-IOB/Donati/1501_172/LogoHighResWhite.png b/CONF-IOB/Donati/1501_172/LogoHighResWhite.png new file mode 100644 index 0000000..361a978 Binary files /dev/null and b/CONF-IOB/Donati/1501_172/LogoHighResWhite.png differ diff --git a/CONF-IOB/Donati/1501_172/MP-MON-DEMO.html b/CONF-IOB/Donati/1501_172/MP-MON-DEMO.html new file mode 100644 index 0000000..7bd8331 --- /dev/null +++ b/CONF-IOB/Donati/1501_172/MP-MON-DEMO.html @@ -0,0 +1,540 @@ + + + + + + Index - MP-MONi DEMO + + + + + + + + + + + + +
+ + + +
+
+
+ +
+
+ +
+
SMER.09
+
+
+
articolo:
+
-
+
fermo generico
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.03
+
+
+
articolo:
+
5010710
+
fermo generico
+
tempo ciclo:
+
07:31
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.04
+
+
+
articolo:
+
5009047
+
lavorazione
+
tempo ciclo:
+
07:01
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.02
+
+
+
articolo:
+
5010225
+
lavorazione
+
tempo ciclo:
+
07:00
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.03
+
+
+
articolo:
+
5009595
+
fermo generico
+
tempo ciclo:
+
10:49
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.08
+
+
+
articolo:
+
5009595
+
lavorazione
+
tempo ciclo:
+
09:07
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.07
+
+
+
articolo:
+
5009580
+
lavorazione
+
tempo ciclo:
+
07:34
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.02
+
+
+
articolo:
+
5003049
+
lavorazione
+
tempo ciclo:
+
06:55
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.01
+
+
+
articolo:
+
5009030
+
lavorazione
+
tempo ciclo:
+
08:04
+ + +
+
+
+
+
+
+
+
+ +
+
EXABB
+
+
+
articolo:
+
5010290
+
lavorazione
+
tempo ciclo:
+
10:03
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.04
+
+
+
articolo:
+
5010660
+
lavorazione
+
tempo ciclo:
+
14:43
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.10
+
+
+
articolo:
+
5009556
+
lavorazione
+
tempo ciclo:
+
14:03
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.01
+
+
+
articolo:
+
5010260
+
lavorazione
+
tempo ciclo:
+
06:45
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.06
+
+
+
articolo:
+
5007041
+
lavorazione
+
tempo ciclo:
+
02:00
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.02
+
+
+
articolo:
+
5010720
+
manuale
+
tempo ciclo:
+
02:01
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.01
+
+
+
articolo:
+
5010181
+
lavorazione
+
tempo ciclo:
+
01:43
+ + +
+
+
+
+
+
+
+
+ +
+
SBAV.05
+
+
+
articolo:
+
5007580
+
allarme CN
+
tempo ciclo:
+
03:13
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.11
+
+
+
articolo:
+
5009053
+
lavorazione
+
tempo ciclo:
+
08:45
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.COS
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.01
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.02
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.03
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ + + + + + + +
+
+
+

MoonPro MONitor

+
+
+ SteamWare +
+
+

Steamware s.r.l. - © 2007-2016

+
+
+ +
+
+ + + + + + + + + diff --git a/CONF-IOB/Donati/1501_172/MP-MON-DEMO_b.html b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_b.html new file mode 100644 index 0000000..8ed3c2e --- /dev/null +++ b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_b.html @@ -0,0 +1,540 @@ + + + + + + Index - MP-MONi DEMO + + + + + + + + + + + + +
+ + + +
+
+
+ +
+
+ +
+
SMER.09
+
+
+
articolo:
+
-
+
fermo generico
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.03
+
+
+
articolo:
+
5010710
+
fermo generico
+
tempo ciclo:
+
07:31
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.04
+
+
+
articolo:
+
5009047
+
lavorazione
+
tempo ciclo:
+
07:01
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.02
+
+
+
articolo:
+
5010225
+
lavorazione
+
tempo ciclo:
+
07:00
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.03
+
+
+
articolo:
+
5009595
+
fermo generico
+
tempo ciclo:
+
10:49
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.08
+
+
+
articolo:
+
5009595
+
lavorazione
+
tempo ciclo:
+
09:07
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.07
+
+
+
articolo:
+
5009580
+
lavorazione
+
tempo ciclo:
+
07:34
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.02
+
+
+
articolo:
+
5003049
+
lavorazione
+
tempo ciclo:
+
06:55
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.01
+
+
+
articolo:
+
5009030
+
lavorazione
+
tempo ciclo:
+
08:04
+ + +
+
+
+
+
+
+
+
+ +
+
EXABB
+
+
+
articolo:
+
5010290
+
lavorazione
+
tempo ciclo:
+
10:03
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.04
+
+
+
articolo:
+
5010660
+
lavorazione
+
tempo ciclo:
+
14:43
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.10
+
+
+
articolo:
+
5009556
+
lavorazione
+
tempo ciclo:
+
14:03
+ + +
+
+
+
+
+
+
+
+ +
+
PUL.01
+
+
+
articolo:
+
5010260
+
lavorazione
+
tempo ciclo:
+
06:45
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.06
+
+
+
articolo:
+
5007041
+
lavorazione
+
tempo ciclo:
+
02:00
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.02
+
+
+
articolo:
+
5010720
+
manuale
+
tempo ciclo:
+
02:01
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.01
+
+
+
articolo:
+
5010181
+
lavorazione
+
tempo ciclo:
+
01:43
+ + +
+
+
+
+
+
+
+
+ +
+
SBAV.05
+
+
+
articolo:
+
5007580
+
allarme CN
+
tempo ciclo:
+
03:13
+ + +
+
+
+
+
+
+
+
+ +
+
SMER.11
+
+
+
articolo:
+
5009053
+
lavorazione
+
tempo ciclo:
+
08:45
+ + +
+
+
+
+
+
+
+
+ +
+
TAV.COS
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.01
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.02
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ +
+
COMB.03
+
+
+
articolo:
+
-
+
n.d.
+
tempo ciclo:
+
00:00
+ + +
+
+
+
+
+
+
+
+ + + + + + + +
+
+
+

MoonPro MONitor

+
+
+ SteamWare +
+
+

Steamware s.r.l. - © 2007-2016

+
+
+ +
+
+ + + + + + + + + diff --git a/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSans.woff b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSans.woff new file mode 100644 index 0000000..55b25f8 Binary files /dev/null and b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSans.woff differ diff --git a/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSansCondensed.woff b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSansCondensed.woff new file mode 100644 index 0000000..aedbd93 Binary files /dev/null and b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/OpenSansCondensed.woff differ diff --git a/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/bootstrap b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/bootstrap new file mode 100644 index 0000000..5e1bd51 --- /dev/null +++ b/CONF-IOB/Donati/1501_172/MP-MON-DEMO_files/bootstrap @@ -0,0 +1 @@ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(n){"use strict";var t=n.fn.jquery.split(" ")[0].split(".");if(t[0]<2&&t[1]<9||1==t[0]&&9==t[1]&&t[2]<1||t[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4");}(jQuery);+function(n){"use strict";function t(){var i=document.createElement("bootstrap"),n={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var t in n)if(void 0!==i.style[t])return{end:n[t]};return!1}n.fn.emulateTransitionEnd=function(t){var i=!1,u=this,r;n(this).one("bsTransitionEnd",function(){i=!0});return r=function(){i||n(u).trigger(n.support.transition.end)},setTimeout(r,t),this};n(function(){n.support.transition=t();n.support.transition&&(n.event.special.bsTransitionEnd={bindType:n.support.transition.end,delegateType:n.support.transition.end,handle:function(t){if(n(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}})})}(jQuery);+function(n){"use strict";function u(i){return this.each(function(){var r=n(this),u=r.data("bs.alert");u||r.data("bs.alert",u=new t(this));"string"==typeof i&&u[i].call(r)})}var i='[data-dismiss="alert"]',t=function(t){n(t).on("click",i,this.close)},r;t.VERSION="3.3.7";t.TRANSITION_DURATION=150;t.prototype.close=function(i){function e(){r.detach().trigger("closed.bs.alert").remove()}var f=n(this),u=f.attr("data-target"),r;u||(u=f.attr("href"),u=u&&u.replace(/.*(?=#[^\s]*$)/,""));r=n("#"===u?[]:u);i&&i.preventDefault();r.length||(r=f.closest(".alert"));r.trigger(i=n.Event("close.bs.alert"));i.isDefaultPrevented()||(r.removeClass("in"),n.support.transition&&r.hasClass("fade")?r.one("bsTransitionEnd",e).emulateTransitionEnd(t.TRANSITION_DURATION):e())};r=n.fn.alert;n.fn.alert=u;n.fn.alert.Constructor=t;n.fn.alert.noConflict=function(){return n.fn.alert=r,this};n(document).on("click.bs.alert.data-api",i,t.prototype.close)}(jQuery);+function(n){"use strict";function i(i){return this.each(function(){var u=n(this),r=u.data("bs.button"),f="object"==typeof i&&i;r||u.data("bs.button",r=new t(this,f));"toggle"==i?r.toggle():i&&r.setState(i)})}var t=function(i,r){this.$element=n(i);this.options=n.extend({},t.DEFAULTS,r);this.isLoading=!1},r;t.VERSION="3.3.7";t.DEFAULTS={loadingText:"loading..."};t.prototype.setState=function(t){var i="disabled",r=this.$element,f=r.is("input")?"val":"html",u=r.data();t+="Text";null==u.resetText&&r.data("resetText",r[f]());setTimeout(n.proxy(function(){r[f](null==u[t]?this.options[t]:u[t]);"loadingText"==t?(this.isLoading=!0,r.addClass(i).attr(i,i).prop(i,!0)):this.isLoading&&(this.isLoading=!1,r.removeClass(i).removeAttr(i).prop(i,!1))},this),0)};t.prototype.toggle=function(){var t=!0,i=this.$element.closest('[data-toggle="buttons"]'),n;i.length?(n=this.$element.find("input"),"radio"==n.prop("type")?(n.prop("checked")&&(t=!1),i.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==n.prop("type")&&(n.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),n.prop("checked",this.$element.hasClass("active")),t&&n.trigger("change")):(this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active"))};r=n.fn.button;n.fn.button=i;n.fn.button.Constructor=t;n.fn.button.noConflict=function(){return n.fn.button=r,this};n(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(t){var r=n(t.target).closest(".btn");i.call(r,"toggle");n(t.target).is('input[type="radio"], input[type="checkbox"]')||(t.preventDefault(),r.is("input,button")?r.trigger("focus"):r.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(t){n(t.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(t.type))})}(jQuery);+function(n){"use strict";function i(i){return this.each(function(){var u=n(this),r=u.data("bs.carousel"),f=n.extend({},t.DEFAULTS,u.data(),"object"==typeof i&&i),e="string"==typeof i?i:f.slide;r||u.data("bs.carousel",r=new t(this,f));"number"==typeof i?r.to(i):e?r[e]():f.interval&&r.pause().cycle()})}var t=function(t,i){this.$element=n(t);this.$indicators=this.$element.find(".carousel-indicators");this.options=i;this.paused=null;this.sliding=null;this.interval=null;this.$active=null;this.$items=null;this.options.keyboard&&this.$element.on("keydown.bs.carousel",n.proxy(this.keydown,this));"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",n.proxy(this.pause,this)).on("mouseleave.bs.carousel",n.proxy(this.cycle,this))},u,r;t.VERSION="3.3.7";t.TRANSITION_DURATION=600;t.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0};t.prototype.keydown=function(n){if(!/input|textarea/i.test(n.target.tagName)){switch(n.which){case 37:this.prev();break;case 39:this.next();break;default:return}n.preventDefault()}};t.prototype.cycle=function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(n.proxy(this.next,this),this.options.interval)),this};t.prototype.getItemIndex=function(n){return this.$items=n.parent().children(".item"),this.$items.index(n||this.$active)};t.prototype.getItemForDirection=function(n,t){var i=this.getItemIndex(t),f="prev"==n&&0===i||"next"==n&&i==this.$items.length-1,r,u;return f&&!this.options.wrap?t:(r="prev"==n?-1:1,u=(i+r)%this.$items.length,this.$items.eq(u))};t.prototype.to=function(n){var i=this,t=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(n>this.$items.length-1||n<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){i.to(n)}):t==n?this.pause().cycle():this.slide(n>t?"next":"prev",this.$items.eq(n))};t.prototype.pause=function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&n.support.transition&&(this.$element.trigger(n.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this};t.prototype.next=function(){if(!this.sliding)return this.slide("next")};t.prototype.prev=function(){if(!this.sliding)return this.slide("prev")};t.prototype.slide=function(i,r){var e=this.$element.find(".item.active"),u=r||this.getItemForDirection(i,e),l=this.interval,f="next"==i?"left":"right",a=this,o,s,h,c;return u.hasClass("active")?this.sliding=!1:(o=u[0],s=n.Event("slide.bs.carousel",{relatedTarget:o,direction:f}),(this.$element.trigger(s),!s.isDefaultPrevented())?((this.sliding=!0,l&&this.pause(),this.$indicators.length)&&(this.$indicators.find(".active").removeClass("active"),h=n(this.$indicators.children()[this.getItemIndex(u)]),h&&h.addClass("active")),c=n.Event("slid.bs.carousel",{relatedTarget:o,direction:f}),n.support.transition&&this.$element.hasClass("slide")?(u.addClass(i),u[0].offsetWidth,e.addClass(f),u.addClass(f),e.one("bsTransitionEnd",function(){u.removeClass([i,f].join(" ")).addClass("active");e.removeClass(["active",f].join(" "));a.sliding=!1;setTimeout(function(){a.$element.trigger(c)},0)}).emulateTransitionEnd(t.TRANSITION_DURATION)):(e.removeClass("active"),u.addClass("active"),this.sliding=!1,this.$element.trigger(c)),l&&this.cycle(),this):void 0)};u=n.fn.carousel;n.fn.carousel=i;n.fn.carousel.Constructor=t;n.fn.carousel.noConflict=function(){return n.fn.carousel=u,this};r=function(t){var o,r=n(this),u=n(r.attr("data-target")||(o=r.attr("href"))&&o.replace(/.*(?=#[^\s]+$)/,"")),e,f;u.hasClass("carousel")&&(e=n.extend({},u.data(),r.data()),f=r.attr("data-slide-to"),f&&(e.interval=!1),i.call(u,e),f&&u.data("bs.carousel").to(f),t.preventDefault())};n(document).on("click.bs.carousel.data-api","[data-slide]",r).on("click.bs.carousel.data-api","[data-slide-to]",r);n(window).on("load",function(){n('[data-ride="carousel"]').each(function(){var t=n(this);i.call(t,t.data())})})}(jQuery);+function(n){"use strict";function r(t){var i,r=t.attr("data-target")||(i=t.attr("href"))&&i.replace(/.*(?=#[^\s]+$)/,"");return n(r)}function i(i){return this.each(function(){var u=n(this),r=u.data("bs.collapse"),f=n.extend({},t.DEFAULTS,u.data(),"object"==typeof i&&i);!r&&f.toggle&&/show|hide/.test(i)&&(f.toggle=!1);r||u.data("bs.collapse",r=new t(this,f));"string"==typeof i&&r[i]()})}var t=function(i,r){this.$element=n(i);this.options=n.extend({},t.DEFAULTS,r);this.$trigger=n('[data-toggle="collapse"][href="#'+i.id+'"],[data-toggle="collapse"][data-target="#'+i.id+'"]');this.transitioning=null;this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger);this.options.toggle&&this.toggle()},u;t.VERSION="3.3.7";t.TRANSITION_DURATION=350;t.DEFAULTS={toggle:!0};t.prototype.dimension=function(){var n=this.$element.hasClass("width");return n?"width":"height"};t.prototype.show=function(){var f,r,e,u,o,s;if(!this.transitioning&&!this.$element.hasClass("in")&&(r=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing"),!(r&&r.length&&(f=r.data("bs.collapse"),f&&f.transitioning))&&(e=n.Event("show.bs.collapse"),this.$element.trigger(e),!e.isDefaultPrevented()))){if(r&&r.length&&(i.call(r,"hide"),f||r.data("bs.collapse",null)),u=this.dimension(),this.$element.removeClass("collapse").addClass("collapsing")[u](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1,o=function(){this.$element.removeClass("collapsing").addClass("collapse in")[u]("");this.transitioning=0;this.$element.trigger("shown.bs.collapse")},!n.support.transition)return o.call(this);s=n.camelCase(["scroll",u].join("-"));this.$element.one("bsTransitionEnd",n.proxy(o,this)).emulateTransitionEnd(t.TRANSITION_DURATION)[u](this.$element[0][s])}};t.prototype.hide=function(){var r,i,u;if(!this.transitioning&&this.$element.hasClass("in")&&(r=n.Event("hide.bs.collapse"),this.$element.trigger(r),!r.isDefaultPrevented()))return i=this.dimension(),this.$element[i](this.$element[i]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1,u=function(){this.transitioning=0;this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")},n.support.transition?void this.$element[i](0).one("bsTransitionEnd",n.proxy(u,this)).emulateTransitionEnd(t.TRANSITION_DURATION):u.call(this)};t.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};t.prototype.getParent=function(){return n(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(n.proxy(function(t,i){var u=n(i);this.addAriaAndCollapsedClass(r(u),u)},this)).end()};t.prototype.addAriaAndCollapsedClass=function(n,t){var i=n.hasClass("in");n.attr("aria-expanded",i);t.toggleClass("collapsed",!i).attr("aria-expanded",i)};u=n.fn.collapse;n.fn.collapse=i;n.fn.collapse.Constructor=t;n.fn.collapse.noConflict=function(){return n.fn.collapse=u,this};n(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(t){var u=n(this);u.attr("data-target")||t.preventDefault();var f=r(u),e=f.data("bs.collapse"),o=e?"toggle":u.data();i.call(f,o)})}(jQuery);+function(n){"use strict";function r(t){var i=t.attr("data-target"),r;return i||(i=t.attr("href"),i=i&&/#[A-Za-z]/.test(i)&&i.replace(/.*(?=#[^\s]*$)/,"")),r=i&&n(i),r&&r.length?r:t.parent()}function u(t){t&&3===t.which||(n(o).remove(),n(i).each(function(){var u=n(this),i=r(u),f={relatedTarget:this};i.hasClass("open")&&(t&&"click"==t.type&&/input|textarea/i.test(t.target.tagName)&&n.contains(i[0],t.target)||(i.trigger(t=n.Event("hide.bs.dropdown",f)),t.isDefaultPrevented()||(u.attr("aria-expanded","false"),i.removeClass("open").trigger(n.Event("hidden.bs.dropdown",f)))))}))}function e(i){return this.each(function(){var r=n(this),u=r.data("bs.dropdown");u||r.data("bs.dropdown",u=new t(this));"string"==typeof i&&u[i].call(r)})}var o=".dropdown-backdrop",i='[data-toggle="dropdown"]',t=function(t){n(t).on("click.bs.dropdown",this.toggle)},f;t.VERSION="3.3.7";t.prototype.toggle=function(t){var f=n(this),i,o,e;if(!f.is(".disabled, :disabled")){if(i=r(f),o=i.hasClass("open"),u(),!o){if("ontouchstart"in document.documentElement&&!i.closest(".navbar-nav").length&&n(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(n(this)).on("click",u),e={relatedTarget:this},i.trigger(t=n.Event("show.bs.dropdown",e)),t.isDefaultPrevented())return;f.trigger("focus").attr("aria-expanded","true");i.toggleClass("open").trigger(n.Event("shown.bs.dropdown",e))}return!1}};t.prototype.keydown=function(t){var e,o,s,h,f,u;if(/(38|40|27|32)/.test(t.which)&&!/input|textarea/i.test(t.target.tagName)&&(e=n(this),t.preventDefault(),t.stopPropagation(),!e.is(".disabled, :disabled"))){if(o=r(e),s=o.hasClass("open"),!s&&27!=t.which||s&&27==t.which)return 27==t.which&&o.find(i).trigger("focus"),e.trigger("click");h=" li:not(.disabled):visible a";f=o.find(".dropdown-menu"+h);f.length&&(u=f.index(t.target),38==t.which&&u>0&&u--,40==t.which&&udocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&n?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!n?this.scrollbarWidth:""})};t.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})};t.prototype.checkScrollbar=function(){var n=window.innerWidth,t;n||(t=document.documentElement.getBoundingClientRect(),n=t.right-Math.abs(t.left));this.bodyIsOverflowing=document.body.clientWidth
<\/div>
<\/div><\/div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}};t.prototype.init=function(t,i,r){var f,e,u,o,s;if(this.enabled=!0,this.type=t,this.$element=n(i),this.options=this.getOptions(r),this.$viewport=this.options.viewport&&n(n.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(f=this.options.trigger.split(" "),e=f.length;e--;)if(u=f[e],"click"==u)this.$element.on("click."+this.type,this.options.selector,n.proxy(this.toggle,this));else"manual"!=u&&(o="hover"==u?"mouseenter":"focusin",s="hover"==u?"mouseleave":"focusout",this.$element.on(o+"."+this.type,this.options.selector,n.proxy(this.enter,this)),this.$element.on(s+"."+this.type,this.options.selector,n.proxy(this.leave,this)));this.options.selector?this._options=n.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()};t.prototype.getDefaults=function(){return t.DEFAULTS};t.prototype.getOptions=function(t){return t=n.extend({},this.getDefaults(),this.$element.data(),t),t.delay&&"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),t};t.prototype.getDelegateOptions=function(){var t={},i=this.getDefaults();return this._options&&n.each(this._options,function(n,r){i[n]!=r&&(t[n]=r)}),t};t.prototype.enter=function(t){var i=t instanceof this.constructor?t:n(t.currentTarget).data("bs."+this.type);return i||(i=new this.constructor(t.currentTarget,this.getDelegateOptions()),n(t.currentTarget).data("bs."+this.type,i)),t instanceof n.Event&&(i.inState["focusin"==t.type?"focus":"hover"]=!0),i.tip().hasClass("in")||"in"==i.hoverState?void(i.hoverState="in"):(clearTimeout(i.timeout),i.hoverState="in",i.options.delay&&i.options.delay.show?void(i.timeout=setTimeout(function(){"in"==i.hoverState&&i.show()},i.options.delay.show)):i.show())};t.prototype.isInStateTrue=function(){for(var n in this.inState)if(this.inState[n])return!0;return!1};t.prototype.leave=function(t){var i=t instanceof this.constructor?t:n(t.currentTarget).data("bs."+this.type);if(i||(i=new this.constructor(t.currentTarget,this.getDelegateOptions()),n(t.currentTarget).data("bs."+this.type,i)),t instanceof n.Event&&(i.inState["focusout"==t.type?"focus":"hover"]=!1),!i.isInStateTrue())return clearTimeout(i.timeout),i.hoverState="out",i.options.delay&&i.options.delay.hide?void(i.timeout=setTimeout(function(){"out"==i.hoverState&&i.hide()},i.options.delay.hide)):i.hide()};t.prototype.show=function(){var c=n.Event("show.bs."+this.type),l,p,e,w,h;if(this.hasContent()&&this.enabled){if(this.$element.trigger(c),l=n.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]),c.isDefaultPrevented()||!l)return;var u=this,r=this.tip(),a=this.getUID(this.type);this.setContent();r.attr("id",a);this.$element.attr("aria-describedby",a);this.options.animation&&r.addClass("fade");var i="function"==typeof this.options.placement?this.options.placement.call(this,r[0],this.$element[0]):this.options.placement,v=/\s?auto?\s?/i,y=v.test(i);y&&(i=i.replace(v,"")||"top");r.detach().css({top:0,left:0,display:"block"}).addClass(i).data("bs."+this.type,this);this.options.container?r.appendTo(this.options.container):r.insertAfter(this.$element);this.$element.trigger("inserted.bs."+this.type);var f=this.getPosition(),o=r[0].offsetWidth,s=r[0].offsetHeight;y&&(p=i,e=this.getPosition(this.$viewport),i="bottom"==i&&f.bottom+s>e.bottom?"top":"top"==i&&f.top-se.width?"left":"left"==i&&f.left-ou.top+u.height&&(f.top=u.top+u.height-s)):(h=t.left-e,c=t.left+e+i,hu.right&&(f.left=u.left+u.width-c)),f):f};t.prototype.getTitle=function(){var t=this.$element,n=this.options;return t.attr("data-original-title")||("function"==typeof n.title?n.title.call(t[0]):n.title)};t.prototype.getUID=function(n){do n+=~~(1e6*Math.random());while(document.getElementById(n));return n};t.prototype.tip=function(){if(!this.$tip&&(this.$tip=n(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip};t.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")};t.prototype.enable=function(){this.enabled=!0};t.prototype.disable=function(){this.enabled=!1};t.prototype.toggleEnabled=function(){this.enabled=!this.enabled};t.prototype.toggle=function(t){var i=this;t&&(i=n(t.currentTarget).data("bs."+this.type),i||(i=new this.constructor(t.currentTarget,this.getDelegateOptions()),n(t.currentTarget).data("bs."+this.type,i)));t?(i.inState.click=!i.inState.click,i.isInStateTrue()?i.enter(i):i.leave(i)):i.tip().hasClass("in")?i.leave(i):i.enter(i)};t.prototype.destroy=function(){var n=this;clearTimeout(this.timeout);this.hide(function(){n.$element.off("."+n.type).removeData("bs."+n.type);n.$tip&&n.$tip.detach();n.$tip=null;n.$arrow=null;n.$viewport=null;n.$element=null})};i=n.fn.tooltip;n.fn.tooltip=r;n.fn.tooltip.Constructor=t;n.fn.tooltip.noConflict=function(){return n.fn.tooltip=i,this}}(jQuery);+function(n){"use strict";function r(i){return this.each(function(){var u=n(this),r=u.data("bs.popover"),f="object"==typeof i&&i;!r&&/destroy|hide/.test(i)||(r||u.data("bs.popover",r=new t(this,f)),"string"==typeof i&&r[i]())})}var t=function(n,t){this.init("popover",n,t)},i;if(!n.fn.tooltip)throw new Error("Popover requires tooltip.js");t.VERSION="3.3.7";t.DEFAULTS=n.extend({},n.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'