diff --git a/elab_orchestrator.py b/elab_orchestrator.py index a6e3cc8..56a8b3f 100755 --- a/elab_orchestrator.py +++ b/elab_orchestrator.py @@ -1,77 +1,134 @@ #!.venv/bin/python # Import necessary libraries -import mysql.connector import logging -import importlib -import time import asyncio +import os +import aiomysql +import contextvars import subprocess + # Import custom modules for configuration and database connection -from utils.config import loader_ftp_csv as setting -from utils.database.connection import connetti_db -from utils.database.loader_action import get_matlab_cmd +from utils.config import loader_matlab_elab as setting from utils.database import DATA_LOADED +from utils.database.matlab_query import get_matlab_command +from utils.csv.loaders import get_next_csv_atomic + + +# Crea una context variable per identificare il worker +worker_context = contextvars.ContextVar('worker_id', default='00') + +# Formatter personalizzato che include il worker_id +class WorkerFormatter(logging.Formatter): + def format(self, record): + record.worker_id = worker_context.get() + return super().format(record) # Initialize the logger for this module -logger = logging.getLogger(__name__) +logger = logging.getLogger() -# Function to elaborate CSV data -async def run_matlab_elab(id: int, unit_name: str, unit_type: str, tool_name: str, tool_type: str, semaphore: asyncio.Semaphore) -> bool: - async with semaphore: - if get_matlab_cmd(cfg, unit_name, tool_name): - # If a record is found, lock it by updating the 'locked' field to 1 +# Delay tra un processamento CSV e il successivo (in secondi) +ELAB_PROCESSING_DELAY = 0.2 +# Tempo di attesa se non ci sono record da elaborare +NO_RECORD_SLEEP = 60 +async def worker(worker_id: int, cfg: object, pool) -> None: + # Imposta il context per questo worker + worker_context.set(f"W{worker_id}") + debug_mode = (logging.getLogger().getEffectiveLevel() == logging.DEBUG) + logger.info("Avviato") + while True: + try: + logger.info("Inizio elaborazione") + record = await get_next_csv_atomic(pool, cfg.dbrectable, DATA_LOADED) + + if record: + id, unit_type, tool_type, unit_name, tool_name = [x.lower().replace(" ", "_") if isinstance(x, str) else x for x in record] + matlab_info = await get_matlab_command(cfg, tool_name, unit_name) + matlab_cmd = f"timeout {cfg.timeout} ./run_{matlab_info['matcall']}.sh {cfg.matlab_runtime} {unit_name} {tool_name}" + + # matlab_error_filename = f'{cfg.matlab_error_path}{unit_name}{tool_name}_output_error.txt' + + success = await subprocess.run(matlab_cmd, + cwd=cfg.matlab_func_path, + capture_output=True, + text=True, + check=True) + + if not success: + logger.error("Errore durante l'elaborazione") + await asyncio.sleep(ELAB_PROCESSING_DELAY) + else: + logger.debug("Nessun record disponibile") + await asyncio.sleep(NO_RECORD_SLEEP) + + except Exception as e: + logger.error(f"Errore durante l'esecuzione: {e}", exc_info=debug_mode) + await asyncio.sleep(1) async def main(): - # Load the configuration settings + """Main function: avvia i worker e gestisce il ciclo principale.""" + logger.info("Avvio del sistema...") + cfg = setting.Config() + logger.info("Configurazione caricata correttamente") try: - # Configure logging to write log messages to a file with a specific format - logging.basicConfig( - format="%(asctime)s - PID: %(process)d.%(name)s.%(levelname)s: %(message)s ", - filename=cfg.logfilename, - level=logging.INFO, + # Configura il logging globale + log_level = os.getenv("LOG_LEVEL", "INFO").upper() + debug_mode = (logging.getLogger().getEffectiveLevel() == logging.DEBUG) + + # Configura il logging con il formatter personalizzato + handler = logging.FileHandler(cfg.logfilename) + formatter = WorkerFormatter( + "%(asctime)s - PID: %(process)d.Worker-%(worker_id)s.%(name)s.%(funcName)s.%(levelname)s: %(message)s" + ) + handler.setFormatter(formatter) + + # Rimuovi eventuali handler esistenti e aggiungi il nostro + logger.handlers.clear() + logger.addHandler(handler) + logger.setLevel(getattr(logging, log_level)) + + logger.info("Logging configurato correttamente") + + # Numero massimo di worker concorrenti + logger.info(f"Avvio di {cfg.max_threads} worker concorrenti") + + pool = await aiomysql.create_pool( + host=cfg.dbhost, + user=cfg.dbuser, + password=cfg.dbpass, + db=cfg.dbname, + minsize=4, + maxsize=cfg.max_threads*4, + pool_recycle=3600 ) + # Avvia i worker + workers = [ + asyncio.create_task(worker(i, cfg, pool)) + for i in range(cfg.max_threads) + ] - # Limita il numero di esecuzioni concorrenti a max_threads - semaphore = asyncio.Semaphore(cfg.max_threads) - running_tasks = set() + logger.info("Sistema avviato correttamente. In attesa di nuovi task...") - # Enter an infinite loop to continuously process records - while True: - try: - # Establish a database connection - with connetti_db(cfg) as conn: - cur = conn.cursor() - # Select a single record from the raw data table that is not currently locked and has a status of 0 - cur.execute(f'select id, unit_name, unit_type, tool_name, tool_type from {cfg.dbname}.{cfg.dbrectable} where locked = 0 and status = {DATA_LOADED} limit 1') - id, unit_name, unit_type, tool_name, tool_type = cur.fetchone() - if id: - task = asyncio.create_task(run_matlab_elab(id, unit_name, unit_type, tool_name, tool_type, semaphore)) - running_tasks.add(task) - # Rimuovi i task completati dal set - running_tasks = {t for t in running_tasks if not t.done()} - - - # If a record was successfully processed, log the number of threads currently running - #logger.info(f"Threads in execution: {len(threads)}") - except Exception as e: - logger.info(f"Error: {e}.") + try: + await asyncio.gather(*workers, return_exceptions=debug_mode) + finally: + pool.close() + await pool.wait_closed() except KeyboardInterrupt: - # Handle a keyboard interrupt (e.g., Ctrl+C) to gracefully shut down the program - logger.info("Info: Shutdown requested...exiting") + logger.info("Info: Shutdown richiesto... chiusura in corso") except Exception as e: - logger.info(f"Error: {e}.") + logger.error(f"Errore principale: {e}", exc_info=debug_mode) if __name__ == "__main__": asyncio.run(main()) \ No newline at end of file diff --git a/env/elab.ini b/env/elab.ini index e69de29..fedad1a 100644 --- a/env/elab.ini +++ b/env/elab.ini @@ -0,0 +1,14 @@ +[logging] + logFilename = ./load_raw_data.log + +[threads] + max_num = 20 + +[matlab] + runtime = "/usr/local/MATLAB/MATLAB_Runtime/v93" + func_path = "/usr/local/matlab_func/" + timeout = 1800 + error = "" + error_path = "/tmp/" + + diff --git a/load_orchestrator.py b/load_orchestrator.py index fa5c81b..c5afc4d 100755 --- a/load_orchestrator.py +++ b/load_orchestrator.py @@ -12,6 +12,8 @@ import contextvars from utils.config import loader_load_data as setting from utils.database import CSV_RECEIVED +from utils.csv.loaders import get_next_csv_atomic + # Crea una context variable per identificare il worker worker_context = contextvars.ContextVar('worker_id', default='00') @@ -29,41 +31,6 @@ CSV_PROCESSING_DELAY = 0.2 # Tempo di attesa se non ci sono record da elaborare NO_RECORD_SLEEP = 60 -async def get_next_csv_atomic(pool, table_name): - """Preleva atomicamente il prossimo CSV da elaborare""" - async with pool.acquire() as conn: - # IMPORTANTE: Disabilita autocommit per questa transazione - await conn.begin() - - try: - async with conn.cursor() as cur: - # Usa SELECT FOR UPDATE per lock atomico - await cur.execute(f""" - SELECT id, unit_type, tool_type, unit_name, tool_name - FROM {table_name} - WHERE locked = 0 AND status = %s - ORDER BY id - LIMIT 1 - FOR UPDATE SKIP LOCKED - """, (CSV_RECEIVED,)) - - result = await cur.fetchone() - if result: - await cur.execute(f""" - UPDATE {table_name} - SET locked = 1 - WHERE id = %s - """, (result[0],)) - - # Commit esplicito per rilasciare il lock - await conn.commit() - return result - - except Exception as e: - # Rollback in caso di errore - await conn.rollback() - raise e - async def worker(worker_id: int, cfg: object, pool) -> None: # Imposta il context per questo worker worker_context.set(f"W{worker_id}") @@ -75,7 +42,7 @@ async def worker(worker_id: int, cfg: object, pool) -> None: try: logger.info("Inizio elaborazione") - record = await get_next_csv_atomic(pool, cfg.dbrectable) + record = await get_next_csv_atomic(pool, cfg.dbrectable, CSV_RECEIVED) if record: success = await load_csv(record, cfg, pool) diff --git a/old_script/TS_PiniScript.py b/old_script/TS_PiniScript.py new file mode 100755 index 0000000..148010d --- /dev/null +++ b/old_script/TS_PiniScript.py @@ -0,0 +1,2584 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config +from datetime import datetime +import math +import shutil +from pyproj import Transformer +import utm +import json + +def find_nearest_element(target_time_millis, array): + return min(array, key=lambda elem: abs(elem[0] - target_time_millis)) +def find_nearest_element_coppie(target_time_millis, array): + return min(array, key=lambda elem: abs(elem[7].timestamp()*1000 - target_time_millis)) + +def removeDuplicates(lst): + return list(set([i for i in lst])) + +def getDataFromCsvAndInsert(pathFile): + #try: + print(pathFile) + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + if(len(data) > 0 and data is not None): + data.pop(0) #rimuove header + + #try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor() + #except Error as e: + # print('Error:', e) + + folder_name = pathFile.split("/")[-2]#cartella + + if "[276_208_TS0003]" in pathFile: + folder_name = "TS0003" + elif "[Neuchatel_CDP]" in pathFile: + folder_name = "TS7" + elif "[TS0006_EP28]" in pathFile: + folder_name = "TS0006_EP28" + elif "[TS0007_ChesaArcoiris]" in pathFile: + folder_name = "TS0007_ChesaArcoiris" + elif "[TS0006_EP28_3]" in pathFile: + folder_name = "TS0006_EP28_3" + elif "[TS0006_EP28_4]" in pathFile: + folder_name = "TS0006_EP28_4" + elif "[TS0006_EP28_5]" in pathFile: + folder_name = "TS0006_EP28_5" + elif "[TS18800]" in pathFile: + folder_name = "TS18800" + elif "[Granges_19 100]" in pathFile: + folder_name = "Granges_19 100" + elif "[Granges_19 200]" in pathFile: + folder_name = "Granges_19 200" + elif "[Chesa_Arcoiris_2]" in pathFile: + folder_name = "Chesa_Arcoiris_2" + elif "[TS0006_EP28_1]" in pathFile: + folder_name = "TS0006_EP28_1" + elif "[TS_PS_Petites_Croisettes]" in pathFile: + folder_name = "TS_PS_Petites_Croisettes" + elif "[_Chesa_Arcoiris_1]" in pathFile: + folder_name = "_Chesa_Arcoiris_1" + elif "[TS_test]" in pathFile: + folder_name = "TS_test" + elif "[TS-VIME]" in pathFile: + folder_name = "TS-VIME" + query = "select l.id as lavoro_id, s.id as site_id, st.type_id, s.upgeo_sist_coordinate, s.upgeo_utmzone, s.upgeo_utmhemisphere FROM upgeo_st as st left join upgeo_lavori as l on st.lavoro_id=l.id left join sites as s on s.id=l.site_id where st.name=%s" + cursor.execute(query, [folder_name]) + result = cursor.fetchall() + lavoro_id = result[0][0] + progetto_id = result[0][1] + st_type = result[0][2] + sistema_coordinate = int(result[0][3]) + utm_zone = result[0][4] + utm_hemisphere = False if result[0][5] == "S" else True + soglie = [] + soglieMonitoraggiAggiuntivi = [] + for row in data: + row = row.split(",") + if st_type == 1:#Leica + mira_name = row[0] + easting = row[1] + northing = row[2] + height = row[3] + datet = datetime.strptime(row[4], '%d.%m.%Y %H:%M:%S.%f').strftime("%Y-%m-%d %H:%M:%S") + elif st_type == 4:#Trimble S7 + datet = row[0] + mira_name = row[1] + northing = row[2] + easting = row[3] + height = row[4] + elif st_type == 7:#Trimble S9 + datet = row[0] + mira_name = row[1] + northing = row[2] + easting = row[3] + height = row[4] + elif st_type == 10:#Trimble S7 x-y inverted + datet = row[0] + mira_name = row[1] + northing = row[3] + easting = row[2] + height = row[4] + if sistema_coordinate == 6: + y = float(easting) + x = float(northing) + y_ = float((y - 2600000)/1000000) + x_ = float((x - 1200000)/1000000) + lambda_ = float( 2.6779094 + 4.728982 * y_ + 0.791484 * y_ * x_ + 0.1306 * y_ * pow(x_,2) - 0.0436 * pow(y_,3) ) + phi_ = float( 16.9023892 + 3.238272 * x_ - 0.270978 * pow(y_,2) - 0.002528 * pow(x_,2) - 0.0447 * pow(y_,2) * x_ - 0.0140 * pow(x_,3) ) + lat = float("{:.8f}".format((phi_ * 100 / 36))) + lon = float("{:.8f}".format((lambda_ * 100 / 36))) + elif sistema_coordinate == 7: + result = utm.to_latlon(float(easting), float(northing), utm_zone, northern=utm_hemisphere) + lat = float(result[0]) + lon = float(result[1]) + elif sistema_coordinate == 10: + x_ch1903 = float(easting) + y_ch1903 = float(northing) + transformer = Transformer.from_crs("EPSG:21781", "EPSG:4326") + lat, lon = transformer.transform(x_ch1903, y_ch1903) + else: + lon = float(easting) + lat = float(northing) + + query = "select m.id as mira_id, m.name from upgeo_mire as m join upgeo_lavori as l on m.lavoro_id=l.id where m.name=%s and m.lavoro_id=%s" + cursor.execute(query, [mira_name, lavoro_id]) + result = cursor.fetchall() + if len(result) > 0: #mira esiste + mira_id = result[0][0] + query = "insert ignore into ELABDATAUPGEO (mira_id, EventTimestamp, north, east, elevation, lat, lon, sist_coordinate) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [mira_id, datet, northing, easting, height, lat, lon, sistema_coordinate]) + conn.commit() + else: #mira non esiste + query = "select c.id,c.name,c.upgeo_numero_mire, c.upgeo_numero_mireTot from companies as c join sites as s on c.id=s.company_id where s.id=%s" + cursor.execute(query, [progetto_id]) + result = cursor.fetchall() + company_id = result[0][0] + company_name = result[0][1] + upgeo_numero_mire = result[0][2] + upgeo_numero_mireTot = result[0][3] + if(upgeo_numero_mire < upgeo_numero_mireTot): + query = "insert into upgeo_mire (lavoro_id, name) value(%s,%s)" + cursor.execute(query, [lavoro_id, mira_name]) + conn.commit() + mira_id = cursor.lastrowid + query = "insert ignore into ELABDATAUPGEO (mira_id, EventTimestamp, north, east, elevation, lat, lon, sist_coordinate) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [mira_id, datet, northing, easting, height, lat, lon, sistema_coordinate]) + conn.commit() + query = "select count(m.id) as count_mire FROM upgeo_mire as m join upgeo_lavori as l on l.id=m.lavoro_id join sites as s on s.id=l.site_id join companies as c on c.id=s.company_id where c.id=%s" + cursor.execute(query, [company_id]) + result = cursor.fetchall() + num_mire = result[0][0] + query = "update companies set upgeo_numero_mire=%s where id=%s" + cursor.execute(query, [num_mire, company_id]) + conn.commit() + query = "select m.id as mira_id, m.name, IFNULL(m.multipleDateRange,'vuoto') as multipleDateRange, l.name as lavoro_name from upgeo_mire as m join upgeo_lavori as l on m.lavoro_id=l.id where m.abilitato=1 and m.name=%s and m.lavoro_id=%s" + cursor.execute(query, [mira_name, lavoro_id]) + result = cursor.fetchall() + if len(result) > 0: + soglie.append((progetto_id, lavoro_id, result[0][0], mira_name, result[0][2], result[0][3])) + soglie = removeDuplicates(soglie) + query = "select m.id AS mira_id, m.name, IFNULL(m.multipleDateRange, 'vuoto') AS multipleDateRange, l.name AS lavoro_name from upgeo_mire as m join upgeo_lavori as l on m.lavoro_id=l.id where m.abilitato=1 and m.lavoro_id=%s" + cursor.execute(query, [lavoro_id]) + resultMireMonitoraggiAggiuntivi = cursor.fetchall() + if len(resultMireMonitoraggiAggiuntivi) > 0: + for s in resultMireMonitoraggiAggiuntivi: + soglieMonitoraggiAggiuntivi.append((progetto_id, lavoro_id, s[0], s[1], s[2], s[3])) + soglieMonitoraggiAggiuntivi = removeDuplicates(soglieMonitoraggiAggiuntivi) + arrayCoppie = {} + arrayCoppieMuro = {} + arrayCoppieTralicci = {} + arrayBinari = {} + for s in soglie: + dictSoglieAlarmData = {} + progetto_id = s[0] + lavoro_id = s[1] + mira_id = s[2] + mira_name = s[3] + print("dentro soglie: ",mira_name) + multipleDateRange = s[4] + lavoro_name = s[5] + maxValue = 99999999 + query = "select IFNULL(l.areaAttenzioneInizioN,'vuoto') as areaAttenzioneInizioN, IFNULL(l.areaInterventoInizioN,'vuoto') as areaInterventoInizioN, IFNULL(l.areaInterventoImmediatoInizioN,'vuoto') as areaInterventoImmediatoInizioN, IFNULL(l.areaAttenzioneInizioE,'vuoto') as areaAttenzioneInizioE, IFNULL(l.areaInterventoInizioE,'vuoto') as areaInterventoInizioE, IFNULL(l.areaInterventoImmediatoInizioE,'vuoto') as areaInterventoImmediatoInizioE, IFNULL(l.areaAttenzioneInizioH,'vuoto') as areaAttenzioneInizioH, IFNULL(l.areaInterventoInizioH,'vuoto') as areaInterventoInizioH, IFNULL(l.areaInterventoImmediatoInizioH,'vuoto') as areaInterventoImmediatoInizioH, IFNULL(l.areaAttenzioneInizioR2D,'vuoto') as areaAttenzioneInizioR2D, IFNULL(l.areaInterventoInizioR2D,'vuoto') as areaInterventoInizioR2D, IFNULL(l.areaInterventoImmediatoInizioR2D,'vuoto') as areaInterventoImmediatoInizioR2D, IFNULL(l.areaAttenzioneInizioR3D,'vuoto') as areaAttenzioneInizioR3D, IFNULL(l.areaInterventoInizioR3D,'vuoto') as areaInterventoInizioR3D, IFNULL(l.areaInterventoImmediatoInizioR3D,'vuoto') as areaInterventoImmediatoInizioR3D, l.email_livello_unoN, l.sms_livello_unoN, l.email_livello_dueN, l.sms_livello_dueN, l.email_livello_treN, l.sms_livello_treN, l.email_livello_unoE, l.sms_livello_unoE, l.email_livello_dueE, l.sms_livello_dueE, l.email_livello_treE, l.sms_livello_treE, l.email_livello_unoH, l.sms_livello_unoH, l.email_livello_dueH, l.sms_livello_dueH, l.email_livello_treH, l.sms_livello_treH, l.email_livello_unoR2D, l.sms_livello_unoR2D, l.email_livello_dueR2D, l.sms_livello_dueR2D, l.email_livello_treR2D, l.sms_livello_treR2D, l.email_livello_unoR3D, l.sms_livello_unoR3D, l.email_livello_dueR3D, l.sms_livello_dueR3D, l.email_livello_treR3D, l.sms_livello_treR3D, IFNULL(l.lista_monitoring_type, '') as lista_monitoring_type, IFNULL(m.areaAttenzioneInizioN,'vuoto') as areaAttenzioneInizioN_mira, IFNULL(m.areaInterventoInizioN,'vuoto') as areaInterventoInizioN_mira, IFNULL(m.areaInterventoImmediatoInizioN,'vuoto') as areaInterventoImmediatoInizioN_mira, IFNULL(m.areaAttenzioneInizioE,'vuoto') as areaAttenzioneInizioE_mira, IFNULL(m.areaInterventoInizioE,'vuoto') as areaInterventoInizioE_mira, IFNULL(m.areaInterventoImmediatoInizioE,'vuoto') as areaInterventoImmediatoInizioE_mira, IFNULL(m.areaAttenzioneInizioH,'vuoto') as areaAttenzioneInizioH_mira, IFNULL(m.areaInterventoInizioH,'vuoto') as areaInterventoInizioH_mira, IFNULL(m.areaInterventoImmediatoInizioH,'vuoto') as areaInterventoImmediatoInizioH_mira, IFNULL(m.areaAttenzioneInizioR2D,'vuoto') as areaAttenzioneInizioR2D_mira, IFNULL(m.areaInterventoInizioR2D,'vuoto') as areaInterventoInizioR2D_mira, IFNULL(m.areaInterventoImmediatoInizioR2D,'vuoto') as areaInterventoImmediatoInizioR2D_mira, IFNULL(m.areaAttenzioneInizioR3D,'vuoto') as areaAttenzioneInizioR3D_mira, IFNULL(m.areaInterventoInizioR3D,'vuoto') as areaInterventoInizioR3D_mira, IFNULL(m.areaInterventoImmediatoInizioR3D,'vuoto') as areaInterventoImmediatoInizioR3D_mira, m.email_livello_unoN as email_livello_unoN_mira, m.sms_livello_unoN as sms_livello_unoN_mira, m.email_livello_dueN as email_livello_dueN_mira, m.sms_livello_dueN as sms_livello_dueN_mira, m.email_livello_treN as email_livello_treN_mira, m.sms_livello_treN as sms_livello_treN_mira, m.email_livello_unoE as email_livello_unoE_mira, m.sms_livello_unoE as sms_livello_unoE_mira, m.email_livello_dueE as email_livello_dueE_mira, m.sms_livello_dueE as sms_livello_dueE_mira, m.email_livello_treE as email_livello_treE_mira, m.sms_livello_treE as sms_livello_treE_mira, m.email_livello_unoH as email_livello_unoH_mira, m.sms_livello_unoH as sms_livello_unoH_mira, m.email_livello_dueH as email_livello_dueH_mira, m.sms_livello_dueH as sms_livello_dueH_mira, m.email_livello_treH as email_livello_treH_mira, m.sms_livello_treH as sms_livello_treH_mira, m.email_livello_unoR2D as email_livello_unoR2D_mira, m.sms_livello_unoR2D as sms_livello_unoR2D_mira, m.email_livello_dueR2D as email_livello_dueR2D_mira, m.sms_livello_dueR2D as sms_livello_dueR2D_mira, m.email_livello_treR2D as email_livello_treR2D_mira, m.sms_livello_treR2D as sms_livello_treR2D_mira, m.email_livello_unoR3D as email_livello_unoR3D_mira, m.sms_livello_unoR3D as sms_livello_unoR3D_mira, m.email_livello_dueR3D as email_livello_dueR3D_mira, m.sms_livello_dueR3D as sms_livello_dueR3D_mira, m.email_livello_treR3D as email_livello_treR3D_mira, m.sms_livello_treR3D as sms_livello_treR3D_mira from upgeo_lavori as l left join upgeo_mire as m on m.lavoro_id=l.id where l.id=%s and m.id=%s" + #query = "SELECT IFNULL(areaAttenzioneInizioN,'vuoto') AS areaAttenzioneInizioN, IFNULL(areaInterventoInizioN,'vuoto') AS areaInterventoInizioN, IFNULL(areaInterventoImmediatoInizioN,'vuoto') AS areaInterventoImmediatoInizioN, IFNULL(areaAttenzioneInizioE,'vuoto') AS areaAttenzioneInizioE, IFNULL(areaInterventoInizioE,'vuoto') AS areaInterventoInizioE, IFNULL(areaInterventoImmediatoInizioE,'vuoto') AS areaInterventoImmediatoInizioE, IFNULL(areaAttenzioneInizioH,'vuoto') AS areaAttenzioneInizioH, IFNULL(areaInterventoInizioH,'vuoto') AS areaInterventoInizioH, IFNULL(areaInterventoImmediatoInizioH,'vuoto') AS areaInterventoImmediatoInizioH, IFNULL(areaAttenzioneInizioR2D,'vuoto') AS areaAttenzioneInizioR2D, IFNULL(areaInterventoInizioR2D,'vuoto') AS areaInterventoInizioR2D, IFNULL(areaInterventoImmediatoInizioR2D,'vuoto') AS areaInterventoImmediatoInizioR2D, IFNULL(areaAttenzioneInizioR3D,'vuoto') AS areaAttenzioneInizioR3D, IFNULL(areaInterventoInizioR3D,'vuoto') AS areaInterventoInizioR3D, IFNULL(areaInterventoImmediatoInizioR3D,'vuoto') AS areaInterventoImmediatoInizioR3D, email_livello_unoN, sms_livello_unoN, email_livello_dueN, sms_livello_dueN, email_livello_treN, sms_livello_treN, email_livello_unoE, sms_livello_unoE, email_livello_dueE, sms_livello_dueE, email_livello_treE, sms_livello_treE, email_livello_unoH, sms_livello_unoH, email_livello_dueH, sms_livello_dueH, email_livello_treH, sms_livello_treH, email_livello_unoR2D, sms_livello_unoR2D, email_livello_dueR2D, sms_livello_dueR2D, email_livello_treR2D, sms_livello_treR2D, email_livello_unoR3D, sms_livello_unoR3D, email_livello_dueR3D, sms_livello_dueR3D, email_livello_treR3D, sms_livello_treR3D, IFNULL(lista_monitoring_type, '') AS lista_monitoring_type FROM upgeo_lavori WHERE id=%s" + #query = "select IFNULL(areaAttenzioneInizio,'vuoto') as areaAttenzioneInizio, IFNULL(areaInterventoInizio,'vuoto') as areaInterventoInizio, IFNULL(areaInterventoImmediatoInizio,'vuoto') as areaInterventoImmediatoInizio, IFNULL(soglieToSeries,'vuoto') as soglieToSeries, email_livello_uno, sms_livello_uno, email_livello_due, sms_livello_due, email_livello_tre, sms_livello_tre from upgeo_lavori where id=%s" + cursor.execute(query, [lavoro_id, mira_id]) + resultSoglie = cursor.fetchall() + #if(resultSoglie[0][0] != "vuoto" and resultSoglie[0][1] != "vuoto" and resultSoglie[0][2] != "vuoto" and + # resultSoglie[0][3] != "vuoto" and resultSoglie[0][4] != "vuoto" and resultSoglie[0][5] != "vuoto" and + # resultSoglie[0][6] != "vuoto" and resultSoglie[0][7] != "vuoto" and resultSoglie[0][8] != "vuoto" and + # resultSoglie[0][9] != "vuoto" and resultSoglie[0][10] != "vuoto" and resultSoglie[0][11] != "vuoto" and + # resultSoglie[0][12] != "vuoto" and resultSoglie[0][13] != "vuoto" and resultSoglie[0][14] != "vuoto" and + # resultSoglie[0][46] != "vuoto" and resultSoglie[0][47] != "vuoto" and resultSoglie[0][48] != "vuoto" and + # resultSoglie[0][49] != "vuoto" and resultSoglie[0][50] != "vuoto" and resultSoglie[0][51] != "vuoto" and + # resultSoglie[0][52] != "vuoto" and resultSoglie[0][53] != "vuoto" and resultSoglie[0][54] != "vuoto" and + # resultSoglie[0][55] != "vuoto" and resultSoglie[0][56] != "vuoto" and resultSoglie[0][57] != "vuoto" and + # resultSoglie[0][58] != "vuoto" and resultSoglie[0][59] != "vuoto" and resultSoglie[0][60] != "vuoto"): + + if(multipleDateRange != "vuoto"): + for drange in multipleDateRange.split(";"): + if(drange != "" and drange is not None): + fdate = drange.split(",")[0] + ldate = drange.split(",")[1] + #debug + #query = "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id="+str(mira_id)+" and EventTimestamp between "+fdate+" and "+ldate+" order by EventTimestamp asc limit 1)"\ + # "union"\ + # "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id="+str(mira_id)+" and EventTimestamp between "+fdate+" and "+ldate+" order by EventTimestamp desc limit 1)"\ + # "union"\ + # "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id="+str(mira_id)+" and EventTimestamp between "+fdate+" and "+ldate+" order by EventTimestamp desc limit 1 offset 1)" + #print(mira_id, query) + query = "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s and EventTimestamp between %s and %s order by EventTimestamp asc limit 1)"\ + "union"\ + "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s and EventTimestamp between %s and %s order by EventTimestamp desc limit 1)"\ + "union"\ + "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s and EventTimestamp between %s and %s order by EventTimestamp desc limit 1 offset 1)" + cursor.execute(query, [mira_id, fdate, ldate, mira_id, fdate, ldate, mira_id, fdate, ldate]) + res = cursor.fetchall() + #print(fdate, ldate) + #print(mira_id, res) + if(str(lavoro_id) in dictSoglieAlarmData): + dictSoglieAlarmData[str(lavoro_id)].append(res) + else: + dictSoglieAlarmData[str(lavoro_id)] = [] + dictSoglieAlarmData[str(lavoro_id)].append(res) + else: + query = "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s order by EventTimestamp asc limit 1)"\ + "union"\ + "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s order by EventTimestamp desc limit 1)"\ + "union"\ + "(select mira_id, EventTimestamp, north, east, elevation from ELABDATAUPGEO where mira_id=%s order by EventTimestamp desc limit 1 offset 1)" + cursor.execute(query, [mira_id, mira_id, mira_id]) + res = cursor.fetchall() + if(str(lavoro_id) in dictSoglieAlarmData): + dictSoglieAlarmData[str(lavoro_id)].append(res) + else: + dictSoglieAlarmData[str(lavoro_id)] = [] + dictSoglieAlarmData[str(lavoro_id)].append(res) + + #print(dictSoglieAlarmData) + if len(dictSoglieAlarmData[str(lavoro_id)]) > 0: + globalX = 0 + globalY = 0 + globalZ = 0 + globalXPenultimo = 0 + globalYPenultimo = 0 + globalZPenultimo = 0 + for datoAlarm in dictSoglieAlarmData[str(lavoro_id)]: + if(len(datoAlarm) > 0): + #print(len(datoAlarm)) + #print(datoAlarm) + primoDato = datoAlarm[0] + ultimoDato = datoAlarm[0] + penultimoDato = datoAlarm[0] + if(len(datoAlarm) == 2): + ultimoDato = datoAlarm[1] + elif(len(datoAlarm) == 3): + ultimoDato = datoAlarm[1] + penultimoDato = datoAlarm[2] + ultimaDataDato = ultimoDato[1] + x = ((float(ultimoDato[2]) - float(primoDato[2])) + float(globalX))*1000;#m to mm + y = ((float(ultimoDato[3]) - float(primoDato[3])) + float(globalY))*1000;#m to mm + z = ((float(ultimoDato[4]) - float(primoDato[4])) + float(globalZ))*1000;#m to mm + r2d = math.sqrt(pow(float(x), 2) + pow(float(y), 2)) + r3d = math.sqrt(pow(float(x), 2) + pow(float(y), 2) + pow(float(z), 2)) + globalX = (float(ultimoDato[2]) - float(primoDato[2])) + globalY = (float(ultimoDato[3]) - float(primoDato[3])) + globalZ = (float(ultimoDato[4]) - float(primoDato[4])) + ultimaDataDatoPenultimo = penultimoDato[1] + xPenultimo = ((float(penultimoDato[2]) - float(primoDato[2])) + float(globalXPenultimo))*1000;#m to mm + yPenultimo = ((float(penultimoDato[3]) - float(primoDato[3])) + float(globalYPenultimo))*1000;#m to mm + zPenultimo = ((float(penultimoDato[4]) - float(primoDato[4])) + float(globalZPenultimo))*1000;#m to mm + r2dPenultimo = math.sqrt(pow(float(xPenultimo), 2) + pow(float(yPenultimo), 2)) + r3dPenultimo = math.sqrt(pow(float(xPenultimo), 2) + pow(float(yPenultimo), 2) + pow(float(zPenultimo), 2)) + globalXPenultimo = (float(penultimoDato[2]) - float(primoDato[2])) + globalYPenultimo = (float(penultimoDato[3]) - float(primoDato[3])) + globalZPenultimo = (float(penultimoDato[4]) - float(primoDato[4])) + #print(mira_id, z, ultimaDataDato, zPenultimo, ultimaDataDatoPenultimo) + #print(mira_id, primoDato[1], ultimoDato[1], penultimoDato[1]) + soglieN = False + soglieN_mira = False + soglieE = False + soglieE_mira = False + soglieH = False + soglieH_mira = False + soglieR2D = False + soglieR2D_mira = False + soglieR3D = False + soglieR3D_mira = False + if (resultSoglie[0][0] != "vuoto" and resultSoglie[0][1] != "vuoto" and resultSoglie[0][2] != "vuoto"): + soglieN = True + if (resultSoglie[0][46] != "vuoto" and resultSoglie[0][47] != "vuoto" and resultSoglie[0][48] != "vuoto"): + soglieN_mira = True + if (resultSoglie[0][3] != "vuoto" and resultSoglie[0][4] != "vuoto" and resultSoglie[0][5] != "vuoto"): + soglieE = True + if (resultSoglie[0][49] != "vuoto" and resultSoglie[0][50] != "vuoto" and resultSoglie[0][51] != "vuoto"): + soglieE_mira = True + if (resultSoglie[0][6] != "vuoto" and resultSoglie[0][7] != "vuoto" and resultSoglie[0][8] != "vuoto"): + soglieH = True + if (resultSoglie[0][52] != "vuoto" and resultSoglie[0][53] != "vuoto" and resultSoglie[0][54] != "vuoto"): + soglieH_mira = True + if (resultSoglie[0][9] != "vuoto" and resultSoglie[0][10] != "vuoto" and resultSoglie[0][11] != "vuoto"): + soglieR2D = True + if (resultSoglie[0][55] != "vuoto" and resultSoglie[0][56] != "vuoto" and resultSoglie[0][57] != "vuoto"): + soglieR2D_mira = True + if (resultSoglie[0][12] != "vuoto" and resultSoglie[0][13] != "vuoto" and resultSoglie[0][14] != "vuoto"): + soglieR3D = True + if (resultSoglie[0][58] != "vuoto" and resultSoglie[0][59] != "vuoto" and resultSoglie[0][60] != "vuoto"): + soglieR3D_mira = True + print("mira-id: ", mira_id, ultimaDataDato, x, y, z, r2d, r3d) + if(soglieN_mira): + if (resultSoglie[0][46] != "vuoto" and resultSoglie[0][47] != "vuoto" and resultSoglie[0][48] != "vuoto"): + if(abs(x) >= abs(float(resultSoglie[0][46])) and abs(x) <= abs(float(resultSoglie[0][47]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][46])) and abs(xPenultimo) <= abs(float(resultSoglie[0][47]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][47])) and abs(xPenultimo) <= abs(float(resultSoglie[0][48]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][48])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 1, "X", int(resultSoglie[0][61]), int(resultSoglie[0][62])]) + conn.commit() + elif(abs(x) >= abs(float(resultSoglie[0][47])) and abs(x) <= abs(float(resultSoglie[0][48]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(xPenultimo) >= abs(float(resultSoglie[0][46])) and abs(xPenultimo) <= abs(float(resultSoglie[0][47]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 2, "X", int(resultSoglie[0][63]), int(resultSoglie[0][64])]) + conn.commit() + elif not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][46])) and abs(xPenultimo) <= abs(float(resultSoglie[0][47]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][47])) and abs(xPenultimo) <= abs(float(resultSoglie[0][48]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][48])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 2, "X", int(resultSoglie[0][63]), int(resultSoglie[0][64])]) + conn.commit() + elif(abs(x) >= abs(float(resultSoglie[0][48])) and abs(x) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(xPenultimo) >= abs(float(resultSoglie[0][46])) and abs(xPenultimo) <= abs(float(resultSoglie[0][47]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][65]), int(resultSoglie[0][66])]) + conn.commit() + elif(abs(xPenultimo) >= abs(float(resultSoglie[0][47])) and abs(xPenultimo) <= abs(float(resultSoglie[0][48]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][65]), int(resultSoglie[0][66])]) + conn.commit() + elif not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][46])) and abs(xPenultimo) <= abs(float(resultSoglie[0][47]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][47])) and abs(xPenultimo) <= abs(float(resultSoglie[0][48]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][48])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][65]), int(resultSoglie[0][66])]) + conn.commit() + elif(soglieN): + if (resultSoglie[0][0] != "vuoto" and resultSoglie[0][1] != "vuoto" and resultSoglie[0][2] != "vuoto"): + if(abs(x) >= abs(float(resultSoglie[0][0])) and abs(x) <= abs(float(resultSoglie[0][1]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][0])) and abs(xPenultimo) <= abs(float(resultSoglie[0][1]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][1])) and abs(xPenultimo) <= abs(float(resultSoglie[0][2]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][2])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 1, "X", int(resultSoglie[0][15]), int(resultSoglie[0][16])]) + conn.commit() + elif(abs(x) >= abs(float(resultSoglie[0][1])) and abs(x) <= abs(float(resultSoglie[0][2]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(xPenultimo) >= abs(float(resultSoglie[0][0])) and abs(xPenultimo) <= abs(float(resultSoglie[0][1]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 2, "X", int(resultSoglie[0][17]), int(resultSoglie[0][18])]) + conn.commit() + elif not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][0])) and abs(xPenultimo) <= abs(float(resultSoglie[0][1]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][1])) and abs(xPenultimo) <= abs(float(resultSoglie[0][2]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][2])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 2, "X", int(resultSoglie[0][17]), int(resultSoglie[0][18])]) + conn.commit() + elif(abs(x) >= abs(float(resultSoglie[0][2])) and abs(x) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "X", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(xPenultimo) >= abs(float(resultSoglie[0][0])) and abs(xPenultimo) <= abs(float(resultSoglie[0][1]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][19]), int(resultSoglie[0][20])]) + conn.commit() + elif(abs(xPenultimo) >= abs(float(resultSoglie[0][1])) and abs(xPenultimo) <= abs(float(resultSoglie[0][2]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][19]), int(resultSoglie[0][20])]) + conn.commit() + elif not ( (abs(xPenultimo) >= abs(float(resultSoglie[0][0])) and abs(xPenultimo) <= abs(float(resultSoglie[0][1]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][1])) and abs(xPenultimo) <= abs(float(resultSoglie[0][2]))) or + (abs(xPenultimo) >= abs(float(resultSoglie[0][2])) and abs(xPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, x, 3, "X", int(resultSoglie[0][19]), int(resultSoglie[0][20])]) + conn.commit() + if(soglieE_mira): + if (resultSoglie[0][49] != "vuoto" and resultSoglie[0][50] != "vuoto" and resultSoglie[0][51] != "vuoto"): + if(abs(y) >= abs(float(resultSoglie[0][49])) and abs(y) <= abs(float(resultSoglie[0][50]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][49])) and abs(yPenultimo) <= abs(float(resultSoglie[0][50]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][50])) and abs(yPenultimo) <= abs(float(resultSoglie[0][51]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][51])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 1, "Y", int(resultSoglie[0][67]), int(resultSoglie[0][68])]) + conn.commit() + elif(abs(y) >= abs(float(resultSoglie[0][50])) and abs(y) <= abs(float(resultSoglie[0][51]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(yPenultimo) >= abs(float(resultSoglie[0][49])) and abs(yPenultimo) <= abs(float(resultSoglie[0][50]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 2, "Y", int(resultSoglie[0][69]), int(resultSoglie[0][70])]) + conn.commit() + elif not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][49])) and abs(yPenultimo) <= abs(float(resultSoglie[0][50]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][50])) and abs(yPenultimo) <= abs(float(resultSoglie[0][51]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][51])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 2, "Y", int(resultSoglie[0][69]), int(resultSoglie[0][70])]) + conn.commit() + elif(abs(y) >= abs(float(resultSoglie[0][51])) and abs(y) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(yPenultimo) >= abs(float(resultSoglie[0][49])) and abs(yPenultimo) <= abs(float(resultSoglie[0][50]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][71]), int(resultSoglie[0][72])]) + conn.commit() + elif(abs(yPenultimo) >= abs(float(resultSoglie[0][50])) and abs(yPenultimo) <= abs(float(resultSoglie[0][51]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][71]), int(resultSoglie[0][72])]) + conn.commit() + elif not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][49])) and abs(yPenultimo) <= abs(float(resultSoglie[0][50]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][50])) and abs(yPenultimo) <= abs(float(resultSoglie[0][51]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][51])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][71]), int(resultSoglie[0][72])]) + conn.commit() + elif(soglieE): + if (resultSoglie[0][3] != "vuoto" and resultSoglie[0][4] != "vuoto" and resultSoglie[0][5] != "vuoto"): + if(abs(y) >= abs(float(resultSoglie[0][3])) and abs(y) <= abs(float(resultSoglie[0][4]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][3])) and abs(yPenultimo) <= abs(float(resultSoglie[0][4]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][4])) and abs(yPenultimo) <= abs(float(resultSoglie[0][5]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][5])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 1, "Y", int(resultSoglie[0][21]), int(resultSoglie[0][22])]) + conn.commit() + elif(abs(y) >= abs(float(resultSoglie[0][4])) and abs(y) <= abs(float(resultSoglie[0][5]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(yPenultimo) >= abs(float(resultSoglie[0][3])) and abs(yPenultimo) <= abs(float(resultSoglie[0][4]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 2, "Y", int(resultSoglie[0][23]), int(resultSoglie[0][24])]) + conn.commit() + elif not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][3])) and abs(yPenultimo) <= abs(float(resultSoglie[0][4]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][4])) and abs(yPenultimo) <= abs(float(resultSoglie[0][5]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][5])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 2, "Y", int(resultSoglie[0][23]), int(resultSoglie[0][24])]) + conn.commit() + elif(abs(y) >= abs(float(resultSoglie[0][5])) and abs(y) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "Y", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(yPenultimo) >= abs(float(resultSoglie[0][3])) and abs(yPenultimo) <= abs(float(resultSoglie[0][4]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][25]), int(resultSoglie[0][26])]) + conn.commit() + elif(abs(yPenultimo) >= abs(float(resultSoglie[0][4])) and abs(yPenultimo) <= abs(float(resultSoglie[0][5]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][25]), int(resultSoglie[0][26])]) + conn.commit() + elif not ( (abs(yPenultimo) >= abs(float(resultSoglie[0][3])) and abs(yPenultimo) <= abs(float(resultSoglie[0][4]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][4])) and abs(yPenultimo) <= abs(float(resultSoglie[0][5]))) or + (abs(yPenultimo) >= abs(float(resultSoglie[0][5])) and abs(yPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, y, 3, "Y", int(resultSoglie[0][25]), int(resultSoglie[0][26])]) + conn.commit() + if(soglieH_mira): + #print("quaaaa1;") + if (resultSoglie[0][52] != "vuoto" and resultSoglie[0][53] != "vuoto" and resultSoglie[0][54] != "vuoto"): + #print("quaaaa2;") + #print(abs(z), abs(float(resultSoglie[0][52])), abs(float(resultSoglie[0][53])), abs(float(resultSoglie[0][54]))) + if(abs(z) >= abs(float(resultSoglie[0][52])) and abs(z) <= abs(float(resultSoglie[0][53]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + #print(abs(zPenultimo), ultimaDataDatoPenultimo) + if not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][52])) and abs(zPenultimo) <= abs(float(resultSoglie[0][53]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][53])) and abs(zPenultimo) <= abs(float(resultSoglie[0][54]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][54])) and abs(zPenultimo) <= abs(maxValue)) ): + #print("creo") + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 1, "Z", int(resultSoglie[0][73]), int(resultSoglie[0][74])]) + conn.commit() + elif(abs(z) >= abs(float(resultSoglie[0][53])) and abs(z) <= abs(float(resultSoglie[0][54]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(zPenultimo) >= abs(float(resultSoglie[0][52])) and abs(zPenultimo) <= abs(float(resultSoglie[0][53]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 2, "Z", int(resultSoglie[0][75]), int(resultSoglie[0][76])]) + conn.commit() + elif not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][52])) and abs(zPenultimo) <= abs(float(resultSoglie[0][53]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][53])) and abs(zPenultimo) <= abs(float(resultSoglie[0][54]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][54])) and abs(zPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 2, "Z", int(resultSoglie[0][75]), int(resultSoglie[0][76])]) + conn.commit() + elif(abs(z) >= abs(float(resultSoglie[0][54])) and abs(z) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(zPenultimo) >= abs(float(resultSoglie[0][52])) and abs(zPenultimo) <= abs(float(resultSoglie[0][53]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][77]), int(resultSoglie[0][78])]) + conn.commit() + elif(abs(zPenultimo) >= abs(float(resultSoglie[0][53])) and abs(zPenultimo) <= abs(float(resultSoglie[0][54]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][77]), int(resultSoglie[0][78])]) + conn.commit() + elif not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][52])) and abs(zPenultimo) <= abs(float(resultSoglie[0][53]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][53])) and abs(zPenultimo) <= abs(float(resultSoglie[0][54]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][54])) and abs(zPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][77]), int(resultSoglie[0][78])]) + conn.commit() + elif(soglieH): + if (resultSoglie[0][6] != "vuoto" and resultSoglie[0][7] != "vuoto" and resultSoglie[0][8] != "vuoto"): + if(abs(z) >= abs(float(resultSoglie[0][6])) and abs(z) <= abs(float(resultSoglie[0][7]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + #print(abs(zPenultimo), ultimaDataDatoPenultimo) + if not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][6])) and abs(zPenultimo) <= abs(float(resultSoglie[0][7]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][7])) and abs(zPenultimo) <= abs(float(resultSoglie[0][8]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][8])) and abs(zPenultimo) <= abs(maxValue)) ): + #print("creo") + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 1, "Z", int(resultSoglie[0][27]), int(resultSoglie[0][28])]) + conn.commit() + elif(abs(z) >= abs(float(resultSoglie[0][7])) and abs(z) <= abs(float(resultSoglie[0][8]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(zPenultimo) >= abs(float(resultSoglie[0][6])) and abs(zPenultimo) <= abs(float(resultSoglie[0][7]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 2, "Z", int(resultSoglie[0][29]), int(resultSoglie[0][30])]) + conn.commit() + elif not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][6])) and abs(zPenultimo) <= abs(float(resultSoglie[0][7]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][7])) and abs(zPenultimo) <= abs(float(resultSoglie[0][8]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][8])) and abs(zPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 2, "Z", int(resultSoglie[0][29]), int(resultSoglie[0][30])]) + conn.commit() + elif(abs(z) >= abs(float(resultSoglie[0][8])) and abs(z) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "Z", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(zPenultimo) >= abs(float(resultSoglie[0][6])) and abs(zPenultimo) <= abs(float(resultSoglie[0][7]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][31]), int(resultSoglie[0][32])]) + conn.commit() + elif(abs(zPenultimo) >= abs(float(resultSoglie[0][7])) and abs(zPenultimo) <= abs(float(resultSoglie[0][8]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][31]), int(resultSoglie[0][32])]) + conn.commit() + elif not ( (abs(zPenultimo) >= abs(float(resultSoglie[0][6])) and abs(zPenultimo) <= abs(float(resultSoglie[0][7]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][7])) and abs(zPenultimo) <= abs(float(resultSoglie[0][8]))) or + (abs(zPenultimo) >= abs(float(resultSoglie[0][8])) and abs(zPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, z, 3, "Z", int(resultSoglie[0][31]), int(resultSoglie[0][32])]) + conn.commit() + if(soglieR2D_mira): + if (resultSoglie[0][55] != "vuoto" and resultSoglie[0][56] != "vuoto" and resultSoglie[0][57] != "vuoto"): + if(abs(r2d) >= abs(float(resultSoglie[0][55])) and abs(r2d) <= abs(float(resultSoglie[0][56]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][55])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][56]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][56])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][57]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][57])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 1, "R2D", int(resultSoglie[0][79]), int(resultSoglie[0][80])]) + conn.commit() + elif(abs(r2d) >= abs(float(resultSoglie[0][56])) and abs(r2d) <= abs(float(resultSoglie[0][57]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r2dPenultimo) >= abs(float(resultSoglie[0][55])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][56]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 2, "R2D", int(resultSoglie[0][81]), int(resultSoglie[0][82])]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][55])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][56]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][56])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][57]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][57])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 2, "R2D", int(resultSoglie[0][81]), int(resultSoglie[0][82])]) + conn.commit() + elif(abs(r2d) >= abs(float(resultSoglie[0][57])) and abs(r2d) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r2dPenultimo) >= abs(float(resultSoglie[0][55])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][56]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][83]), int(resultSoglie[0][84])]) + conn.commit() + elif(abs(r2dPenultimo) >= abs(float(resultSoglie[0][56])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][57]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][83]), int(resultSoglie[0][84])]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][55])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][56]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][56])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][57]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][57])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][83]), int(resultSoglie[0][84])]) + conn.commit() + elif(soglieR2D): + if (resultSoglie[0][9] != "vuoto" and resultSoglie[0][10] != "vuoto" and resultSoglie[0][11] != "vuoto"): + if(abs(r2d) >= abs(float(resultSoglie[0][9])) and abs(r2d) <= abs(float(resultSoglie[0][10]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][9])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][10]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][10])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][11]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][11])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 1, "R2D", int(resultSoglie[0][33]), int(resultSoglie[0][34])]) + conn.commit() + elif(abs(r2d) >= abs(float(resultSoglie[0][10])) and abs(r2d) <= abs(float(resultSoglie[0][11]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r2dPenultimo) >= abs(float(resultSoglie[0][9])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][10]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 2, "R2D", int(resultSoglie[0][35]), int(resultSoglie[0][36])]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][9])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][10]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][10])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][11]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][11])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 2, "R2D", int(resultSoglie[0][35]), int(resultSoglie[0][36])]) + conn.commit() + elif(abs(r2d) >= abs(float(resultSoglie[0][11])) and abs(r2d) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "R2D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r2dPenultimo) >= abs(float(resultSoglie[0][9])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][10]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][37]), int(resultSoglie[0][38])]) + conn.commit() + elif(abs(r2dPenultimo) >= abs(float(resultSoglie[0][10])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][11]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][37]), int(resultSoglie[0][38])]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(resultSoglie[0][9])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][10]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][10])) and abs(r2dPenultimo) <= abs(float(resultSoglie[0][11]))) or + (abs(r2dPenultimo) >= abs(float(resultSoglie[0][11])) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r2d, 3, "R2D", int(resultSoglie[0][37]), int(resultSoglie[0][38])]) + conn.commit() + if(soglieR3D_mira): + if (resultSoglie[0][58] != "vuoto" and resultSoglie[0][59] != "vuoto" and resultSoglie[0][60] != "vuoto"): + if(abs(r3d) >= abs(float(resultSoglie[0][58])) and abs(r3d) <= abs(float(resultSoglie[0][59]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][58])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][59]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][59])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][60]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][60])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 1, "R3D", int(resultSoglie[0][85]), int(resultSoglie[0][86])]) + conn.commit() + elif(abs(r3d) >= abs(float(resultSoglie[0][59])) and abs(r3d) <= abs(float(resultSoglie[0][60]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r3dPenultimo) >= abs(float(resultSoglie[0][58])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][59]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 2, "R3D", int(resultSoglie[0][87]), int(resultSoglie[0][88])]) + conn.commit() + elif not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][58])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][59]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][59])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][60]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][60])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 2, "R3D", int(resultSoglie[0][87]), int(resultSoglie[0][88])]) + conn.commit() + elif(abs(r3d) >= abs(float(resultSoglie[0][60])) and abs(r3d) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r3dPenultimo) >= abs(float(resultSoglie[0][58])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][59]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][89]), int(resultSoglie[0][90])]) + conn.commit() + elif(abs(r3dPenultimo) >= abs(float(resultSoglie[0][59])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][60]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][89]), int(resultSoglie[0][90])]) + conn.commit() + elif not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][58])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][59]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][59])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][60]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][60])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][89]), int(resultSoglie[0][90])]) + conn.commit() + elif(soglieR3D): + if (resultSoglie[0][12] != "vuoto" and resultSoglie[0][13] != "vuoto" and resultSoglie[0][14] != "vuoto"): + if(abs(r3d) >= abs(float(resultSoglie[0][12])) and abs(r3d) <= abs(float(resultSoglie[0][13]))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 1, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][12])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][13]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][13])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][14]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][14])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 1, "R3D", int(resultSoglie[0][39]), int(resultSoglie[0][40])]) + conn.commit() + elif(abs(r3d) >= abs(float(resultSoglie[0][13])) and abs(r3d) <= abs(float(resultSoglie[0][14]))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 2, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r3dPenultimo) >= abs(float(resultSoglie[0][12])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][13]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 2, "R3D", int(resultSoglie[0][41]), int(resultSoglie[0][42])]) + conn.commit() + elif not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][12])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][13]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][13])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][14]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][14])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 2, "R3D", int(resultSoglie[0][41]), int(resultSoglie[0][42])]) + conn.commit() + elif(abs(r3d) >= abs(float(resultSoglie[0][14])) and abs(r3d) <= abs(maxValue)): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and description=%s and date_time >= %s order by date_time asc limit 1" + cursor.execute(query, ["upgeo-mira-id|"+str(mira_id), 3, "R3D", ultimaDataDato]) + result = cursor.fetchall() + if(len(result) <= 0): + if(abs(r3dPenultimo) >= abs(float(resultSoglie[0][12])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][13]))):#se valore precedente è in allarme livello 1 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][43]), int(resultSoglie[0][44])]) + conn.commit() + elif(abs(r3dPenultimo) >= abs(float(resultSoglie[0][13])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][14]))):#se valore precedente è in allarme livello 2 + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][43]), int(resultSoglie[0][44])]) + conn.commit() + elif not ( (abs(r3dPenultimo) >= abs(float(resultSoglie[0][12])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][13]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][13])) and abs(r3dPenultimo) <= abs(float(resultSoglie[0][14]))) or + (abs(r3dPenultimo) >= abs(float(resultSoglie[0][14])) and abs(r3dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, description, send_email, send_sms) value(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [9, "upgeo-mira-id|"+str(mira_id), ultimaDataDato, r3d, 3, "R3D", int(resultSoglie[0][43]), int(resultSoglie[0][44])]) + conn.commit() + for s in soglieMonitoraggiAggiuntivi: + progetto_id = s[0] + lavoro_id = s[1] + mira_id = s[2] + mira_name = s[3] + print("dentro soglieAggiuntive: ",mira_name) + multipleDateRange = s[4] + lavoro_name = s[5] + maxValue = 99999999 + query = "select IFNULL(l.areaAttenzioneInizioN,'vuoto') as areaAttenzioneInizioN, IFNULL(l.areaInterventoInizioN,'vuoto') as areaInterventoInizioN, IFNULL(l.areaInterventoImmediatoInizioN,'vuoto') as areaInterventoImmediatoInizioN, IFNULL(l.areaAttenzioneInizioE,'vuoto') as areaAttenzioneInizioE, IFNULL(l.areaInterventoInizioE,'vuoto') as areaInterventoInizioE, IFNULL(l.areaInterventoImmediatoInizioE,'vuoto') as areaInterventoImmediatoInizioE, IFNULL(l.areaAttenzioneInizioH,'vuoto') as areaAttenzioneInizioH, IFNULL(l.areaInterventoInizioH,'vuoto') as areaInterventoInizioH, IFNULL(l.areaInterventoImmediatoInizioH,'vuoto') as areaInterventoImmediatoInizioH, IFNULL(l.areaAttenzioneInizioR2D,'vuoto') as areaAttenzioneInizioR2D, IFNULL(l.areaInterventoInizioR2D,'vuoto') as areaInterventoInizioR2D, IFNULL(l.areaInterventoImmediatoInizioR2D,'vuoto') as areaInterventoImmediatoInizioR2D, IFNULL(l.areaAttenzioneInizioR3D,'vuoto') as areaAttenzioneInizioR3D, IFNULL(l.areaInterventoInizioR3D,'vuoto') as areaInterventoInizioR3D, IFNULL(l.areaInterventoImmediatoInizioR3D,'vuoto') as areaInterventoImmediatoInizioR3D, l.email_livello_unoN, l.sms_livello_unoN, l.email_livello_dueN, l.sms_livello_dueN, l.email_livello_treN, l.sms_livello_treN, l.email_livello_unoE, l.sms_livello_unoE, l.email_livello_dueE, l.sms_livello_dueE, l.email_livello_treE, l.sms_livello_treE, l.email_livello_unoH, l.sms_livello_unoH, l.email_livello_dueH, l.sms_livello_dueH, l.email_livello_treH, l.sms_livello_treH, l.email_livello_unoR2D, l.sms_livello_unoR2D, l.email_livello_dueR2D, l.sms_livello_dueR2D, l.email_livello_treR2D, l.sms_livello_treR2D, l.email_livello_unoR3D, l.sms_livello_unoR3D, l.email_livello_dueR3D, l.sms_livello_dueR3D, l.email_livello_treR3D, l.sms_livello_treR3D, IFNULL(l.lista_monitoring_type, '') as lista_monitoring_type, IFNULL(m.areaAttenzioneInizioN,'vuoto') as areaAttenzioneInizioN_mira, IFNULL(m.areaInterventoInizioN,'vuoto') as areaInterventoInizioN_mira, IFNULL(m.areaInterventoImmediatoInizioN,'vuoto') as areaInterventoImmediatoInizioN_mira, IFNULL(m.areaAttenzioneInizioE,'vuoto') as areaAttenzioneInizioE_mira, IFNULL(m.areaInterventoInizioE,'vuoto') as areaInterventoInizioE_mira, IFNULL(m.areaInterventoImmediatoInizioE,'vuoto') as areaInterventoImmediatoInizioE_mira, IFNULL(m.areaAttenzioneInizioH,'vuoto') as areaAttenzioneInizioH_mira, IFNULL(m.areaInterventoInizioH,'vuoto') as areaInterventoInizioH_mira, IFNULL(m.areaInterventoImmediatoInizioH,'vuoto') as areaInterventoImmediatoInizioH_mira, IFNULL(m.areaAttenzioneInizioR2D,'vuoto') as areaAttenzioneInizioR2D_mira, IFNULL(m.areaInterventoInizioR2D,'vuoto') as areaInterventoInizioR2D_mira, IFNULL(m.areaInterventoImmediatoInizioR2D,'vuoto') as areaInterventoImmediatoInizioR2D_mira, IFNULL(m.areaAttenzioneInizioR3D,'vuoto') as areaAttenzioneInizioR3D_mira, IFNULL(m.areaInterventoInizioR3D,'vuoto') as areaInterventoInizioR3D_mira, IFNULL(m.areaInterventoImmediatoInizioR3D,'vuoto') as areaInterventoImmediatoInizioR3D_mira, m.email_livello_unoN as email_livello_unoN_mira, m.sms_livello_unoN as sms_livello_unoN_mira, m.email_livello_dueN as email_livello_dueN_mira, m.sms_livello_dueN as sms_livello_dueN_mira, m.email_livello_treN as email_livello_treN_mira, m.sms_livello_treN as sms_livello_treN_mira, m.email_livello_unoE as email_livello_unoE_mira, m.sms_livello_unoE as sms_livello_unoE_mira, m.email_livello_dueE as email_livello_dueE_mira, m.sms_livello_dueE as sms_livello_dueE_mira, m.email_livello_treE as email_livello_treE_mira, m.sms_livello_treE as sms_livello_treE_mira, m.email_livello_unoH as email_livello_unoH_mira, m.sms_livello_unoH as sms_livello_unoH_mira, m.email_livello_dueH as email_livello_dueH_mira, m.sms_livello_dueH as sms_livello_dueH_mira, m.email_livello_treH as email_livello_treH_mira, m.sms_livello_treH as sms_livello_treH_mira, m.email_livello_unoR2D as email_livello_unoR2D_mira, m.sms_livello_unoR2D as sms_livello_unoR2D_mira, m.email_livello_dueR2D as email_livello_dueR2D_mira, m.sms_livello_dueR2D as sms_livello_dueR2D_mira, m.email_livello_treR2D as email_livello_treR2D_mira, m.sms_livello_treR2D as sms_livello_treR2D_mira, m.email_livello_unoR3D as email_livello_unoR3D_mira, m.sms_livello_unoR3D as sms_livello_unoR3D_mira, m.email_livello_dueR3D as email_livello_dueR3D_mira, m.sms_livello_dueR3D as sms_livello_dueR3D_mira, m.email_livello_treR3D as email_livello_treR3D_mira, m.sms_livello_treR3D as sms_livello_treR3D_mira,IFNULL(l.data_inizio_pali,'') as data_inizio_pali, IFNULL(l.data_inizio_muri,'') as data_inizio_muri, IFNULL(l.data_inizio_tralicci,'') as data_inizio_tralicci, IFNULL(l.data_inizio_binari,'') as data_inizio_binari, IFNULL(l.data_inizio_segmenticonvergenza,'') as data_inizio_segmenticonvergenza, IFNULL(l.data_inizio_cedimenti,'') as data_inizio_cedimenti, IFNULL(l.data_inizio_convergenzacile,'') as data_inizio_convergenzacile, IFNULL(l.data_inizio_fessure,'') as data_inizio_fessure from upgeo_lavori as l left join upgeo_mire as m on m.lavoro_id=l.id where l.id=%s and m.id=%s" + #query = "SELECT IFNULL(areaAttenzioneInizioN,'vuoto') AS areaAttenzioneInizioN, IFNULL(areaInterventoInizioN,'vuoto') AS areaInterventoInizioN, IFNULL(areaInterventoImmediatoInizioN,'vuoto') AS areaInterventoImmediatoInizioN, IFNULL(areaAttenzioneInizioE,'vuoto') AS areaAttenzioneInizioE, IFNULL(areaInterventoInizioE,'vuoto') AS areaInterventoInizioE, IFNULL(areaInterventoImmediatoInizioE,'vuoto') AS areaInterventoImmediatoInizioE, IFNULL(areaAttenzioneInizioH,'vuoto') AS areaAttenzioneInizioH, IFNULL(areaInterventoInizioH,'vuoto') AS areaInterventoInizioH, IFNULL(areaInterventoImmediatoInizioH,'vuoto') AS areaInterventoImmediatoInizioH, IFNULL(areaAttenzioneInizioR2D,'vuoto') AS areaAttenzioneInizioR2D, IFNULL(areaInterventoInizioR2D,'vuoto') AS areaInterventoInizioR2D, IFNULL(areaInterventoImmediatoInizioR2D,'vuoto') AS areaInterventoImmediatoInizioR2D, IFNULL(areaAttenzioneInizioR3D,'vuoto') AS areaAttenzioneInizioR3D, IFNULL(areaInterventoInizioR3D,'vuoto') AS areaInterventoInizioR3D, IFNULL(areaInterventoImmediatoInizioR3D,'vuoto') AS areaInterventoImmediatoInizioR3D, email_livello_unoN, sms_livello_unoN, email_livello_dueN, sms_livello_dueN, email_livello_treN, sms_livello_treN, email_livello_unoE, sms_livello_unoE, email_livello_dueE, sms_livello_dueE, email_livello_treE, sms_livello_treE, email_livello_unoH, sms_livello_unoH, email_livello_dueH, sms_livello_dueH, email_livello_treH, sms_livello_treH, email_livello_unoR2D, sms_livello_unoR2D, email_livello_dueR2D, sms_livello_dueR2D, email_livello_treR2D, sms_livello_treR2D, email_livello_unoR3D, sms_livello_unoR3D, email_livello_dueR3D, sms_livello_dueR3D, email_livello_treR3D, sms_livello_treR3D, IFNULL(lista_monitoring_type, '') AS lista_monitoring_type FROM upgeo_lavori WHERE id=%s" + #query = "select IFNULL(areaAttenzioneInizio,'vuoto') as areaAttenzioneInizio, IFNULL(areaInterventoInizio,'vuoto') as areaInterventoInizio, IFNULL(areaInterventoImmediatoInizio,'vuoto') as areaInterventoImmediatoInizio, IFNULL(soglieToSeries,'vuoto') as soglieToSeries, email_livello_uno, sms_livello_uno, email_livello_due, sms_livello_due, email_livello_tre, sms_livello_tre from upgeo_lavori where id=%s" + cursor.execute(query, [lavoro_id, mira_id]) + resultSoglie = cursor.fetchall() + if(resultSoglie[0][45] != ''):#lista_monitoring_type + #print("resultSoglie[0][45]: ", resultSoglie[0][45]) + lista_monitoring_type = json.loads(resultSoglie[0][45]) + for monitoring_type in lista_monitoring_type: + if monitoring_type["type"] == 1: + print(1, lavoro_id, mira_id) + query = "select lavoro_id, num, mira_id_a, mira_id_b from upgeo_mire_coppie where lavoro_id=%s and (mira_id_a=%s or mira_id_b=%s) and tipoPaloMuro=0 order by num asc" + cursor.execute(query, [lavoro_id, mira_id, mira_id]) + resultCoppie = cursor.fetchall() + for coppia in resultCoppie: + query = "select id, name, multipleDateRange from upgeo_mire where abilitato=1 and lavoro_id=%s and (id=%s or id=%s)" + cursor.execute(query, [lavoro_id, coppia[2], coppia[3]]) + resultCoppiaMire = cursor.fetchall() + for coppiaMira in resultCoppiaMire: + resultDataCoppie = [] + if lavoro_name not in arrayCoppie: + arrayCoppie[lavoro_name] = {} + if coppia[1] not in arrayCoppie[lavoro_name]: + arrayCoppie[lavoro_name][coppia[1]] = {} + if coppiaMira[1] not in arrayCoppie[lavoro_name][coppia[1]]: + arrayCoppie[lavoro_name][coppia[1]][coppiaMira[1]] = [] + if coppiaMira[2] is not None: + for drange in coppiaMira[2].split(";"): + if(drange != ''): + fdate = drange.split(",")[0] + ldate = drange.split(",")[1] + params = [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate] + query = """select d.id as fake_id, d.id as id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, + uo.name as operatore_name, us.description as strumento_desc, un.description as nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, s.multipleDateRange as fasi_lavorazione, + l.soglieCoppieUnitaMisura, l.areaAttenzioneInizioCoppieInc, l.areaInterventoInizioCoppieInc, l.areaInterventoImmediatoInizioCoppieInc, + l.areaAttenzioneInizioCoppieAssest, l.areaInterventoInizioCoppieAssest, l.areaInterventoImmediatoInizioCoppieAssest, + l.areaAttenzioneInizioCoppieSpostLat, l.areaInterventoInizioCoppieSpostLat, l.areaInterventoImmediatoInizioCoppieSpostLat, + l.reportVarInclin, l.reportAssest, l.reportSpostLat, l.parametroLetture, + l.email_livello_unoCoppieInc, + l.email_livello_dueCoppieInc, + l.email_livello_treCoppieInc, + l.sms_livello_unoCoppieInc, + l.sms_livello_dueCoppieInc, + l.sms_livello_treCoppieInc, + l.email_livello_unoCoppieAssest, + l.email_livello_dueCoppieAssest, + l.email_livello_treCoppieAssest, + l.sms_livello_unoCoppieAssest, + l.sms_livello_dueCoppieAssest, + l.sms_livello_treCoppieAssest, + l.email_livello_unoCoppieSpostLat, + l.email_livello_dueCoppieSpostLat, + l.email_livello_treCoppieSpostLat, + l.sms_livello_unoCoppieSpostLat, + l.sms_livello_dueCoppieSpostLat, + l.sms_livello_treCoppieSpostLat + from sites as s + join upgeo_lavori as l on s.id=l.site_id + join upgeo_mire as m on m.lavoro_id=l.id + join ELABDATAUPGEO as d on d.mira_id=m.id + left join upgeo_operatori AS uo ON uo.id = d.operatore_id + left join upgeo_strumenti AS us ON us.id = d.strumento_id + left join upgeo_note AS un ON un.id = d.nota_id + where s.upgeo=1 and s.id=%s and l.id=%s and m.id=%s and d.EventTimestamp between %s and %s""" + if(resultSoglie[0][91] != ''): + query += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][91]) + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, params) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppie[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + params = [progetto_id, lavoro_id, coppiaMira[0]] + query = """select d.id as fake_id, d.id as id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, + uo.name as operatore_name, us.description as strumento_desc, un.description as nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, s.multipleDateRange as fasi_lavorazione, + l.soglieCoppieUnitaMisura, l.areaAttenzioneInizioCoppieInc, l.areaInterventoInizioCoppieInc, l.areaInterventoImmediatoInizioCoppieInc, + l.areaAttenzioneInizioCoppieAssest, l.areaInterventoInizioCoppieAssest, l.areaInterventoImmediatoInizioCoppieAssest, + l.areaAttenzioneInizioCoppieSpostLat, l.areaInterventoInizioCoppieSpostLat, l.areaInterventoImmediatoInizioCoppieSpostLat, + l.reportVarInclin, l.reportAssest, l.reportSpostLat, l.parametroLetture, + l.email_livello_unoCoppieInc, + l.email_livello_dueCoppieInc, + l.email_livello_treCoppieInc, + l.sms_livello_unoCoppieInc, + l.sms_livello_dueCoppieInc, + l.sms_livello_treCoppieInc, + l.email_livello_unoCoppieAssest, + l.email_livello_dueCoppieAssest, + l.email_livello_treCoppieAssest, + l.sms_livello_unoCoppieAssest, + l.sms_livello_dueCoppieAssest, + l.sms_livello_treCoppieAssest, + l.email_livello_unoCoppieSpostLat, + l.email_livello_dueCoppieSpostLat, + l.email_livello_treCoppieSpostLat, + l.sms_livello_unoCoppieSpostLat, + l.sms_livello_dueCoppieSpostLat, + l.sms_livello_treCoppieSpostLat + from sites as s + join upgeo_lavori as l on s.id=l.site_id + join upgeo_mire as m on m.lavoro_id=l.id + join ELABDATAUPGEO as d on d.mira_id=m.id + left join upgeo_operatori AS uo ON uo.id = d.operatore_id + left join upgeo_strumenti AS us ON us.id = d.strumento_id + left join upgeo_note AS un ON un.id = d.nota_id + where s.upgeo=1 and s.id=%s and l.id=%s and m.id=%s""" + if(resultSoglie[0][91] != ''): + query += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][91]) + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, params) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppie[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + elif monitoring_type["type"] == 2: + print(2, lavoro_id, mira_id) + query = "select lavoro_id, num, mira_id_a, mira_id_b from upgeo_mire_coppie where lavoro_id=%s and (mira_id_a=%s or mira_id_b=%s) and tipoPaloMuro=0 order by num asc" + cursor.execute(query, [lavoro_id, mira_id, mira_id]) + resultCoppie = cursor.fetchall() + for coppia in resultCoppie: + query = "select id, name, multipleDateRange from upgeo_mire where abilitato=1 and lavoro_id=%s and (id=%s or id=%s)" + cursor.execute(query, [lavoro_id, coppia[2], coppia[3]]) + resultCoppiaMire = cursor.fetchall() + for coppiaMira in resultCoppiaMire: + resultDataCoppie = [] + if lavoro_name not in arrayCoppieMuro: + arrayCoppieMuro[lavoro_name] = {} + if coppia[1] not in arrayCoppieMuro[lavoro_name]: + arrayCoppieMuro[lavoro_name][coppia[1]] = {} + if coppiaMira[1] not in arrayCoppieMuro[lavoro_name][coppia[1]]: + arrayCoppieMuro[lavoro_name][coppia[1]][coppiaMira[1]] = [] + if coppiaMira[2] is not None: + for drange in coppiaMira[2].split(";"): + if(drange != ''): + fdate = drange.split(",")[0] + ldate = drange.split(",")[1] + params = [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate] + query = """select d.id as fake_id, d.id as id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, + uo.name as operatore_name, us.description as strumento_desc, un.description as nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, s.multipleDateRange as fasi_lavorazione, + l.soglieCoppieUnitaMisuraMuro, l.areaAttenzioneInizioCoppieIncMuro, l.areaInterventoInizioCoppieIncMuro, l.areaInterventoImmediatoInizioCoppieIncMuro, + l.areaAttenzioneInizioCoppieAssestMuro, l.areaInterventoInizioCoppieAssestMuro, l.areaInterventoImmediatoInizioCoppieAssestMuro, + l.areaAttenzioneInizioCoppieSpostLatMuro, l.areaInterventoInizioCoppieSpostLatMuro, l.areaInterventoImmediatoInizioCoppieSpostLatMuro, + l.reportVarInclinMuro, l.reportAssestMuro, l.reportSpostLatMuro, l.parametroLettureMuro + from sites as s + join upgeo_lavori as l on s.id=l.site_id + join upgeo_mire as m on m.lavoro_id=l.id + join ELABDATAUPGEO as d on d.mira_id=m.id + left join upgeo_operatori AS uo ON uo.id = d.operatore_id + left join upgeo_strumenti AS us ON us.id = d.strumento_id + left join upgeo_note AS un ON un.id = d.nota_id + where s.upgeo=1 and s.id=%s and l.id=%s and m.id=%s and d.EventTimestamp between %s and %s""" + if(resultSoglie[0][92] != ''): + query += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][92]) + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, params) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppieMuro[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + params = [progetto_id, lavoro_id, coppiaMira[0]] + query = """select d.id as fake_id, d.id as id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, + uo.name as operatore_name, us.description as strumento_desc, un.description as nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, s.multipleDateRange as fasi_lavorazione, + l.soglieCoppieUnitaMisuraMuro, l.areaAttenzioneInizioCoppieIncMuro, l.areaInterventoInizioCoppieIncMuro, l.areaInterventoImmediatoInizioCoppieIncMuro, + l.areaAttenzioneInizioCoppieAssestMuro, l.areaInterventoInizioCoppieAssestMuro, l.areaInterventoImmediatoInizioCoppieAssestMuro, + l.areaAttenzioneInizioCoppieSpostLatMuro, l.areaInterventoInizioCoppieSpostLatMuro, l.areaInterventoImmediatoInizioCoppieSpostLatMuro, + l.reportVarInclinMuro, l.reportAssestMuro, l.reportSpostLatMuro, l.parametroLettureMuro + from sites as s + join upgeo_lavori as l on s.id=l.site_id + join upgeo_mire as m on m.lavoro_id=l.id + join ELABDATAUPGEO as d on d.mira_id=m.id + left join upgeo_operatori AS uo ON uo.id = d.operatore_id + left join upgeo_strumenti AS us ON us.id = d.strumento_id + left join upgeo_note AS un ON un.id = d.nota_id + where s.upgeo=1 and s.id=%s and l.id=%s and m.id=%s""" + if(resultSoglie[0][92] != ''): + query += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][92]) + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, params) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppieMuro[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + elif monitoring_type["type"] == 3: + print(3, lavoro_id, mira_id) + sql = """SELECT id, lavoro_id, num, mira_id_a, mira_id_b + FROM upgeo_mire_coppie_traliccio + WHERE lavoro_id = %s AND (mira_id_a = %s OR mira_id_b = %s)""" + cursor.execute(sql, (lavoro_id, mira_id, mira_id)) + result_coppie = cursor.fetchall() + for coppia in result_coppie: + sql = """SELECT lavoro_id, num, lista + FROM upgeo_mire_tralicci + WHERE lavoro_id = %s AND JSON_CONTAINS(lista, CAST(%s AS JSON), '$') + ORDER BY num ASC""" + cursor.execute(sql, (lavoro_id, coppia[0])) + result_tralicci = cursor.fetchall() + for traliccio in result_tralicci: + sql = """SELECT id, name, multipleDateRange + FROM upgeo_mire + WHERE abilitato = 1 AND lavoro_id = %s AND (id = %s OR id = %s)""" + cursor.execute(sql, (coppia[1], coppia[3], coppia[4])) + result_coppia_mire = cursor.fetchall() + for coppia_mira in result_coppia_mire: + result_data_coppie = [] + if coppia_mira[2]: + for drange in coppia_mira[2].split(";"): + if drange: + fdate, ldate = drange.split(",") + params = [progetto_id, lavoro_id, coppia_mira[0], fdate, ldate] + sql = """SELECT d.id AS fake_id, d.id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, + m.id AS mira_id, m.name AS mira_name, d.EventTimestamp, d.north, d.east, d.elevation, + d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, uo.name AS operatore_name, + us.description AS strumento_desc, un.description AS nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, + s.multipleDateRange AS fasi_lavorazione, l.soglieCoppieUnitaMisuraTraliccio, + l.areaAttenzioneInizioCoppieIncTraliccio, l.areaInterventoInizioCoppieIncTraliccio, + l.areaInterventoImmediatoInizioCoppieIncTraliccio, + l.areaAttenzioneInizioCoppieAssestTraliccio, + l.areaInterventoInizioCoppieAssestTraliccio, + l.areaInterventoImmediatoInizioCoppieAssestTraliccio, + l.areaAttenzioneInizioCoppieSpostLatTraliccio, + l.areaInterventoInizioCoppieSpostLatTraliccio, + l.areaInterventoImmediatoInizioCoppieSpostLatTraliccio, + l.reportVarInclinTraliccio, l.reportAssestTraliccio, + l.reportSpostLatTraliccio, l.parametroLettureTraliccio + FROM sites AS s + JOIN upgeo_lavori AS l ON s.id = l.site_id + JOIN upgeo_mire AS m ON m.lavoro_id = l.id + JOIN ELABDATAUPGEO AS d ON d.mira_id = m.id + LEFT JOIN upgeo_operatori AS uo ON uo.id = d.operatore_id + LEFT JOIN upgeo_strumenti AS us ON us.id = d.strumento_id + LEFT JOIN upgeo_note AS un ON un.id = d.nota_id + WHERE s.upgeo = 1 AND s.id = %s AND l.id = %s AND m.id = %s AND d.EventTimestamp BETWEEN %s AND %s""" + if(resultSoglie[0][93] != ''): + sql += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][93]) + sql += " ORDER BY lavoro_name, EventTimestamp ASC" + cursor.execute(sql, params) + result_data_coppie = cursor.fetchall() + if result_data_coppie: + arrayCoppieTralicci.setdefault(lavoro_name, {}).setdefault( + traliccio[1], {}).setdefault( + coppia[2], {}).setdefault( + coppia_mira[1], []).extend(result_data_coppie) + else: + params = [progetto_id, lavoro_id, coppia_mira[0]] + sql = """SELECT d.id AS fake_id, d.id, l.name AS lavoro_name, l.id AS lavoro_id, s.id AS site_id, + m.id AS mira_id, m.name AS mira_name, d.EventTimestamp, d.north, d.east, d.elevation, + d.lat, d.lon, d.operatore_id, d.strumento_id, d.nota_id, uo.name AS operatore_name, + us.description AS strumento_desc, un.description AS nota_desc, d.sist_coordinate, + l.areaAttenzioneInizio, l.areaInterventoInizio, l.areaInterventoImmediatoInizio, + s.multipleDateRange AS fasi_lavorazione, l.soglieCoppieUnitaMisuraTraliccio, + l.areaAttenzioneInizioCoppieIncTraliccio, l.areaInterventoInizioCoppieIncTraliccio, + l.areaInterventoImmediatoInizioCoppieIncTraliccio, + l.areaAttenzioneInizioCoppieAssestTraliccio, + l.areaInterventoInizioCoppieAssestTraliccio, + l.areaInterventoImmediatoInizioCoppieAssestTraliccio, + l.areaAttenzioneInizioCoppieSpostLatTraliccio, + l.areaInterventoInizioCoppieSpostLatTraliccio, + l.areaInterventoImmediatoInizioCoppieSpostLatTraliccio, + l.reportVarInclinTraliccio, l.reportAssestTraliccio, + l.reportSpostLatTraliccio, l.parametroLettureTraliccio + FROM sites AS s + JOIN upgeo_lavori AS l ON s.id = l.site_id + JOIN upgeo_mire AS m ON m.lavoro_id = l.id + JOIN ELABDATAUPGEO AS d ON d.mira_id = m.id + LEFT JOIN upgeo_operatori AS uo ON uo.id = d.operatore_id + LEFT JOIN upgeo_strumenti AS us ON us.id = d.strumento_id + LEFT JOIN upgeo_note AS un ON un.id = d.nota_id + WHERE s.upgeo = 1 AND s.id = %s AND l.id = %s AND m.id = %s""" + if(resultSoglie[0][93] != ''): + sql += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][93]) + sql += " ORDER BY lavoro_name, EventTimestamp ASC" + cursor.execute(sql, params) + result_data_coppie = cursor.fetchall() + if result_data_coppie: + arrayCoppieTralicci.setdefault(lavoro_name, {}).setdefault( + traliccio[1], {}).setdefault( + coppia[1], {}).setdefault( + coppia_mira[1], []).extend(result_data_coppie) + elif monitoring_type["type"] == 4: + print(4, lavoro_id, mira_id) + print() + sql = """ + SELECT + mire.id AS mira_id, + mire.name AS mira_name, + mire.multipleDateRange, + mire.progressiva_id, + progressivebinari.name AS progressiva_name, + progressivebinari.offsetInizialeSghembo + FROM upgeo_mire AS mire + JOIN upgeo_mire_progressivebinari AS progressivebinari + ON mire.progressiva_id = progressivebinari.id + WHERE mire.abilitato = 1 AND mire.lavoro_id = %s AND mire.id = %s + ORDER BY progressivebinari.id + """ + cursor.execute(sql, (lavoro_id, mira_id)) + #print(lavoro_id, mira_id) + result_progressiva_mire = cursor.fetchall() + for progressiva_mira in result_progressiva_mire: + #print(progressiva_mira[1], lavoro_id, mira_id) + result_data_progressive = [] + multiple_date_range = progressiva_mira[2] + if multiple_date_range: + #print("SONO QUIIIIIII") + ranges = multiple_date_range.split(";") + for range_item in ranges: + if range_item: + fdate, ldate = range_item.split(",") + params = [progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0], fdate, ldate] + sql = """ + SELECT + d.id AS fake_id, d.id AS id, l.name AS lavoro_name, l.id AS lavoro_id, + s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, + d.operatore_id, d.strumento_id, d.nota_id, uo.name AS operatore_name, + us.description AS strumento_desc, un.description AS nota_desc, + d.sist_coordinate, l.areaAttenzioneInizio, l.areaInterventoInizio, + l.areaInterventoImmediatoInizio, s.multipleDateRange AS fasi_lavorazione, + m.progressiva_pos, l.passoLong, l.passoTrasv, l.passoSghembo, + l.areaAttenzioneInizioBinariTrasv, l.areaInterventoInizioBinariTrasv, + l.areaInterventoImmediatoInizioBinariTrasv, l.areaAttenzioneInizioBinariLongVert, + l.areaInterventoInizioBinariLongVert, l.areaInterventoImmediatoInizioBinariLongVert, + l.areaAttenzioneInizioBinariLongOriz, l.areaInterventoInizioBinariLongOriz, + l.areaInterventoImmediatoInizioBinariLongOriz, l.areaAttenzioneInizioBinariSghembo, + l.areaInterventoInizioBinariSghembo, l.areaInterventoImmediatoInizioBinariSghembo, + l.reportBinariSpostTrasv, l.reportBinariSpostLongVert, l.reportBinariSpostLongOriz, + l.reportBinariSghembo, l.reportVarInclin, l.reportAssest, l.reportSpostLat, + %s AS offsetInizialeSghembo, l.parametroLettureBinari, + l.email_livello_unoBinariTrasv, + l.email_livello_dueBinariTrasv, + l.email_livello_treBinariTrasv, + l.sms_livello_unoBinariTrasv, + l.sms_livello_dueBinariTrasv, + l.sms_livello_treBinariTrasv, + l.email_livello_unoBinariLongVert, + l.email_livello_dueBinariLongVert, + l.email_livello_treBinariLongVert, + l.sms_livello_unoBinariLongVert, + l.sms_livello_dueBinariLongVert, + l.sms_livello_treBinariLongVert, + l.email_livello_unoBinariLongOriz, + l.email_livello_dueBinariLongOriz, + l.email_livello_treBinariLongOriz, + l.sms_livello_unoBinariLongOriz, + l.sms_livello_dueBinariLongOriz, + l.sms_livello_treBinariLongOriz, + l.email_livello_unoBinariSghembo, + l.email_livello_dueBinariSghembo, + l.email_livello_treBinariSghembo, + l.sms_livello_unoBinariSghembo, + l.sms_livello_dueBinariSghembo, + l.sms_livello_treBinariSghembo + FROM sites AS s + JOIN upgeo_lavori AS l ON s.id = l.site_id + JOIN upgeo_mire AS m ON m.lavoro_id = l.id + JOIN ELABDATAUPGEO AS d ON d.mira_id = m.id + LEFT JOIN upgeo_operatori AS uo ON uo.id = d.operatore_id + LEFT JOIN upgeo_strumenti AS us ON us.id = d.strumento_id + LEFT JOIN upgeo_note AS un ON un.id = d.nota_id + WHERE s.upgeo = 1 AND s.id = %s AND l.id = %s AND m.id = %s + AND d.EventTimestamp BETWEEN %s AND %s""" + if(resultSoglie[0][94] != ''): + sql += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][94]) + sql += " ORDER BY lavoro_name, EventTimestamp ASC" + cursor.execute(sql, params) + #print(progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0], fdate, ldate) + result_data_progressive = cursor.fetchall() + if result_data_progressive: + key = f'{progressiva_mira[3]}$${progressiva_mira[4]}' + arrayBinari.setdefault(lavoro_name, {}).setdefault(key, {}).setdefault(progressiva_mira[1], []).append(result_data_progressive) + else: + params = [progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0]] + sql = """ + SELECT + d.id AS fake_id, d.id AS id, l.name AS lavoro_name, l.id AS lavoro_id, + s.id AS site_id, m.id AS mira_id, m.name AS mira_name, + d.EventTimestamp, d.north, d.east, d.elevation, d.lat, d.lon, + d.operatore_id, d.strumento_id, d.nota_id, uo.name AS operatore_name, + us.description AS strumento_desc, un.description AS nota_desc, + d.sist_coordinate, l.areaAttenzioneInizio, l.areaInterventoInizio, + l.areaInterventoImmediatoInizio, s.multipleDateRange AS fasi_lavorazione, + m.progressiva_pos, l.passoLong, l.passoTrasv, l.passoSghembo, + l.areaAttenzioneInizioBinariTrasv, l.areaInterventoInizioBinariTrasv, + l.areaInterventoImmediatoInizioBinariTrasv, l.areaAttenzioneInizioBinariLongVert, + l.areaInterventoInizioBinariLongVert, l.areaInterventoImmediatoInizioBinariLongVert, + l.areaAttenzioneInizioBinariLongOriz, l.areaInterventoInizioBinariLongOriz, + l.areaInterventoImmediatoInizioBinariLongOriz, l.areaAttenzioneInizioBinariSghembo, + l.areaInterventoInizioBinariSghembo, l.areaInterventoImmediatoInizioBinariSghembo, + l.reportBinariSpostTrasv, l.reportBinariSpostLongVert, l.reportBinariSpostLongOriz, + l.reportBinariSghembo, l.reportVarInclin, l.reportAssest, l.reportSpostLat, + %s AS offsetInizialeSghembo, l.parametroLettureBinari, + l.email_livello_unoBinariTrasv, + l.email_livello_dueBinariTrasv, + l.email_livello_treBinariTrasv, + l.sms_livello_unoBinariTrasv, + l.sms_livello_dueBinariTrasv, + l.sms_livello_treBinariTrasv, + l.email_livello_unoBinariLongVert, + l.email_livello_dueBinariLongVert, + l.email_livello_treBinariLongVert, + l.sms_livello_unoBinariLongVert, + l.sms_livello_dueBinariLongVert, + l.sms_livello_treBinariLongVert, + l.email_livello_unoBinariLongOriz, + l.email_livello_dueBinariLongOriz, + l.email_livello_treBinariLongOriz, + l.sms_livello_unoBinariLongOriz, + l.sms_livello_dueBinariLongOriz, + l.sms_livello_treBinariLongOriz, + l.email_livello_unoBinariSghembo, + l.email_livello_dueBinariSghembo, + l.email_livello_treBinariSghembo, + l.sms_livello_unoBinariSghembo, + l.sms_livello_dueBinariSghembo, + l.sms_livello_treBinariSghembo + FROM sites AS s + JOIN upgeo_lavori AS l ON s.id = l.site_id + JOIN upgeo_mire AS m ON m.lavoro_id = l.id + JOIN ELABDATAUPGEO AS d ON d.mira_id = m.id + LEFT JOIN upgeo_operatori AS uo ON uo.id = d.operatore_id + LEFT JOIN upgeo_strumenti AS us ON us.id = d.strumento_id + LEFT JOIN upgeo_note AS un ON un.id = d.nota_id + WHERE s.upgeo = 1 AND s.id = %s AND l.id = %s AND m.id = %s""" + if(resultSoglie[0][94] != ''): + sql += " and d.EventTimestamp >= %s" + params.append(resultSoglie[0][94]) + sql += " ORDER BY lavoro_name, EventTimestamp ASC" + cursor.execute(sql, params) + #print(progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0]) + result_data_progressive = cursor.fetchall() + if result_data_progressive: + key = f'{progressiva_mira[3]}$${progressiva_mira[4]}' + arrayBinari.setdefault(lavoro_name, {}).setdefault(key, {}).setdefault(progressiva_mira[1], []).append(result_data_progressive) + #print(arrayBinari) + #ELAB BINARI + print("----------------- BINARI ----------------") + for key, value in arrayBinari.items(): + #print(key, value) + # Sort the dictionary by the number before "$$" + value = dict(sorted(value.items(), key=lambda item: int(item[0].split('$$')[0]))) + # Create a new dictionary with keys after "$$" + new_test_importazione = {} + for key_temp, vv in value.items(): + # Removes "id$$" from the name + new_key = key_temp.split('$$')[1] + new_test_importazione[new_key] = vv + # Update value with the new dictionary + value = new_test_importazione + spost_trasv_array = {} + sghembo_array = {} + spost_long_vert_array = {} + spost_long_oriz_array = {} + array_dati = value + fasi_lavorazione = None + area_attenzione_inizio_binari_trasv = None + area_intervento_inizio_binari_trasv = None + area_intervento_immediato_inizio_binari_trasv = None + area_attenzione_inizio_binari_sghembo = None + area_intervento_inizio_binari_sghembo = None + area_intervento_immediato_inizio_binari_sghembo = None + area_attenzione_inizio_binari_long_vert = None + area_intervento_inizio_binari_long_vert = None + area_intervento_immediato_inizio_binari_long_vert = None + area_attenzione_inizio_binari_long_oriz = None + area_intervento_inizio_binari_long_oriz = None + area_intervento_immediato_inizio_binari_long_oriz = None + passo_sghembo = 0 + passo_long = 0 + lavoro_id = 0 + report_binari_spost_trasv = 0 + report_binari_spost_long_vert = 0 + report_binari_spost_long_oriz = 0 + report_binari_sghembo = 0 + parametro_letture_binari = 4200 + email_livello_unoBinariTrasv = 0 + email_livello_dueBinariTrasv = 0 + email_livello_treBinariTrasv = 0 + sms_livello_unoBinariTrasv = 0 + sms_livello_dueBinariTrasv = 0 + sms_livello_treBinariTrasv = 0 + email_livello_unoBinariLongVert = 0 + email_livello_dueBinariLongVert = 0 + email_livello_treBinariLongVert = 0 + sms_livello_unoBinariLongVert = 0 + sms_livello_dueBinariLongVert = 0 + sms_livello_treBinariLongVert = 0 + email_livello_unoBinariLongOriz = 0 + email_livello_dueBinariLongOriz = 0 + email_livello_treBinariLongOriz = 0 + sms_livello_unoBinariLongOriz = 0 + sms_livello_dueBinariLongOriz = 0 + sms_livello_treBinariLongOriz = 0 + email_livello_unoBinariSghembo = 0 + email_livello_dueBinariSghembo = 0 + email_livello_treBinariSghembo = 0 + sms_livello_unoBinariSghembo = 0 + sms_livello_dueBinariSghembo = 0 + sms_livello_treBinariSghembo = 0 + for key_progressiva, value_progressiva in array_dati.items(): + x = 0 + if len(value_progressiva) > 0: # Controlla che ci siano dati + #value_progressiva = json.loads(json.dumps(value_progressiva)) + for key_progressiva_mira, value_progressiva_mira_dati in value_progressiva.items(): + global_z = 0 + global_n = 0 + global_e = 0 + global_elevation = 0 + for gruppo_dati in value_progressiva_mira_dati: + tmp_global_n = global_n + tmp_global_e = global_e + tmp_global_elevation = global_elevation + if len(gruppo_dati) > 0: + for j in range(len(gruppo_dati)): + lavoro_id = gruppo_dati[j][3] + fasi_lavorazione = gruppo_dati[j][23] + area_attenzione_inizio_binari_trasv = gruppo_dati[j][28] + area_intervento_inizio_binari_trasv = gruppo_dati[j][29] + area_intervento_immediato_inizio_binari_trasv = gruppo_dati[j][30] + area_attenzione_inizio_binari_sghembo = gruppo_dati[j][37] + area_intervento_inizio_binari_sghembo = gruppo_dati[j][38] + area_intervento_immediato_inizio_binari_sghembo = gruppo_dati[j][39] + area_attenzione_inizio_binari_long_vert = gruppo_dati[j][31] + area_intervento_inizio_binari_long_vert = gruppo_dati[j][32] + area_intervento_immediato_inizio_binari_long_vert = gruppo_dati[j][33] + area_attenzione_inizio_binari_long_oriz = gruppo_dati[j][34] + area_intervento_inizio_binari_long_oriz = gruppo_dati[j][35] + area_intervento_immediato_inizio_binari_long_oriz = gruppo_dati[j][36] + passo_sghembo = gruppo_dati[j][27] + passo_long = gruppo_dati[j][25] + parametro_letture_binari = int(gruppo_dati[j][48]) + email_livello_unoBinariTrasv = int(gruppo_dati[j][49]) + email_livello_dueBinariTrasv = int(gruppo_dati[j][50]) + email_livello_treBinariTrasv = int(gruppo_dati[j][51]) + sms_livello_unoBinariTrasv = int(gruppo_dati[j][52]) + sms_livello_dueBinariTrasv = int(gruppo_dati[j][53]) + sms_livello_treBinariTrasv = int(gruppo_dati[j][54]) + email_livello_unoBinariLongVert = int(gruppo_dati[j][55]) + email_livello_dueBinariLongVert = int(gruppo_dati[j][56]) + email_livello_treBinariLongVert = int(gruppo_dati[j][57]) + sms_livello_unoBinariLongVert = int(gruppo_dati[j][58]) + sms_livello_dueBinariLongVert = int(gruppo_dati[j][59]) + sms_livello_treBinariLongVert = int(gruppo_dati[j][60]) + email_livello_unoBinariLongOriz = int(gruppo_dati[j][61]) + email_livello_dueBinariLongOriz = int(gruppo_dati[j][62]) + email_livello_treBinariLongOriz = int(gruppo_dati[j][63]) + sms_livello_unoBinariLongOriz = int(gruppo_dati[j][64]) + sms_livello_dueBinariLongOriz = int(gruppo_dati[j][65]) + sms_livello_treBinariLongOriz = int(gruppo_dati[j][66]) + email_livello_unoBinariSghembo = int(gruppo_dati[j][67]) + email_livello_dueBinariSghembo = int(gruppo_dati[j][68]) + email_livello_treBinariSghembo = int(gruppo_dati[j][69]) + sms_livello_unoBinariSghembo = int(gruppo_dati[j][70]) + sms_livello_dueBinariSghembo = int(gruppo_dati[j][71]) + sms_livello_treBinariSghembo = int(gruppo_dati[j][72]) + if gruppo_dati[j][7] is not None: + timestamp_str = gruppo_dati[j][7] + if isinstance(timestamp_str, datetime): + timestamp_ms = int(timestamp_str.timestamp() * 1000) + else: + timestamp_ms = int(datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000) + spost_trasv_array.setdefault(key_progressiva, {}).setdefault(x, []) + sghembo_array.setdefault(key_progressiva, {}).setdefault(x, []) + spost_long_vert_array.setdefault(key_progressiva, {}).setdefault(x, []) + spost_long_oriz_array.setdefault(key_progressiva, {}).setdefault(x, []) + n = float(gruppo_dati[j][8]) + tmp_global_n + e = float(gruppo_dati[j][9]) + tmp_global_e + z = float(gruppo_dati[j][10]) + tmp_global_elevation + if tmp_global_elevation != 0: + z -= float(gruppo_dati[0][10]) + if tmp_global_n != 0: + n -= float(gruppo_dati[0][8]) + if tmp_global_e != 0: + e -= float(gruppo_dati[0][9]) + spost_trasv_array[key_progressiva][x].append([ + timestamp_ms, + float(z), + gruppo_dati[j][24], + 4, + fasi_lavorazione + ]) + sghembo_array[key_progressiva][x].append([ + timestamp_ms, + float(z), + gruppo_dati[j][24], + 4, + fasi_lavorazione, + float(gruppo_dati[j][47]) + ]) + spost_long_vert_array[key_progressiva][x].append([ + timestamp_ms, + float(z), + gruppo_dati[j][24], + 4, + fasi_lavorazione + ]) + spost_long_oriz_array[key_progressiva][x].append([ + timestamp_ms, + float(n), + gruppo_dati[j][24], + 4, + fasi_lavorazione, + float(e) + ]) + global_n = float(n) + global_e = float(e) + global_elevation = float(z) + x += 1 + print("---spost_trasv_array--") + #print(spost_trasv_array) + for keyTrasv, value in spost_trasv_array.items(): + arrSx = [] + arrDx = [] + if(len(value) == 2): + if(value[0][0][2] == 0):#sinistra + arrSx = value[0] + arrDx = value[1] + if(value[0][0][2] == 1):#destra + arrDx = value[0] + arrSx = value[1] + #arrDx.sort(key=lambda x: x[0]) + #arrSx.sort(key=lambda x: x[0]) + arrSx = sorted(arrSx, key=lambda x: x[0]) + arrDx = sorted(arrDx, key=lambda x: x[0]) + arrays = [arrSx, arrDx] + res = {'array': arrays[0], 'index': 0, 'highestValue': max(arrays[0], key=lambda x: x[0])[0]} + for key in range(1, len(arrays)): + current = arrays[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > res['highestValue']: + res = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_array = res['array'] + index_of_higher_first_date_array = res['index'] + highest_value = res['highestValue'] + #print(higher_first_date_array, index_of_higher_first_date_array, highest_value) + if index_of_higher_first_date_array == 0: # arrSx + if abs(higher_first_date_array[0][0] - arrDx[0][0]) > parametro_letture_binari * 1000: + minDate = higher_first_date_array[0][0] + filteredArray2 = [item for item in arrDx if item[0] >= minDate] + arrDx = filteredArray2 + elif index_of_higher_first_date_array == 1: # arrDx + if abs(higher_first_date_array[0][0] - arrSx[0][0]) > parametro_letture_binari * 1000: + minDate = higher_first_date_array[0][0] + filteredArray2 = [item for item in arrSx if item[0] >= minDate] + arrSx = filteredArray2 + if arrDx and arrSx and arrDx[0] and arrSx[0]: + nearestElementDx = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrDx) + nearestElementSx = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrSx) + nearestElementDxPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrDx) + nearestElementSxPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrSx) + if(nearestElementDx and nearestElementSx and nearestElementDxPenultimo and nearestElementSxPenultimo): + if (abs(nearestElementDx[0] - nearestElementSx[0]) <= parametro_letture_binari * 1000 and abs(arrDx[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + max_millis = max(nearestElementDx[0], nearestElementSx[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + dz = ((float(nearestElementDx[1]) - float(nearestElementSx[1])) - (float(arrDx[0][1]) - float(arrSx[0][1]))) * 1000 + print(dato_date, keyTrasv, dz, lavoro_id) + if (abs(nearestElementDxPenultimo[0] - nearestElementSxPenultimo[0]) <= parametro_letture_binari * 1000 and abs(arrDx[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + dz_penultimo = ((float(nearestElementDxPenultimo[1]) - float(nearestElementSxPenultimo[1])) - (float(arrDx[0][1]) - float(arrSx[0][1]))) * 1000 + print("prev: ", keyTrasv, dz_penultimo) + if(area_attenzione_inizio_binari_trasv is not None and area_intervento_inizio_binari_trasv is not None and area_intervento_immediato_inizio_binari_trasv is not None): + if(abs(dz) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz) <= abs(float(area_intervento_inizio_binari_trasv))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), 1, dato_date, 41]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(dz_penultimo) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 1, sms_livello_unoBinariTrasv, email_livello_unoBinariTrasv]) + conn.commit() + elif(abs(dz) >= abs(float(area_intervento_inizio_binari_trasv)) and abs(dz) <= abs(float(area_intervento_immediato_inizio_binari_trasv))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), 2, dato_date, 41]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(dz_penultimo) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_inizio_binari_trasv))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 2, sms_livello_dueBinariTrasv, email_livello_dueBinariTrasv]) + conn.commit() + elif not ( (abs(dz_penultimo) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 2, sms_livello_dueBinariTrasv, email_livello_dueBinariTrasv]) + conn.commit() + elif(abs(dz) >= abs(float(area_intervento_immediato_inizio_binari_trasv)) and abs(dz) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), 3, dato_date, 41]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(dz_penultimo) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_inizio_binari_trasv))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 3, sms_livello_treBinariTrasv, email_livello_treBinariTrasv]) + conn.commit() + elif(abs(dz_penultimo) >= abs(float(area_intervento_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_trasv))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 3, sms_livello_treBinariTrasv, email_livello_treBinariTrasv]) + conn.commit() + elif not ( (abs(dz_penultimo) >= abs(float(area_attenzione_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_trasv))) or + (abs(dz_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_trasv)) and abs(dz_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,41,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyTrasv), dato_date, dz, 3, sms_livello_treBinariTrasv, email_livello_treBinariTrasv]) + conn.commit() + print("---------------") + print("---spost_long_vert_array---") + #print(spost_long_vert_array) + valueProgressive = [] + for keyProgressivaLongVert, valueProgressiva in spost_long_vert_array.items(): + print("keyProgressivaLongVert: ",keyProgressivaLongVert) + valueProgressive.append({'key': keyProgressivaLongVert, 'data': valueProgressiva}) + #print("valueProgressive: ", valueProgressive) + if(len(valueProgressive) >= 3): + for index, vp in enumerate(valueProgressive): + if(index > 1):#parto dalla terza + keyProgressiva = vp["key"] + valueProgressiva = vp["data"] + keyProgressivaPrev = valueProgressive[index-2]["key"] + valueProgressivaPrev = valueProgressive[index-2]["data"] + snameDx = keyProgressivaPrev +" - "+ keyProgressiva +" (R)" + snameSx = keyProgressivaPrev +" - "+ keyProgressiva +" (L)" + print(snameDx) + print(snameSx) + arrSx = [] + arrDx = [] + arrSxPrev = [] + arrDxPrev = [] + if(len(valueProgressiva) == 2 and len(valueProgressivaPrev) == 2):#2 mire + if(valueProgressiva[0][0][2] == 0):#sinistra + arrSx = valueProgressiva[0] + arrDx = valueProgressiva[1] + if(valueProgressiva[0][0][2] == 1):#destra + arrDx = valueProgressiva[0] + arrSx = valueProgressiva[1] + arrSx = sorted(arrSx, key=lambda x: x[0]) + arrDx = sorted(arrDx, key=lambda x: x[0]) + if(valueProgressivaPrev[0][0][2] == 0):#sinistra + arrSxPrev = valueProgressivaPrev[0] + arrDxPrev = valueProgressivaPrev[1] + if(valueProgressivaPrev[0][0][2] == 1):#destra + arrDxPrev = valueProgressivaPrev[0] + arrSxPrev = valueProgressivaPrev[1] + arrSxPrev = sorted(arrSxPrev, key=lambda x: x[0]) + arrDxPrev = sorted(arrDxPrev, key=lambda x: x[0]) + # + arraysDx = [arrDx, arrDxPrev] + arraysSx = [arrSx, arrSxPrev] + resDx = {'array': arraysDx[0], 'index': 0, 'highestValue': max(arraysDx[0], key=lambda x: x[0])[0]} + for key in range(1, len(arraysDx)): + current = arraysDx[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > resDx['highestValue']: + resDx = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_arrayDx = resDx['array'] + index_of_higher_first_date_arrayDx = resDx['index'] + highest_valueDx = resDx['highestValue'] + print("index_of_higher_first_date_arrayDx: ",index_of_higher_first_date_arrayDx, "highest_valueDx: ",highest_valueDx) + minDateDx = higher_first_date_arrayDx[0][0] + # + resSx = {'array': arraysSx[0], 'index': 0, 'highestValue': max(arraysSx[0], key=lambda x: x[0])[0]} + for key in range(1, len(arraysSx)): + current = arraysSx[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > resSx['highestValue']: + resSx = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_arraySx = resSx['array'] + index_of_higher_first_date_arraySx = resSx['index'] + highest_valueSx = resSx['highestValue'] + print("index_of_higher_first_date_arraySx: ",index_of_higher_first_date_arraySx, "highest_valueSx: ",highest_valueSx) + minDateSx = higher_first_date_arraySx[0][0] + # + if index_of_higher_first_date_arrayDx == 0:#arrDx + if abs(minDateDx - arrDxPrev[0][0]) > parametro_letture_binari * 1000: + arrDxPrev = [item for item in arrDxPrev if item[0] >= minDateDx] + elif index_of_higher_first_date_arrayDx == 1:#arrDxPrev + if abs(minDateDx - arrDx[0][0]) > parametro_letture_binari * 1000: + arrDx = [item for item in arrDx if item[0] >= minDateDx] + if index_of_higher_first_date_arraySx == 0:#arrSx + if abs(minDateSx - arrSxPrev[0][0]) > parametro_letture_binari * 1000: + arrSxPrev = [item for item in arrSxPrev if item[0] >= minDateSx] + elif index_of_higher_first_date_arraySx == 1:#arrSxPrev + if abs(minDateSx - arrSx[0][0]) > parametro_letture_binari * 1000: + arrSx = [item for item in arrSx if item[0] >= minDateSx] + # + if (arrDx and len(arrDx) > 0 and arrDxPrev and len(arrDxPrev) > 0): + nearestElementDx = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-1][0], arrDx) + nearestElementDxPenultimo = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-2][0], arrDx) + nearestElementDxPrev = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-1][0], arrDxPrev) + nearestElementDxPrevPenultimo = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-2][0], arrDxPrev) + if(nearestElementDx and nearestElementDxPenultimo and nearestElementDxPrev and nearestElementDxPrevPenultimo): + max_millis = max(nearestElementDx[0], nearestElementDxPenultimo[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + print(abs(nearestElementDxPrev[0] - nearestElementDx[0]), parametro_letture_binari * 1000) + print("nearestElementDxPrev[0]: ", nearestElementDxPrev[0], "nearestElementDx[0]: ", nearestElementDx[0]) + print(abs(arrDxPrev[0][0] - arrDx[0][0]), parametro_letture_binari * 1000) + if ( + abs(nearestElementDxPrev[0] - nearestElementDx[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000): + zdx = nearestElementDx[1] + zdxPrev = nearestElementDxPrev[1] + spost_long_vert_dx = ((float(zdx) - float(zdxPrev)) - (float(arrDx[0][1]) - float(arrDxPrev[0][1]))) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_vert_dx) + if ( + abs(nearestElementDxPrevPenultimo[0] - nearestElementDxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000): + zdx = nearestElementDxPenultimo[1] + zdxPrev = nearestElementDxPrevPenultimo[1] + spost_long_vert_dx_penultimo = ((float(zdx) - float(zdxPrev)) - (float(arrDx[0][1]) - float(arrDxPrev[0][1]))) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_vert_dx_penultimo) + if(area_attenzione_inizio_binari_long_vert is not None and area_intervento_inizio_binari_long_vert is not None and area_intervento_immediato_inizio_binari_long_vert is not None): + if(abs(spost_long_vert_dx) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx) <= abs(float(area_intervento_inizio_binari_long_vert))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 1, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(spost_long_vert_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 1, "R", sms_livello_unoBinariLongVert, email_livello_unoBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_dx) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_dx) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 2, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_vert_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 2, "R", sms_livello_dueBinariLongVert, email_livello_dueBinariLongVert]) + conn.commit() + elif not ( (abs(spost_long_vert_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 2, "R", sms_livello_dueBinariLongVert, email_livello_dueBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_dx) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_dx) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 3, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_vert_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 3, "R", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 3, "R", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + elif not ( (abs(spost_long_vert_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_dx, 3, "R", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + if (arrSx and len(arrSx) > 0 and arrSxPrev and len(arrSxPrev) > 0): + nearestElementSx = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-1][0], arrSx) + nearestElementSxPenultimo = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-2][0], arrSx) + nearestElementSxPrev = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-1][0], arrSxPrev) + nearestElementSxPrevPenultimo = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-2][0], arrSxPrev) + if(nearestElementSx and nearestElementSxPenultimo and nearestElementSxPrev and nearestElementSxPrevPenultimo): + max_millis = max(nearestElementSx[0], nearestElementSxPenultimo[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + print(abs(nearestElementSxPrev[0] - nearestElementSx[0]), parametro_letture_binari * 1000) + print("nearestElementSxPrev[0]: ", nearestElementSxPrev[0], "nearestElementSx[0]: ", nearestElementSx[0]) + print(abs(arrSxPrev[0][0] - arrSx[0][0]), parametro_letture_binari * 1000) + if ( + abs(nearestElementSxPrev[0] - nearestElementSx[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + zsx = nearestElementSx[1] + zsxPrev = nearestElementSxPrev[1] + spost_long_vert_sx = ((float(zsx) - float(zsxPrev)) - (float(arrSx[0][1]) - float(arrSxPrev[0][1]))) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_vert_sx) + if ( + abs(nearestElementSxPrevPenultimo[0] - nearestElementSxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + zsx = nearestElementSxPenultimo[1] + zsxPrev = nearestElementSxPrevPenultimo[1] + spost_long_vert_sx_penultimo = ((float(zsx) - float(zsxPrev)) - (float(arrSx[0][1]) - float(arrSxPrev[0][1]))) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_vert_sx_penultimo) + if(area_attenzione_inizio_binari_long_vert is not None and area_intervento_inizio_binari_long_vert is not None and area_intervento_immediato_inizio_binari_long_vert is not None): + if(abs(spost_long_vert_sx) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx) <= abs(float(area_intervento_inizio_binari_long_vert))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 1, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(spost_long_vert_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 1, "L", sms_livello_unoBinariLongVert, email_livello_unoBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_sx) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_sx) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 2, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_vert_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 2, "L", sms_livello_dueBinariLongVert, email_livello_dueBinariLongVert]) + conn.commit() + elif not ( (abs(spost_long_vert_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 2, "L", sms_livello_dueBinariLongVert, email_livello_dueBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_sx) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_sx) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 3, dato_date, 43]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_vert_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 3, "L", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + elif(abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 3, "L", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + elif not ( (abs(spost_long_vert_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_vert))) or + (abs(spost_long_vert_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_vert)) and abs(spost_long_vert_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,43,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_vert_sx, 3, "L", sms_livello_treBinariLongVert, email_livello_treBinariLongVert]) + conn.commit() + print("---------------") + print("---spost_long_oriz_array---") + #print(spost_long_oriz_array) + valueProgressive = [] + for keyProgressivaLongOriz, valueProgressiva in spost_long_oriz_array.items(): + valueProgressive.append({'key': keyProgressivaLongOriz, 'data': valueProgressiva}) + if(len(valueProgressive) >= 3): + for index, vp in enumerate(valueProgressive): + if(index > 1):#parto dalla terza + keyProgressiva = vp["key"] + valueProgressiva = vp["data"] + keyProgressivaPrev = valueProgressive[index-2]["key"] + valueProgressivaPrev = valueProgressive[index-2]["data"] + snameDx = keyProgressivaPrev +" - "+ keyProgressiva +" (R)" + snameSx = keyProgressivaPrev +" - "+ keyProgressiva +" (L)" + arrSx = [] + arrDx = [] + arrSxPrev = [] + arrDxPrev = [] + if(len(valueProgressiva) == 2 and len(valueProgressivaPrev) == 2):#2 mire + if(valueProgressiva[0][0][2] == 0):#sinistra + arrSx = valueProgressiva[0] + arrDx = valueProgressiva[1] + if(valueProgressiva[0][0][2] == 1):#destra + arrDx = valueProgressiva[0] + arrSx = valueProgressiva[1] + arrSx = sorted(arrSx, key=lambda x: x[0]) + arrDx = sorted(arrDx, key=lambda x: x[0]) + if(valueProgressivaPrev[0][0][2] == 0):#sinistra + arrSxPrev = valueProgressivaPrev[0] + arrDxPrev = valueProgressivaPrev[1] + if(valueProgressivaPrev[0][0][2] == 1):#destra + arrDxPrev = valueProgressivaPrev[0] + arrSxPrev = valueProgressivaPrev[1] + arrSxPrev = sorted(arrSxPrev, key=lambda x: x[0]) + arrDxPrev = sorted(arrDxPrev, key=lambda x: x[0]) + # + arraysDx = [arrDx, arrDxPrev] + arraysSx = [arrSx, arrSxPrev] + resDx = {'array': arraysDx[0], 'index': 0, 'highestValue': max(arraysDx[0], key=lambda x: x[0])[0]} + for key in range(1, len(arraysDx)): + current = arraysDx[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > resDx['highestValue']: + resDx = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_arrayDx = resDx['array'] + index_of_higher_first_date_arrayDx = resDx['index'] + highest_valueDx = resDx['highestValue'] + print("index_of_higher_first_date_arrayDx: ",index_of_higher_first_date_arrayDx, "highest_valueDx: ",highest_valueDx) + minDateDx = higher_first_date_arrayDx[0][0] + # + resSx = {'array': arraysSx[0], 'index': 0, 'highestValue': max(arraysSx[0], key=lambda x: x[0])[0]} + for key in range(1, len(arraysSx)): + current = arraysSx[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > resSx['highestValue']: + resSx = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_arraySx = resSx['array'] + index_of_higher_first_date_arraySx = resSx['index'] + highest_valueSx = resSx['highestValue'] + print("index_of_higher_first_date_arraySx: ",index_of_higher_first_date_arraySx, "highest_valueSx: ",highest_valueSx) + minDateSx = higher_first_date_arraySx[0][0] + # + if index_of_higher_first_date_arrayDx == 0:#arrDx + if abs(minDateDx - arrDxPrev[0][0]) > parametro_letture_binari * 1000: + arrDxPrev = [item for item in arrDxPrev if item[0] >= minDateDx] + elif index_of_higher_first_date_arrayDx == 1:#arrDxPrev + if abs(minDateDx - arrDx[0][0]) > parametro_letture_binari * 1000: + arrDx = [item for item in arrDx if item[0] >= minDateDx] + if index_of_higher_first_date_arraySx == 0:#arrSx + if abs(minDateSx - arrSxPrev[0][0]) > parametro_letture_binari * 1000: + arrSxPrev = [item for item in arrSxPrev if item[0] >= minDateSx] + elif index_of_higher_first_date_arraySx == 1:#arrSxPrev + if abs(minDateSx - arrSx[0][0]) > parametro_letture_binari * 1000: + arrSx = [item for item in arrSx if item[0] >= minDateSx] + # + if (arrDx and len(arrDx) > 0 and arrDxPrev and len(arrDxPrev) > 0): + nearestElementDx = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-1][0], arrDx) + nearestElementDxPenultimo = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-2][0], arrDx) + nearestElementDxPrev = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-1][0], arrDxPrev) + nearestElementDxPrevPenultimo = find_nearest_element(higher_first_date_arrayDx[len(higher_first_date_arrayDx)-2][0], arrDxPrev) + if(nearestElementDx and nearestElementDxPenultimo and nearestElementDxPrev and nearestElementDxPrevPenultimo): + max_millis = max(nearestElementDx[0], nearestElementDxPenultimo[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + print(abs(nearestElementDxPrev[0] - nearestElementDx[0]), parametro_letture_binari * 1000) + print("nearestElementDxPrev[0]: ", nearestElementDxPrev[0], "nearestElementDx[0]: ", nearestElementDx[0]) + print(abs(arrDxPrev[0][0] - arrDx[0][0]), parametro_letture_binari * 1000) + if ( + abs(nearestElementDxPrev[0] - nearestElementDx[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000): + ndx = nearestElementDx[1] + ndx0 = arrDx[0][1] + ndxPrev = nearestElementDxPrev[1] + ndxPrev0 = arrDxPrev[0][1] + edx = nearestElementDx[5] + edx0 = arrDx[0][5] + edxPrev = nearestElementDxPrev[5] + edxPrev0 = arrDxPrev[0][5] + spost_long_oriz_dx = (math.sqrt(pow(float(ndx) - float(ndxPrev), 2) + pow(float(edx) - float(edxPrev), 2)) - math.sqrt(pow(float(ndx0) - float(ndxPrev0), 2) + pow(float(edx0) - float(edxPrev0), 2))) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_oriz_dx) + if ( + abs(nearestElementDxPrevPenultimo[0] - nearestElementDxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000): + ndx = nearestElementDxPenultimo[1] + ndx0 = arrDx[0][1] + edx = nearestElementDxPenultimo[5] + edx0 = arrDx[0][5] + ndxPrev = nearestElementDxPrevPenultimo[1] + ndxPrev0 = arrDxPrev[0][1] + edxPrev = nearestElementDxPrevPenultimo[5] + edxPrev0 = arrDxPrev[0][5] + spost_long_oriz_dx_penultimo = (math.sqrt(pow(float(ndx) - float(ndxPrev), 2) + pow(float(edx) - float(edxPrev), 2)) - math.sqrt(pow(float(ndx0) - float(ndxPrev0), 2) + pow(float(edx0) - float(edxPrev0), 2))) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_oriz_dx_penultimo) + if(area_attenzione_inizio_binari_long_oriz is not None and area_intervento_inizio_binari_long_oriz is not None and area_intervento_immediato_inizio_binari_long_oriz is not None): + if(abs(spost_long_oriz_dx) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx) <= abs(float(area_intervento_inizio_binari_long_oriz))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 1, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 1, "R", sms_livello_unoBinariLongOriz, email_livello_unoBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_dx) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 2, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_oriz_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 2, "R", sms_livello_dueBinariLongOriz, email_livello_dueBinariLongOriz]) + conn.commit() + elif not ( (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 2, "R", sms_livello_dueBinariLongOriz, email_livello_dueBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_dx) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 3, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_oriz_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 3, "R", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 3, "R", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + elif not ( (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_dx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_dx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_dx, 3, "R", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + if (arrSx and len(arrSx) > 0 and arrSxPrev and len(arrSxPrev) > 0): + nearestElementSx = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-1][0], arrSx) + nearestElementSxPenultimo = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-2][0], arrSx) + nearestElementSxPrev = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-1][0], arrSxPrev) + nearestElementSxPrevPenultimo = find_nearest_element(higher_first_date_arraySx[len(higher_first_date_arraySx)-2][0], arrSxPrev) + if(nearestElementSx and nearestElementSxPenultimo and nearestElementSxPrev and nearestElementSxPrevPenultimo): + max_millis = max(nearestElementSx[0], nearestElementSxPenultimo[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + print(abs(nearestElementSxPrev[0] - nearestElementSx[0]), parametro_letture_binari * 1000) + print("nearestElementSxPrev[0]: ", nearestElementSxPrev[0], "nearestElementSx[0]: ", nearestElementSx[0]) + print(abs(arrSxPrev[0][0] - arrSx[0][0]), parametro_letture_binari * 1000) + if ( + abs(nearestElementSxPrev[0] - nearestElementSx[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + nsx = nearestElementSx[1] + nsx0 = arrSx[0][1] + nsxPrev = nearestElementSxPrev[1] + nsxPrev0 = arrSxPrev[0][1] + esx = nearestElementSx[5] + esx0 = arrSx[0][5] + esxPrev = nearestElementSxPrev[5] + esxPrev0 = arrSxPrev[0][5] + spost_long_oriz_sx = (math.sqrt(pow(float(nsx) - float(nsxPrev), 2) + pow(float(esx) - float(esxPrev), 2)) - math.sqrt(pow(float(nsx0) - float(nsxPrev0), 2) + pow(float(esx0) - float(esxPrev0), 2))) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_oriz_sx) + if ( + abs(nearestElementSxPrevPenultimo[0] - nearestElementSxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + nsx = nearestElementSxPenultimo[1] + nsx0 = arrSx[0][1] + esx = nearestElementSxPenultimo[5] + esx0 = arrSx[0][5] + nsxPrev = nearestElementSxPrevPenultimo[1] + nsxPrev0 = arrSxPrev[0][1] + esxPrev = nearestElementSxPrevPenultimo[5] + esxPrev0 = arrSxPrev[0][5] + spost_long_oriz_sx_penultimo = (math.sqrt(pow(float(nsx) - float(nsxPrev), 2) + pow(float(esx) - float(esxPrev), 2)) - math.sqrt(pow(float(nsx0) - float(nsxPrev0), 2) + pow(float(esx0) - float(esxPrev0), 2))) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_oriz_sx_penultimo) + if(area_attenzione_inizio_binari_long_oriz is not None and area_intervento_inizio_binari_long_oriz is not None and area_intervento_immediato_inizio_binari_long_oriz is not None): + if(abs(spost_long_oriz_sx) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx) <= abs(float(area_intervento_inizio_binari_long_oriz))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 1, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 1, "L", sms_livello_unoBinariLongOriz, email_livello_unoBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_sx) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 2, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_oriz_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 2, "L", sms_livello_dueBinariLongOriz, email_livello_dueBinariLongOriz]) + conn.commit() + elif not ( (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 2, "L", sms_livello_dueBinariLongOriz, email_livello_dueBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_sx) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 3, dato_date, 44]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(spost_long_oriz_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 3, "L", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + elif(abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 3, "L", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + elif not ( (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_attenzione_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(float(area_intervento_immediato_inizio_binari_long_oriz))) or + (abs(spost_long_oriz_sx_penultimo) >= abs(float(area_intervento_immediato_inizio_binari_long_oriz)) and abs(spost_long_oriz_sx_penultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,44,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, spost_long_oriz_sx, 3, "L", sms_livello_treBinariLongOriz, email_livello_treBinariLongOriz]) + conn.commit() + print("---------------") + print("---sghembo_array---") + #print(sghembo_array) + valueProgressive = [] + for keyProgressivaSghembo, valueProgressiva in sghembo_array.items(): + valueProgressive.append({'key': keyProgressivaSghembo, 'data': valueProgressiva}) + if(len(valueProgressive) >= 2): + for index, vp in enumerate(valueProgressive): + if(index > 0):#parto dalla seconda + keyProgressiva = vp["key"] + valueProgressiva = vp["data"] + keyProgressivaPrev = valueProgressive[index-1]["key"] + valueProgressivaPrev = valueProgressive[index-1]["data"] + arrSx = [] + arrDx = [] + arrSxPrev = [] + arrDxPrev = [] + if(len(valueProgressiva) == 2 and len(valueProgressivaPrev) == 2):#2 mire + if(valueProgressiva[0][0][2] == 0):#sinistra + arrSx = valueProgressiva[0] + arrDx = valueProgressiva[1] + if(valueProgressiva[0][0][2] == 1):#destra + arrDx = valueProgressiva[0] + arrSx = valueProgressiva[1] + arrSx = sorted(arrSx, key=lambda x: x[0]) + arrDx = sorted(arrDx, key=lambda x: x[0]) + if(valueProgressivaPrev[0][0][2] == 0):#sinistra + arrSxPrev = valueProgressivaPrev[0] + arrDxPrev = valueProgressivaPrev[1] + if(valueProgressivaPrev[0][0][2] == 1):#destra + arrDxPrev = valueProgressivaPrev[0] + arrSxPrev = valueProgressivaPrev[1] + arrSxPrev = sorted(arrSxPrev, key=lambda x: x[0]) + arrDxPrev = sorted(arrDxPrev, key=lambda x: x[0]) + arrays = [arrSx, arrDx, arrSxPrev, arrDxPrev] + res = {'array': arrays[0], 'index': 0, 'highestValue': max(arrays[0], key=lambda x: x[0])[0]} + for key in range(1, len(arrays)): + current = arrays[key] + highest_epoch = max(current, key=lambda x: x[0])[0] + if highest_epoch > res['highestValue']: + res = {'array': current, 'index': key, 'highestValue': highest_epoch} + higher_first_date_array = res['array'] + index_of_higher_first_date_array = res['index'] + highest_value = res['highestValue'] + #print(higher_first_date_array, index_of_higher_first_date_array, highest_value) + minDate = higher_first_date_array[0][0] + if index_of_higher_first_date_array == 0: # arrSx + if abs(minDate - arrSxPrev[0][0]) > parametro_letture_binari * 1000: + arrSxPrev = [item for item in arrSxPrev if item[0] >= minDate] + if abs(minDate - arrDxPrev[0][0]) > parametro_letture_binari * 1000: + arrDxPrev = [item for item in arrDxPrev if item[0] >= minDate] + if abs(minDate - arrDx[0][0]) > parametro_letture_binari * 1000: + arrDx = [item for item in arrDx if item[0] >= minDate] + elif index_of_higher_first_date_array == 1: # arrDx + if abs(minDate - arrDxPrev[0][0]) > parametro_letture_binari * 1000: + arrDxPrev = [item for item in arrDxPrev if item[0] >= minDate] + if abs(minDate - arrSxPrev[0][0]) > parametro_letture_binari * 1000: + arrSxPrev = [item for item in arrSxPrev if item[0] >= minDate] + if abs(minDate - arrSx[0][0]) > parametro_letture_binari * 1000: + arrSx = [item for item in arrSx if item[0] >= minDate] + elif index_of_higher_first_date_array == 2: # arrSxPrev + if abs(minDate - arrSx[0][0]) > parametro_letture_binari * 1000: + arrSx = [item for item in arrSx if item[0] >= minDate] + if abs(minDate - arrDxPrev[0][0]) > parametro_letture_binari * 1000: + arrDxPrev = [item for item in arrDxPrev if item[0] >= minDate] + if abs(minDate - arrDx[0][0]) > parametro_letture_binari * 1000: + arrDx = [item for item in arrDx if item[0] >= minDate] + elif index_of_higher_first_date_array == 3: # arrDxPrev + if abs(minDate - arrDx[0][0]) > parametro_letture_binari * 1000: + arrDx = [item for item in arrDx if item[0] >= minDate] + if abs(minDate - arrSx[0][0]) > parametro_letture_binari * 1000: + arrSx = [item for item in arrSx if item[0] >= minDate] + if abs(minDate - arrSxPrev[0][0]) > parametro_letture_binari * 1000: + arrSxPrev = [item for item in arrSxPrev if item[0] >= minDate] + if (arrDx and arrSx and len(arrDx) > 0 and len(arrSx) > 0 and arrDxPrev and arrSxPrev and len(arrDxPrev) > 0 and len(arrSxPrev) > 0): + nearestElementDx = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrDx) + nearestElementSx = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrSx) + nearestElementDxPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrDx) + nearestElementSxPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrSx) + nearestElementDxPrev = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrDxPrev) + nearestElementSxPrev = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-1][0], arrSxPrev) + nearestElementDxPrevPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrDxPrev) + nearestElementSxPrevPenultimo = find_nearest_element(higher_first_date_array[len(higher_first_date_array)-2][0], arrSxPrev) + if(nearestElementDx and nearestElementSx and nearestElementDxPenultimo and nearestElementSxPenultimo and nearestElementDxPrev and nearestElementSxPrev and nearestElementDxPrevPenultimo and nearestElementSxPrevPenultimo): + max_millis = max(nearestElementDx[0], nearestElementSx[0], nearestElementDxPenultimo[0], nearestElementSxPenultimo[0]) + dato_date = datetime.fromtimestamp(max_millis / 1000).strftime("%Y-%m-%d %H:%M:%S") + if ( + abs(nearestElementDxPrev[0] - nearestElementDx[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000 and + abs(nearestElementSxPrev[0] - nearestElementSx[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + zdx = nearestElementDx[1] + zdxPrev = nearestElementDxPrev[1] + zsx = nearestElementSx[1] + zsxPrev = nearestElementSxPrev[1] + offsetInizialeSghembo = arrDx[0][5] + sghembo = abs((((float(zdx) - float(zsx)) - (float(zdxPrev) - float(zsxPrev))) / float(passo_sghembo)) + float(offsetInizialeSghembo)) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva), sghembo) + if ( + abs(nearestElementDxPrevPenultimo[0] - nearestElementDxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrDxPrev[0][0] - arrDx[0][0]) <= parametro_letture_binari * 1000 and + abs(nearestElementSxPrevPenultimo[0] - nearestElementSxPenultimo[0]) <= parametro_letture_binari * 1000 and + abs(arrSxPrev[0][0] - arrSx[0][0]) <= parametro_letture_binari * 1000): + zdx = nearestElementDxPenultimo[1] + zdxPrev = nearestElementDxPrevPenultimo[1] + zsx = nearestElementSxPenultimo[1] + zsxPrev = nearestElementSxPrevPenultimo[1] + offsetInizialeSghemboPenultimo = nearestElementDxPenultimo[5] + sghemboPenultimo = abs((((float(zdx) - float(zsx)) - (float(zdxPrev) - float(zsxPrev))) / float(passo_sghembo)) + float(offsetInizialeSghemboPenultimo)) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva), sghemboPenultimo) + if(area_attenzione_inizio_binari_sghembo is not None and area_intervento_inizio_binari_sghembo is not None and area_intervento_immediato_inizio_binari_sghembo is not None): + if(abs(sghembo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghembo) <= abs(float(area_intervento_inizio_binari_sghembo))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 1, dato_date, 42]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(sghemboPenultimo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_immediato_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_immediato_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 1, sms_livello_unoBinariSghembo, email_livello_unoBinariSghembo]) + conn.commit() + elif(abs(sghembo) >= abs(float(area_intervento_inizio_binari_sghembo)) and abs(sghembo) <= abs(float(area_intervento_immediato_inizio_binari_sghembo))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 2, dato_date, 42]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(sghemboPenultimo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_inizio_binari_sghembo))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 2, sms_livello_dueBinariSghembo, email_livello_dueBinariSghembo]) + conn.commit() + elif not ( (abs(sghemboPenultimo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_immediato_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_immediato_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 2, sms_livello_dueBinariSghembo, email_livello_dueBinariSghembo]) + conn.commit() + elif(abs(sghembo) >= abs(float(area_intervento_immediato_inizio_binari_sghembo)) and abs(sghembo) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), 3, dato_date, 42]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(sghemboPenultimo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_inizio_binari_sghembo))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 3, sms_livello_treBinariSghembo, email_livello_treBinariSghembo]) + conn.commit() + elif(abs(sghemboPenultimo) >= abs(float(area_intervento_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_immediato_inizio_binari_sghembo))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 3, sms_livello_treBinariSghembo, email_livello_treBinariSghembo]) + conn.commit() + elif not ( (abs(sghemboPenultimo) >= abs(float(area_attenzione_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(float(area_intervento_immediato_inizio_binari_sghembo))) or + (abs(sghemboPenultimo) >= abs(float(area_intervento_immediato_inizio_binari_sghembo)) and abs(sghemboPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, send_sms, send_email) value(%s,%s,%s,%s,%s,42,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+str(keyProgressivaPrev)+" - "+str(keyProgressiva), dato_date, sghembo, 3, sms_livello_treBinariSghembo, email_livello_treBinariSghembo]) + conn.commit() + print("---------------") + #ELAB PALI + print("----------------- PALI ----------------") + daArray = {} + daArrayMireName = {} + dzArray = {} + r2dArray = {} + for key, value in arrayCoppie.items(): + arrayDati = value + x = 0 + if(len(arrayDati) > 0): + fasi_lavorazione = None + areaAttenzioneInizioCoppieInc = None + areaInterventoInizioCoppieInc = None + areaInterventoImmediatoInizioCoppieInc = None + areaAttenzioneInizioCoppieAssest = None + areaInterventoInizioCoppieAssest = None + areaInterventoImmediatoInizioCoppieAssest = None + areaAttenzioneInizioCoppieSpostLat = None + areaInterventoInizioCoppieSpostLat = None + areaInterventoImmediatoInizioCoppieSpostLat = None + soglieCoppieUnitaMisura = None + minDatoInc = 0 + maxDatoInc = 0 + minDatoAssest = 0 + maxDatoAssest = 0 + minDatoSpostLat = 0 + maxDatoSpostLat = 0 + lavoro_id = 0 + reportVarInclin = 0 + reportAssest = 0 + reportSpostLat = 0 + parametroLetture = 4200 + email_livello_unoCoppieInc = 0 + email_livello_dueCoppieInc = 0 + email_livello_treCoppieInc = 0 + sms_livello_unoCoppieInc = 0 + sms_livello_dueCoppieInc = 0 + sms_livello_treCoppieInc = 0 + email_livello_unoCoppieAssest = 0 + email_livello_dueCoppieAssest = 0 + email_livello_treCoppieAssest = 0 + sms_livello_unoCoppieAssest = 0 + sms_livello_dueCoppieAssest = 0 + sms_livello_treCoppieAssest = 0 + email_livello_unoCoppieSpostLat = 0 + email_livello_dueCoppieSpostLat = 0 + email_livello_treCoppieSpostLat = 0 + sms_livello_unoCoppieSpostLat = 0 + sms_livello_dueCoppieSpostLat = 0 + sms_livello_treCoppieSpostLat = 0 + arrayDati = dict(sorted(arrayDati.items())) # Equivalent to ksort in PHP + for kk, coppieData in arrayDati.items(): + cd = list(coppieData.values()) + # Process the first element of cd + cd[0] = list({tuple(x) for x in cd[0]}) # Remove duplicates using serialization logic + cd[0] = [list(x) for x in cd[0]] # Convert back to original list of lists + # Process the second element of cd + cd[1] = list({tuple(x) for x in cd[1]}) # Remove duplicates using serialization logic + cd[1] = [list(x) for x in cd[1]] # Convert back to original list of lists + # Assign processed data + datiMiraA = cd[0] + datiMiraB = cd[1] + globalA = 0 + globalB = 0 + globalDX1 = 0 + globalDY1 = 0 + globalDZ1 = 0 + globalDX2 = 0 + globalDY2 = 0 + globalDZ2 = 0 + if(datiMiraA and datiMiraB): + for sub_array in datiMiraA: + sub_array.sort(key=lambda tup: tup[7]) + for sub_array in datiMiraB: + sub_array.sort(key=lambda tup: tup[7]) + arrays = [datiMiraA, datiMiraB] + res = { + 'array': arrays[0], + 'index': 0, + 'highestValue': max( + max(sub_array, key=lambda x: x[7])[7] for sub_array in arrays[0] + ), + } + # Iterate through arrays + for key in range(1, len(arrays)): + current = arrays[key] + highest_epoch = max( + max(sub_array, key=lambda x: x[7])[7] for sub_array in current + ) + if highest_epoch > res['highestValue']: + res = { + 'array': current, + 'index': key, + 'highestValue': highest_epoch, + } + # Extract results + higher_first_date_array = res['array'] + index_of_higher_first_date_array = res['index'] + highest_value = res['highestValue'] + #print(higher_first_date_array, index_of_higher_first_date_array, highest_value) + for i in range(len(datiMiraA)): + tmpGlobalDX1 = globalDX1 + tmpGlobalDY1 = globalDY1 + tmpGlobalDZ1 = globalDZ1 + for j in range(len(datiMiraA[i])): + if key not in dzArray: + dzArray[key] = {} + if key not in r2dArray: + r2dArray[key] = {} + if x not in dzArray[key]: + dzArray[key][x] = {} + if x not in r2dArray[key]: + r2dArray[key][x] = {} + if datiMiraA[i][j][6] not in dzArray[key][x]: + dzArray[key][x][datiMiraA[i][j][6]] = [] + if datiMiraA[i][j][6] not in r2dArray[key][x]: + r2dArray[key][x][datiMiraA[i][j][6]] = [] + dx = (float(datiMiraA[i][j][8]) - float(datiMiraA[i][0][8]))+tmpGlobalDX1 + dy = (float(datiMiraA[i][j][9]) - float(datiMiraA[i][0][9]))+tmpGlobalDY1 + dz = (float(datiMiraA[i][j][10]) - float(datiMiraA[i][0][10]))+tmpGlobalDZ1 + r2d = math.sqrt(pow(float(dx*1000), 2) + pow(float(dy*1000), 2)) + timestamp_str = datiMiraA[i][j][7] + timestamp_ms = 0 + if isinstance(timestamp_str, datetime): + timestamp_ms = int(timestamp_str.timestamp() * 1000) + else: + timestamp_ms = int(datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000) + dzArray[key][x][datiMiraA[i][j][6]].append([ + timestamp_ms, + float(dz * 1000) + ]) + r2dArray[key][x][datiMiraA[i][j][6]].append([ + timestamp_ms, + float(r2d) + ]) + globalDX1 = float(dx) + globalDY1 = float(dy) + globalDZ1 = float(dz) + for i in range(len(datiMiraB)): + tmpGlobalDX2 = globalDX2 + tmpGlobalDY2 = globalDY2 + tmpGlobalDZ2 = globalDZ2 + for j in range(len(datiMiraB[i])): + if key not in dzArray: + dzArray[key] = {} + if key not in r2dArray: + r2dArray[key] = {} + if x not in dzArray[key]: + dzArray[key][x] = {} + if x not in r2dArray[key]: + r2dArray[key][x] = {} + if datiMiraB[i][j][6] not in dzArray[key][x]: + dzArray[key][x][datiMiraB[i][j][6]] = [] + if datiMiraB[i][j][6] not in r2dArray[key][x]: + r2dArray[key][x][datiMiraB[i][j][6]] = [] + dx = (float(datiMiraB[i][j][8]) - float(datiMiraB[i][0][8]))+tmpGlobalDX2 + dy = (float(datiMiraB[i][j][9]) - float(datiMiraB[i][0][9]))+tmpGlobalDY2 + dz = (float(datiMiraB[i][j][10]) - float(datiMiraB[i][0][10]))+tmpGlobalDZ2 + r2d = math.sqrt(pow(float(dx*1000), 2) + pow(float(dy*1000), 2)) + timestamp_str = datiMiraB[i][j][7] + timestamp_ms = 0 + if isinstance(timestamp_str, datetime): + timestamp_ms = int(timestamp_str.timestamp() * 1000) + else: + timestamp_ms = int(datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000) + dzArray[key][x][datiMiraB[i][j][6]].append([ + timestamp_ms, + float(dz * 1000) + ]) + r2dArray[key][x][datiMiraB[i][j][6]].append([ + timestamp_ms, + float(r2d) + ]) + globalDX2 = float(dx) + globalDY2 = float(dy) + globalDZ2 = float(dz) + if(len(higher_first_date_array) > 0): + for i in range(len(higher_first_date_array)): + tmpGlobalA = globalA + tmpGlobalB = globalB + if(datiMiraA[i] and datiMiraB[i] and datiMiraA[i][0] and datiMiraB[i][0]): + #print("index_of_higher_first_date_array: ",index_of_higher_first_date_array) + if(index_of_higher_first_date_array == 0): + higher_first_date_timestamp = int(higher_first_date_array[i][0][7].timestamp() * 1000) + dati_mira_b_timestamp = int(datiMiraB[i][0][7].timestamp() * 1000) + parametro_letture = higher_first_date_array[i][0][37] * 1000 + if abs(higher_first_date_timestamp - dati_mira_b_timestamp) > parametro_letture: + min_date = higher_first_date_array[i][0] + filtered_array2 = [ + item for item in datiMiraB[i] + if int(item[7].timestamp() * 1000) >= higher_first_date_timestamp + ] + datiMiraB[i] = filtered_array2 + elif(index_of_higher_first_date_array == 1): + higher_first_date_timestamp = int(higher_first_date_array[i][0][7].timestamp() * 1000) + dati_mira_a_timestamp = int(datiMiraA[i][0][7].timestamp() * 1000) + parametro_letture = higher_first_date_array[i][0][37] * 1000 + if abs(higher_first_date_timestamp - dati_mira_a_timestamp) > parametro_letture: + min_date = higher_first_date_array[i][0] + filtered_array2 = [ + item for item in datiMiraA[i] + if int(item[7].timestamp() * 1000) >= higher_first_date_timestamp + ] + datiMiraA[i] = filtered_array2 + for j in range(len(higher_first_date_array[i])): + soglieCoppieUnitaMisura = higher_first_date_array[i][j][24] + fasi_lavorazione = higher_first_date_array[i][j][23] + areaAttenzioneInizioCoppieInc = higher_first_date_array[i][j][25] + areaInterventoInizioCoppieInc = higher_first_date_array[i][j][26] + areaInterventoImmediatoInizioCoppieInc = higher_first_date_array[i][j][27] + areaAttenzioneInizioCoppieAssest = higher_first_date_array[i][j][28] + areaInterventoInizioCoppieAssest = higher_first_date_array[i][j][29] + areaInterventoImmediatoInizioCoppieAssest = higher_first_date_array[i][j][30] + areaAttenzioneInizioCoppieSpostLat = higher_first_date_array[i][j][31] + areaInterventoInizioCoppieSpostLat = higher_first_date_array[i][j][32] + areaInterventoImmediatoInizioCoppieSpostLat = higher_first_date_array[i][j][33] + lavoro_id = higher_first_date_array[i][j][3] + parametroLetture = higher_first_date_array[i][j][37] + email_livello_unoCoppieInc = higher_first_date_array[i][j][38] + email_livello_dueCoppieInc = higher_first_date_array[i][j][39] + email_livello_treCoppieInc = higher_first_date_array[i][j][40] + sms_livello_unoCoppieInc = higher_first_date_array[i][j][41] + sms_livello_dueCoppieInc = higher_first_date_array[i][j][42] + sms_livello_treCoppieInc = higher_first_date_array[i][j][43] + email_livello_unoCoppieAssest = higher_first_date_array[i][j][44] + email_livello_dueCoppieAssest = higher_first_date_array[i][j][45] + email_livello_treCoppieAssest = higher_first_date_array[i][j][46] + sms_livello_unoCoppieAssest = higher_first_date_array[i][j][47] + sms_livello_dueCoppieAssest = higher_first_date_array[i][j][48] + sms_livello_treCoppieAssest = higher_first_date_array[i][j][49] + email_livello_unoCoppieSpostLat = higher_first_date_array[i][j][50] + email_livello_dueCoppieSpostLat = higher_first_date_array[i][j][51] + email_livello_treCoppieSpostLat = higher_first_date_array[i][j][52] + sms_livello_unoCoppieSpostLat = higher_first_date_array[i][j][53] + sms_livello_dueCoppieSpostLat = higher_first_date_array[i][j][54] + sms_livello_treCoppieSpostLat = higher_first_date_array[i][j][55] + if higher_first_date_array[i][j][7] is not None: + daArray.setdefault(key, {}) + daArray[key].setdefault(x, []) + daArrayMireName.setdefault(key, {}) + daArrayMireName[key].setdefault(x, "") + if(datiMiraA[i] and datiMiraB[i]): + nearestElementA = find_nearest_element_coppie(higher_first_date_array[i][j][7].timestamp()*1000, datiMiraA[i]) + nearestElementB = find_nearest_element_coppie(higher_first_date_array[i][j][7].timestamp()*1000, datiMiraB[i]) + if(nearestElementA and nearestElementB): + timestampDiff1 = abs(nearestElementB[7].timestamp()*1000 - nearestElementA[7].timestamp()*1000) + timestampDiff2 = abs(datiMiraB[i][0][7].timestamp()*1000 - datiMiraA[i][0][7].timestamp()*1000) + if(timestampDiff1 <= parametroLetture*1000 and timestampDiff2 <= parametroLetture*1000): + n = float(nearestElementB[8]) - float(nearestElementA[8]) + e = float(nearestElementB[9]) - float(nearestElementA[9]) + z = float(nearestElementB[10]) - float(nearestElementA[10]) + v = math.sqrt(pow(n,2)+pow(e,2)) + a = v/z + n0 = float(datiMiraB[i][0][8]) - float(datiMiraA[i][0][8]) + e0 = float(datiMiraB[i][0][9]) - float(datiMiraA[i][0][9]) + z0 = float(datiMiraB[i][0][10]) - float(datiMiraA[i][0][10]) + v0 = math.sqrt(pow(n0,2)+pow(e0,2)) + a0 = v0/z0 + da = float((math.atan(v / z) - math.atan(v0 / z0)) * 180 / math.pi) + tmpGlobalA # degrees + valChart = float(a - a0) + tmpGlobalB + timestamp = higher_first_date_array[i][j][7].timestamp()*1000 + value_to_push = valChart * 1000 if soglieCoppieUnitaMisura == 1 else da + daArray[key][x].append([timestamp, value_to_push]) + daArrayMireName[key][x] = f"({nearestElementB[6]} - {nearestElementA[6]})" + globalA = da + globalB = valChart + x+=1 + soglieCoppieUnitaMisura = '°' if soglieCoppieUnitaMisura == 0 else 'mm/m' + serieName = "Pole" + for i in range(len(daArray[key])):#variazione angolo di inclinazione + if(daArray[key][i] and len(daArray[key][i]) > 1): + dato_date = datetime.fromtimestamp(daArray[key][i][len(daArray[key][i])-1][0] / 1000).strftime("%Y-%m-%d %H:%M:%S") + da = daArray[key][i][len(daArray[key][i])-1][1] + daPenultimo = daArray[key][i][len(daArray[key][i])-2][1] + print(dato_date, "incl", da, i) + if(areaAttenzioneInizioCoppieInc is not None and areaInterventoInizioCoppieInc is not None and areaInterventoImmediatoInizioCoppieInc is not None): + if(abs(da) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(da) <= abs(float(areaInterventoInizioCoppieInc))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], 1, dato_date, 11]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(daPenultimo) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieInc)) and abs(daPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 1, soglieCoppieUnitaMisura, sms_livello_unoCoppieInc, email_livello_unoCoppieInc]) + conn.commit() + elif(abs(da) >= abs(float(areaInterventoInizioCoppieInc)) and abs(da) <= abs(float(areaInterventoImmediatoInizioCoppieInc))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], 2, dato_date, 11]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(daPenultimo) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoInizioCoppieInc))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 2, soglieCoppieUnitaMisura, sms_livello_dueCoppieInc, email_livello_dueCoppieInc]) + conn.commit() + elif not ( (abs(daPenultimo) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieInc)) and abs(daPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 2, soglieCoppieUnitaMisura, sms_livello_dueCoppieInc, email_livello_dueCoppieInc]) + conn.commit() + elif(abs(da) >= abs(float(areaInterventoImmediatoInizioCoppieInc)) and abs(da) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], 3, dato_date, 11]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(daPenultimo) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoInizioCoppieInc))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 3, soglieCoppieUnitaMisura, sms_livello_treCoppieInc, email_livello_treCoppieInc]) + conn.commit() + elif(abs(daPenultimo) >= abs(float(areaInterventoInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieInc))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 3, soglieCoppieUnitaMisura, sms_livello_treCoppieInc, email_livello_treCoppieInc]) + conn.commit() + elif not ( (abs(daPenultimo) >= abs(float(areaAttenzioneInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoInizioCoppieInc)) and abs(daPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieInc))) or + (abs(daPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieInc)) and abs(daPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,11,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" "+daArrayMireName[key][i], dato_date, da, 3, soglieCoppieUnitaMisura, sms_livello_treCoppieInc, email_livello_treCoppieInc]) + conn.commit() + for i in range(len(dzArray[key])):#assestamento + for mira_name, value in dzArray[key][i].items(): + if(value and len(value) > 1): + dato_date = datetime.fromtimestamp(value[len(value)-1][0] / 1000).strftime("%Y-%m-%d %H:%M:%S") + dz = value[len(value)-1][1] + dzPenultimo = value[len(value)-2][1] + print(dato_date, "assest", dz, i) + if(areaAttenzioneInizioCoppieAssest is not None and areaInterventoInizioCoppieAssest is not None and areaInterventoImmediatoInizioCoppieAssest is not None): + if(abs(dz) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dz) <= abs(float(areaInterventoInizioCoppieAssest))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 1, dato_date, 12]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(dzPenultimo) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 1, "mm", sms_livello_unoCoppieAssest, email_livello_unoCoppieAssest]) + conn.commit() + elif(abs(dz) >= abs(float(areaInterventoInizioCoppieAssest)) and abs(dz) <= abs(float(areaInterventoImmediatoInizioCoppieAssest))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 2, dato_date, 12]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(dzPenultimo) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoInizioCoppieAssest))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 2, "mm", sms_livello_dueCoppieAssest, email_livello_dueCoppieAssest]) + conn.commit() + elif not ( (abs(dzPenultimo) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 2, "mm", sms_livello_dueCoppieAssest, email_livello_dueCoppieAssest]) + conn.commit() + elif(abs(dz) >= abs(float(areaInterventoImmediatoInizioCoppieAssest)) and abs(dz) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 3, dato_date, 12]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(dzPenultimo) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoInizioCoppieAssest))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 3, "mm", sms_livello_treCoppieAssest, email_livello_treCoppieAssest]) + conn.commit() + elif(abs(dzPenultimo) >= abs(float(areaInterventoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieAssest))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 3, "mm", sms_livello_treCoppieAssest, email_livello_treCoppieAssest]) + conn.commit() + elif not ( (abs(dzPenultimo) >= abs(float(areaAttenzioneInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieAssest))) or + (abs(dzPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieAssest)) and abs(dzPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,12,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, dz, 3, "mm", sms_livello_treCoppieAssest, email_livello_treCoppieAssest]) + conn.commit() + for i in range(len(r2dArray[key])):#spostamento laterale + for mira_name, value in r2dArray[key][i].items(): + if(value and len(value) > 1): + dato_date = datetime.fromtimestamp(value[len(value)-1][0] / 1000).strftime("%Y-%m-%d %H:%M:%S") + r2d = value[len(value)-1][1] + r2dPenultimo = value[len(value)-2][1] + print(dato_date, "spost lat", r2d, r2dPenultimo, i) + if(areaAttenzioneInizioCoppieSpostLat is not None and areaInterventoInizioCoppieSpostLat is not None and areaInterventoImmediatoInizioCoppieSpostLat is not None): + if(abs(r2d) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2d) <= abs(float(areaInterventoInizioCoppieSpostLat))): #soglia attenzione + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 1, dato_date, 13]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if not ( (abs(r2dPenultimo) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 1, "mm", sms_livello_unoCoppieSpostLat, email_livello_unoCoppieSpostLat]) + conn.commit() + elif(abs(r2d) >= abs(float(areaInterventoInizioCoppieSpostLat)) and abs(r2d) <= abs(float(areaInterventoImmediatoInizioCoppieSpostLat))): #soglia intervento + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 2, dato_date, 13]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(r2dPenultimo) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoInizioCoppieSpostLat))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 2, "mm", sms_livello_dueCoppieSpostLat, email_livello_dueCoppieSpostLat]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 2, "mm", sms_livello_dueCoppieSpostLat, email_livello_dueCoppieSpostLat]) + conn.commit() + elif(abs(r2d) >= abs(float(areaInterventoImmediatoInizioCoppieSpostLat)) and abs(r2d) <= abs(float(maxValue))): #soglia intervento immediato + query = "select id, type_id, tool_name, date_time, alarm_level, description from alarms where tool_name=%s and alarm_level=%s and date_time >= %s and tipologia=%s order by date_time asc limit 1" + cursor.execute(query, ["upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, 3, dato_date, 13]) + resultAlarm = cursor.fetchall() + if(len(resultAlarm) <= 0):#non c'è + if(abs(r2dPenultimo) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoInizioCoppieSpostLat))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 3, "mm", sms_livello_treCoppieSpostLat, email_livello_treCoppieSpostLat]) + conn.commit() + elif(abs(r2dPenultimo) >= abs(float(areaInterventoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieSpostLat))): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 3, "mm", sms_livello_treCoppieSpostLat, email_livello_treCoppieSpostLat]) + conn.commit() + elif not ( (abs(r2dPenultimo) >= abs(float(areaAttenzioneInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(float(areaInterventoImmediatoInizioCoppieSpostLat))) or + (abs(r2dPenultimo) >= abs(float(areaInterventoImmediatoInizioCoppieSpostLat)) and abs(r2dPenultimo) <= abs(maxValue)) ): + query = "insert ignore into alarms (type_id, tool_name, date_time, registered_value, alarm_level, tipologia, description, send_sms, send_email) value(%s,%s,%s,%s,%s,13,%s,%s,%s)" + cursor.execute(query, [9, "upgeo|"+str(lavoro_id)+"|"+serieName+" "+str(i+1)+" - "+mira_name, dato_date, r2d, 3, "mm", sms_livello_treCoppieSpostLat, email_livello_treCoppieSpostLat]) + conn.commit() + cursor.close() + conn.close() + if "[276_208_TS0003]" in pathFile or "[Neuchatel_CDP]" in pathFile or "[TS0006_EP28]" in pathFile or "[TS0007_ChesaArcoiris]" in pathFile or "[TS0006_EP28_3]" in pathFile or "[TS0006_EP28_4]" in pathFile or "[TS0006_EP28_5]" in pathFile or "[TS18800]" in pathFile or "[Granges_19 100]" in pathFile or "[Granges_19 200]" in pathFile or "[Chesa_Arcoiris_2]" in pathFile or "[TS0006_EP28_1]" in pathFile or "[TS_PS_Petites_Croisettes]" in pathFile or "[_Chesa_Arcoiris_1]" in pathFile or "[TS-VIME]" in pathFile:#sposto il file nella cartella della stazione corretta + orig_folder = pathFile.split("/")[-2] + new_pathFile = pathFile.replace(orig_folder,"home/"+folder_name) + shutil.move(pathFile, new_pathFile) + if not os.path.exists(pathFile): + print(f"File moved successfully from {pathFile} to {new_pathFile}\n") + else: + print("File move operation failed.\n") + #except Exception as e: + # print(f"An unexpected error occurred: {str(e)}\n") + +def main(): + #print(sys.argv) + getDataFromCsvAndInsert(sys.argv[1]) + +if __name__ == '__main__': + main() diff --git a/old_script/dbconfig.py b/old_script/dbconfig.py new file mode 100755 index 0000000..7415831 --- /dev/null +++ b/old_script/dbconfig.py @@ -0,0 +1,15 @@ +from configparser import ConfigParser + +def read_db_config(filename='/home/battilo/scripts/config.ini', section='mysql'): + parser = ConfigParser() + parser.read(filename) + + db = {} + if parser.has_section(section): + items = parser.items(section) + for item in items: + db[item[0]] = item[1] + else: + raise Exception('{0} not found in the {1} file'.format(section, filename)) + + return db diff --git a/utils/config/loader_matlab_elab.py b/utils/config/loader_matlab_elab.py index edcd362..1412a16 100644 --- a/utils/config/loader_matlab_elab.py +++ b/utils/config/loader_matlab_elab.py @@ -29,3 +29,10 @@ class Config: self.dbrawdata = c.get("tables", "rawTableName") self.dbrawdata = c.get("tables", "rawTableName") self.dbnodes = c.get("tables", "nodesTableName") + + # Matlab + self.matlab_runtime = c.get("matlab", "runtime") + self.matlab_func_path = c.get("matlab", "func_path") + self.matlab_timeout = c.getint("matlab", "timeout") + self.matlab_error = c.get("matlab", "error") + self.matlab_error_path = c.get("matlab", "error_path") \ No newline at end of file diff --git a/utils/csv/data_preparation.py b/utils/csv/data_preparation.py index e765096..b5c7813 100644 --- a/utils/csv/data_preparation.py +++ b/utils/csv/data_preparation.py @@ -9,6 +9,16 @@ from itertools import islice logger = logging.getLogger(__name__) async def get_data(cfg: object, id: int, pool) -> tuple: + """ + Retrieves unit name, tool name, and tool data for a given record ID from the database. + + Args: + cfg (object): Configuration object containing database table name. + id (int): The ID of the record to retrieve. + pool: The database connection pool. + Returns: + tuple: A tuple containing unit_name, tool_name, and tool_data. + """ async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute(f'select unit_name, tool_name, tool_data from {cfg.dbrectable} where id = {id}') @@ -17,6 +27,16 @@ async def get_data(cfg: object, id: int, pool) -> tuple: return unit_name, tool_name, tool_data async def make_pipe_sep_matrix(cfg: object, id: int, pool) -> list: + """ + Processes pipe-separated data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) righe = ToolData.splitlines() matrice_valori = [] @@ -39,6 +59,16 @@ async def make_pipe_sep_matrix(cfg: object, id: int, pool) -> list: return matrice_valori async def make_ain_din_matrix(cfg: object, id: int, pool) -> list: + """ + Processes analog and digital input data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) node_channels, node_types, node_ains, node_dins = get_nodes_type(cfg, ToolNameID, UnitName) righe = ToolData.splitlines() @@ -63,6 +93,16 @@ async def make_ain_din_matrix(cfg: object, id: int, pool) -> list: return matrice_valori async def make_channels_matrix(cfg: object, id: int, pool) -> list: + """ + Processes channel-based data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) node_channels, node_types, node_ains, node_dins = get_nodes_type(cfg, ToolNameID, UnitName) righe = ToolData.splitlines() @@ -81,6 +121,16 @@ async def make_channels_matrix(cfg: object, id: int, pool) -> list: return matrice_valori async def make_musa_matrix(cfg: object, id: int, pool) -> list: + """ + Processes 'Musa' specific data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) node_channels, node_types, node_ains, node_dins = get_nodes_type(cfg, ToolNameID, UnitName) righe = ToolData.splitlines() @@ -104,6 +154,16 @@ async def make_musa_matrix(cfg: object, id: int, pool) -> list: async def make_tlp_matrix(cfg: object, id: int, pool) -> list: + """ + Processes 'TLP' specific data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) righe = ToolData.splitlines() valori_x_nodo = 2 @@ -121,6 +181,16 @@ async def make_tlp_matrix(cfg: object, id: int, pool) -> list: async def make_gd_matrix(cfg: object, id: int, pool) -> list: + """ + Processes 'GD' specific data from a CSV record into a structured matrix. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record. + pool: The database connection pool. + Returns: + list: A list of lists, where each inner list represents a row in the matrix. + """ UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) righe = ToolData.splitlines() matrice_valori = [] diff --git a/utils/csv/loaders.py b/utils/csv/loaders.py index cab908e..8612700 100644 --- a/utils/csv/loaders.py +++ b/utils/csv/loaders.py @@ -7,6 +7,15 @@ import logging logger = logging.getLogger(__name__) async def main_loader(cfg: object, id: int, pool, action: str) -> None: + """ + Main loader function to process CSV data based on the specified action. + + Args: + cfg (object): Configuration object. + id (int): The ID of the CSV record to process. + pool: The database connection pool. + action (str): The type of data processing to perform (e.g., "pipe_separator", "analogic_digital"). + """ type_matrix_mapping = { "pipe_separator": make_pipe_sep_matrix, "analogic_digital": make_ain_din_matrix, @@ -27,3 +36,39 @@ async def main_loader(cfg: object, id: int, pool, action: str) -> None: await unlock(cfg, id, pool) else: logger.warning(f"Action '{action}' non riconosciuta.") + + +async def get_next_csv_atomic(pool, table_name, status): + """Preleva atomicamente il prossimo CSV da elaborare""" + async with pool.acquire() as conn: + # IMPORTANTE: Disabilita autocommit per questa transazione + await conn.begin() + + try: + async with conn.cursor() as cur: + # Usa SELECT FOR UPDATE per lock atomico + await cur.execute(f""" + SELECT id, unit_type, tool_type, unit_name, tool_name + FROM {table_name} + WHERE locked = 0 AND status = %s + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED + """, (status,)) + + result = await cur.fetchone() + if result: + await cur.execute(f""" + UPDATE {table_name} + SET locked = 1 + WHERE id = %s + """, (result[0],)) + + # Commit esplicito per rilasciare il lock + await conn.commit() + return result + + except Exception as e: + # Rollback in caso di errore + await conn.rollback() + raise e \ No newline at end of file diff --git a/utils/database/matlab_query.py b/utils/database/matlab_query.py new file mode 100644 index 0000000..0f90b6e --- /dev/null +++ b/utils/database/matlab_query.py @@ -0,0 +1,27 @@ +from utils.database.connection import connetti_db +import logging + +logger = logging.getLogger(__name__) + +def get_matlab_command(cfg: object, tool: str, unit: str) -> tuple: + + with connetti_db(cfg) as conn: + cur = conn.cursor(dictionary=True) + query = f""" + SELECT m.matcall, t.ftp_send , t.unit_id, s.`desc` as statustools, t.api_send, u.inoltro_api, u.inoltro_api_url, u.inoltro_api_bearer_token, IFNULL(u.duedate, "") as duedate from matfuncs as m + INNER JOIN tools as t on t.matfunc = m.id + INNER JOIN units as u on u.id = t.unit_id + INNER JOIN statustools as s on t.statustool_id = s.id + where t.name = '{tool}' AND u.name = '{unit}'; + + """ + cur.execute(query) + result = cur.fetchone() + cur.close() + conn.close() + + if not result: + logger.error(f"{unit} - {tool}: Matlab command not found.") + return None + else: + return result \ No newline at end of file diff --git a/utils/parsers/by_type/isi_csv_log_vulink.py b/utils/parsers/by_type/isi_csv_log_vulink.py index a0f7c26..e4b68f1 100644 --- a/utils/parsers/by_type/isi_csv_log_vulink.py +++ b/utils/parsers/by_type/isi_csv_log_vulink.py @@ -1,2 +1,35 @@ +import subprocess +import tempfile +import os + +from utils.database.loader_action import DATA_LOADED, update_status, unlock +from utils.csv.data_preparation import get_data + +import logging + +logger = logging.getLogger(__name__) + async def main_loader(cfg: object, id: int, pool) -> None: - pass \ No newline at end of file + + UnitName, ToolNameID, ToolData = await get_data(cfg, id, pool) + # Creare un file temporaneo + with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as temp_file: + temp_file.write(ToolData) + temp_filename = temp_file.name + + try: + # Eseguire il programma con il file temporaneo + result = await subprocess.run(['python3', 'old_script/TS_PiniScript.py', temp_filename], capture_output=True, text=True) + print(result.stdout) + print(result.stderr) + finally: + # Pulire il file temporaneo + os.unlink(temp_filename) + + if result.returncode != 0: + logger.error(f"Errore nell'esecuzione del programma TS_PiniScript.py: {result.stderr}") + raise Exception(f"Errore nel programma: {result.stderr}") + else: + logger.info(f"Programma TS_PiniScript.py eseguito con successo: {result.stdout}") + await update_status(cfg, id, DATA_LOADED, pool) + await unlock(cfg, id, pool) \ No newline at end of file