From b7fc29ec20781377dfdab8ec5716758f53c40a6e Mon Sep 17 00:00:00 2001 From: alex Date: Sun, 20 Apr 2025 22:00:55 +0200 Subject: [PATCH] refresh script --- ElabNesa.pl | 4 +- FTPCSVRAW_v2.sh | 17 + LoadCSVData.pl | 671 ++++++++-- LoadCSVData.py | 0 SendFtpElabData.pl | 19 +- TS_PiniScript.py | 2553 +++++++++++++++++++++++++++++++++++++++ TS_PiniScript_old.py | 2536 ++++++++++++++++++++++++++++++++++++++ UnitCsvReceiverSmart.pl | 379 +++++- dbconfig.py | 15 + gflowScript.py | 55 + hirpiniaLoadScript.py | 63 + inoltroViaApiElab.py | 78 ++ inoltroViaApiRaw.py | 47 + loadCSVModbGDLora.py | 180 +++ nesaScript.py | 83 ++ nesaScript_new.py | 213 ++++ run_ATD_lnx.sh | 37 + run_Musa_lnx.sh | 37 + run_RSN_lnx.sh | 37 + run_Tilt_lnx.sh | 37 + scp_aseweb_aruba.sh | 6 + sisgeoLoadScript.py | 305 +++++ sorotecPini.py | 306 +++++ vulinkScript.py | 172 +++ vulinkScript_new_old.py | 125 ++ vulinkScript_old.py | 96 ++ 26 files changed, 7943 insertions(+), 128 deletions(-) create mode 100755 FTPCSVRAW_v2.sh create mode 100644 LoadCSVData.py create mode 100755 TS_PiniScript.py create mode 100755 TS_PiniScript_old.py create mode 100755 dbconfig.py create mode 100755 gflowScript.py create mode 100755 hirpiniaLoadScript.py create mode 100644 inoltroViaApiElab.py create mode 100644 inoltroViaApiRaw.py create mode 100755 loadCSVModbGDLora.py create mode 100755 nesaScript.py create mode 100755 nesaScript_new.py create mode 100755 run_ATD_lnx.sh create mode 100755 run_Musa_lnx.sh create mode 100755 run_RSN_lnx.sh create mode 100755 run_Tilt_lnx.sh create mode 100755 scp_aseweb_aruba.sh create mode 100755 sisgeoLoadScript.py create mode 100755 sorotecPini.py create mode 100755 vulinkScript.py create mode 100755 vulinkScript_new_old.py create mode 100755 vulinkScript_old.py diff --git a/ElabNesa.pl b/ElabNesa.pl index a22e97c..21981c2 100755 --- a/ElabNesa.pl +++ b/ElabNesa.pl @@ -13,11 +13,11 @@ use MIME::Lite; $|++; # Autoflush my ( $filename, $sqlout ); -my $username = 'ase_lar'; +my $username = 'aselar'; my $password = 'laravel'; my $db_lar = 'ase_lar'; my $db_sp = 'ase_lar'; -my $server = 'localhost'; +my $server = '85.235.153.201'; my $db_name = "ase_lar"; my $table = "RAWDATACOR"; my ( @CSVData, @sql ); diff --git a/FTPCSVRAW_v2.sh b/FTPCSVRAW_v2.sh new file mode 100755 index 0000000..aba33f5 --- /dev/null +++ b/FTPCSVRAW_v2.sh @@ -0,0 +1,17 @@ +#!/bin/sh +HOST=$1 +USER=$5 +PASSWD=$6 +FILEPATH=$3 +REMOTEPATH=$2 +FILENAME=$4 + +ftp -inv -p $HOST <> file $outfile created\n"; + print SQLOUT "/* lock " . $db_name . ".$table table */\nLOCK TABLES " . $db_name . ".$table WRITE;\n"; print SQLOUT "INSERT IGNORE INTO " . $db_name . ".$table\n"; - print SQLOUT -"(`UnitName`,`ToolNameID`,`NodeNum`,`EventDate`,`EventTime`,`BatLevel`,`Temperature`,\n"; - print SQLOUT -"`Val0`,`Val1`,`Val2`,`Val3`,`Val4`,`Val5`,`Val6`,`Val7`,`Val8`,`Val9`,`ValA`,`ValB`,`ValC`,`ValD`,`ValE`,`ValF`)\n"; + print SQLOUT "(`UnitName`,`ToolNameID`,`NodeNum`,`EventDate`,`EventTime`,`BatLevel`,`Temperature`,\n"; + print SQLOUT "`Val0`,`Val1`,`Val2`,`Val3`,`Val4`,`Val5`,`Val6`,`Val7`,`Val8`,`Val9`,`ValA`,`ValB`,`ValC`,`ValD`,`ValE`,`ValF`)\n"; print SQLOUT "VALUES\n"; print SQLOUT @sql; @sql = (); @@ -126,11 +133,76 @@ sub writeOutSql { return; } -sub matlabCalc { +sub modifyAndWriteOutSql { + my ($tn) = @_; + my $outfile2 = $sqlout . "_" . $outfilenum++; + open SQLOUT, ">", $outfile2 + or die( getTimeStamp("log") + . " - pid $$ >> Error: opening output file " + . $outfile2 + . ":$!\n" ); + print getTimeStamp("log") . " - pid $$ >> file $outfile2 IPI created\n"; + print SQLOUT "/* lock " + . $db_name + . ".$table table */\nLOCK TABLES " + . $db_name + . ".$table WRITE;\n"; + print SQLOUT "INSERT IGNORE INTO " . $db_name . ".$table\n"; + print SQLOUT "(`UnitName`,`ToolNameID`,`NodeNum`,`EventDate`,`EventTime`,`BatLevel`,`Temperature`,\n"; + print SQLOUT "`Val0`,`Val1`,`Val2`,`Val3`,`Val4`,`Val5`,`Val6`,`Val7`,`Val8`,`Val9`,`ValA`,`ValB`,`ValC`,`ValD`,`ValE`,`ValF`)\n"; + print SQLOUT "VALUES\n"; + foreach my $row (@sql) { + my @row_values = split /','/, $row; + if ($row_values[0] eq "('ID0070" && $row_values[1] eq 'DT0111') { + $row_values[0] = "('ID0070"; + $row_values[1] = 'DT0111 IPI'; + } + elsif ($row_values[0] eq "('ID0071" && $row_values[1] eq 'DT0112') { + $row_values[0] = "('ID0071"; + $row_values[1] = 'DT0112 IPI'; + } + elsif ($row_values[0] eq "('ID0072" && $row_values[1] eq 'DT0113') { + $row_values[0] = "('ID0072"; + $row_values[1] = 'DT0113 IPI'; + } + elsif ($row_values[0] eq "('ID0073" && $row_values[1] eq 'DT0114') { + $row_values[0] = "('ID0073"; + $row_values[1] = 'DT0114 IPI'; + } + elsif ($row_values[0] eq "('ID0273" && $row_values[1] eq 'DT0001') { + $row_values[0] = "('ID0273"; + $row_values[1] = 'DT0002'; + } + elsif ($row_values[0] eq "('ID00279" && $row_values[1] eq 'DT0008') { + $row_values[0] = "('ID0279"; + $row_values[1] = 'DT0008'; + } + my $modified_row_string = "" . join("','", @row_values) . "\n"; + print SQLOUT $modified_row_string; + #print getTimeStamp("log") . " - pid $$ >> row IPI[".$row_values[0]." ".$row_values[1]."] $modified_row_string\n"; + } + + print SQLOUT "/* unlock table */\nUNLOCK TABLES;\n"; + + close SQLOUT + or die( getTimeStamp("log") + . " - pid $$ >> Error in closing file " + . $outfile2 + . "\n" ); + + my @args = ( "mysql", "--login-path=asepath", "-e source " . $outfile2 ); + system(@args) == 0 + or die( getTimeStamp("log") . " - pid $$ >> system @args failed: $?\n" ); + print getTimeStamp("log") . " - pid $$ >> file $outfile2 IPI loaded into DB\n"; + + unlink $outfile2; + return; +} + +sub matlabCalc { $matlab_timestamp = getTimeStamp("db_ts"); - print getTimeStamp("log") - . " - pid $$ >> $unit - $tool MatLab calc started...\n"; + print getTimeStamp("log") . " - pid $$ >> $unit - $tool MatLab calc started...\n"; if ( $matlab_cmd =~ /_lnx$/ ) { $matlab_cmd = './run_' . $matlab_cmd . '.sh'; $MatlabErrorFilename .= "${unit}${tool}_output_error.txt"; @@ -138,18 +210,16 @@ sub matlabCalc { #print $ENV{"HOME"} . "\n"; $ENV{"HOME"} = "/" . $ENV{"HOME"}; - my $cmd_elab = - "timeout $matlab_timeout $matlab_cmd $matlab_rt $unit $tool"; - - #my $args = "sh -c \'cd $matlab_func_dir; pwd; $cmd_elab\'"; - - my $args = -"ssh $matlab_exec_user\@$matlab_proxy_ssh -p $matlab_proxy_ssh_port \'cd $matlab_func_dir; $cmd_elab\'"; + chdir($matlab_func_dir) + or die "cannot change: $!\n"; + print getTimeStamp("log") + . " - pid $$ >> current dir: $matlab_func_dir\n"; + my $args = "timeout $matlab_timeout $matlab_cmd $matlab_rt $unit $tool"; if ( system($args) != 0 ) { - my $argscat = -"sh -c \'cd $MatlabErrorPath; cat _${unit}_${tool}*_\*_output_error.txt > ${unit}${tool}_output_error.txt\'"; + my $argscat = "cd $MatlabErrorPath; cat _${unit}_${tool}*_\*_output_error.txt > ${unit}${tool}_output_error.txt"; system($argscat); + open( my $fh, '<', $MatlabErrorFilename ) or warn print getTimeStamp("log") . " - pid $$ >> Cannot open Matlab output error file: ${MatlabErrorFilename}\n"; @@ -167,8 +237,7 @@ sub matlabCalc { if ( $exit_value == 124 ) { print getTimeStamp("log") . " - pid $$ >> system $args excessive duration: killed after $matlab_timeout seconds\n"; - $matlab_error = -"Matlab elab excessive duration: killed after $matlab_timeout seconds"; + $matlab_error = "Matlab elab excessive duration: killed after $matlab_timeout seconds"; } else { print getTimeStamp("log") @@ -189,8 +258,7 @@ sub matlabCalc { sub trxelab { my $user = getpwuid($>); - my $ftpcmd = -"$scriptpath$FtpToCustomerCmd -m \"$matlab_timestamp\" -u $unit -t $tool >> /home/$user/log/loadcsvdata.log 2>&1"; + my $ftpcmd = "$scriptpath$FtpToCustomerCmd -m \"$matlab_timestamp\" -u $unit -t $tool >> /home/$user/log/loadcsvdata.log 2>&1"; print getTimeStamp("log") . " - pid $$ >> Fork FTP command to set GID mysql: $ftpcmd.\n"; @@ -201,14 +269,22 @@ sub trxelab { } +sub trxelabApi { + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro ELAB API: /home/battilo/scripts/inoltroViaApiElab.py $matlab_timestamp $unit $tool $inoltro_api_url $inoltro_api_bearer_token\n"; + unless ( fork() ) { + exec("/home/battilo/scripts/inoltroViaApiElab.py \"$matlab_timestamp\" \"$unit\" \"$tool\" \"$inoltro_api_url\" \"$inoltro_api_bearer_token\" >> /home/asega/log/logInoltroViaApiElab.log 2>&1"); + exit(0); + } + +} + sub getNodesType { my $dbh = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; - my $sth = $dbh->prepare( -'select t.name as name, n.seq as seq, n.num as num, n.channels as channels, y.type as type, n.ain as ain, n.din as din + my $sth = $dbh->prepare('select t.name as name, n.seq as seq, n.num as num, n.channels as channels, y.type as type, n.ain as ain, n.din as din from nodes as n inner join tools as t on t.id = n.tool_id inner join units as u on u.id = t.unit_id @@ -261,6 +337,8 @@ sub getUdbPwd { $sth->execute(); if ( $sth->rows eq 0 ) { + #$password = "laravel"; + #$username = "ase_lar"; die getTimeStamp("log") . " - pid $$ >> No password selected.\n"; } else { @@ -283,8 +361,7 @@ sub getMatlabCmd { or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; - my $sth = $dbh->prepare( -'select m.matcall, t.ftp_send , t.unit_id, s.`desc` as statustools from matfuncs as m + my $sth = $dbh->prepare('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 @@ -302,6 +379,11 @@ sub getMatlabCmd { $ftp_send = $results->{'ftp_send'}; $unit_id = $results->{'unit_id'}; $tool_status = $results->{'statustools'}; + $api_send = $results->{'api_send'}; + $inoltro_api = $results->{'inoltro_api'}; + $inoltro_api_url = $results->{'inoltro_api_url'}; + $inoltro_api_bearer_token = $results->{'inoltro_api_bearer_token'}; + $unit_duedate = $results->{'duedate'}; } } @@ -314,8 +396,8 @@ sub getMatlabCmd { sub makeEmailMsg { $email_msg = <<"END_MSG"; - - + + @@ -363,6 +445,8 @@ END_MSG sub emailSend { $email_obj = 'Matlab error on unit ' . $unit . ' - tool ' . $tool; + #print getTimeStamp("log") . " - pid $$ >> $email_msg\n"; + #print getTimeStamp("log") . " - pid $$ >> $email_obj\n"; my $msg = MIME::Lite->new( From => $from, To => $email_addr, @@ -370,17 +454,9 @@ sub emailSend { Data => $email_msg ); + #AuthUser => "alert\@aseltd.eu", #AuthPass => "Ase#2013!20\@bat", $msg->attr( "content-type" => "text/html" ); - if ( - $msg->send( - 'smtp', "smtps.aruba.it", - AuthUser => "alert\@aseltd.eu", - AuthPass => "Ase#2013!20\@bat", - Port => 465, - SSL => 1, - Debug => 0 - ) - ) + if ($msg->send('smtp', "smtp.aseltd.eu", AuthUser => "alert\@aseltd.eu", AuthPass => "Ase#2013!20\@bat", Port => 587, Debug => 0)) { print getTimeStamp("log") . " - pid $$ >> $email_obj\n"; print getTimeStamp("log") . " - pid $$ >> Mail sent to: $email_addr.\n"; @@ -393,36 +469,104 @@ sub emailSend { my $starttime = getTimeStamp("log"); print "$starttime - pid $$ >> Start execution.\n"; - GetOptions( "filename=s" => \$filename, "sqlout=s" => \$sqlout, "dbname=s" => \$db_name ) or die("Error in command line arguments\n"); + +####### EDIT FILE PER ID0013 ########## open FILE, $filename or die( "Error: opening input file " . $filename . "\n" ); +my ( $filecsvname, $path, $suffix ) = fileparse( $filename, qr/\.[^.]*/ ); +if ( $filecsvname =~ m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d.*|GD\d*)_\d*$/i ) { + my @lines = ; # Read all lines of the file into an array + close(FILE) or die "Error closing1 $filename: $!"; # Close the file after reading all lines + ( $fileDate, $fileTime ) = split( /\s/, $lines[0] ); # Assuming first line is File Creation Date + ( $unittype, $unit ) = split( /\s/, uc $lines[1] ); # Extract unit from second line + $unit =~ s/;+$//; # Clean up the unit string + if ($unit eq "ID0013") { # Process only for unit "ID0013" + my $section_count = 0; + my $keep = 0; + my @filtered_lines; + my @current_section; # Temporarily store lines of the current section + for my $line (@lines) { + # Identify the start of a new section + if ($line =~ /^File Creation Date:/) { + $section_count++; + # If previous section was marked to be kept, store it + push @filtered_lines, @current_section if $keep; + # Reset section data + @current_section = (); + $keep = 0; + } + # Always store the current section's lines in a buffer + push @current_section, $line; + # If the SD path contains "/modb/", mark this section to be kept + if ($line =~ /SD path: .*?\/modb\//) { + $keep = 1; + } + } + # Ensure the last section is processed + push @filtered_lines, @current_section if $keep; + # Only modify the file if there are 2 or more sections + if ($section_count > 1) { + print getTimeStamp("log") . " - pid $$ >> (EDIT PER ID0013) Detected multiple sections ($section_count). Keeping only /modb/ section.\n"; + # Rewrite the file with filtered content (only the relevant section) + open FILE, '>', $filename or die "Error: (EDIT PER ID0013) opening file for writing $filename: $!\n"; + print FILE @filtered_lines; + close(FILE) or die "Error closing2 $filename: $!"; + print getTimeStamp("log") . " - pid $$ >> File updated, only /modb/ section retained for ID0013.\n"; + } else { + print getTimeStamp("log") . " - pid $$ >> Only one section found, no changes made to file.\n"; + } + } else { + print getTimeStamp("log") . " - pid $$ >> Unit is not ID0013, continue normal processing.\n"; + } +} else { + close(FILE) or die "Error closing3 $filename: $!"; +} +######### NORMAL PROCESSING ########### +open FILE, $filename + or die( "Error: opening input file " . $filename . "\n" ); ( $scriptname, $scriptpath ) = fileparse($0); - if ( $db_name ne 'asega' ) { $db_name =~ s/aseu/dbn/; + #$db_name = "ase_lar"; $db_sp = $db_name; + #$db_sp = "ase_lar"; getUdbPwd(); + #die getTimeStamp("log") . " - pid $$ >> debug dbname:".$db_name."\n"; $db_lar = $db_name; + #$db_lar = "ase_lar"; } else { $db_name = 'ase_lar'; } - -my ( $filecsvname, $path, $suffix ) = fileparse( $filename, qr/\.[^.]*/ ); +( $filecsvname, $path, $suffix ) = fileparse( $filename, qr/\.[^.]*/ ); if ( $filecsvname =~ m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d.*|GD\d*)_\d*$/i ) { ( $fileDate, $fileTime ) = split( /\s/, ); ( $unittype, $unit ) = split( /\s/, uc ); $unit =~ s/;+$//; + if ($unit eq "ID0013") {#non mette dati e non fa elab se dentro i dt della id0013 c'รจ /mums/ nel path sd + my $offset_after_second_line = tell(FILE);#salva la posizione + my @linesTmp = ; + print getTimeStamp("log") . " - pid $$ >> DEBUG ID0013 - $linesTmp[3]\n"; + #my ( $unused_iptext, $unused_ip ) = split( /\s/, $linesTmp[0] ); + #my ( $unused_subnettext, $unused_subnet ) = split( /\s/, $linesTmp[1] ); + #my ( $unused_gatewaytext, $unused_gatewayip ) = split( /\s/, $linesTmp[2] ); + my ( $unused_sdtext, $unused_pathtext, $sd_path ) = split( /\s/, $linesTmp[3] ); + if($sd_path =~ /\/mums\//){ + print getTimeStamp("log") . " - pid $$ >> in path SD there is /mums/ for unit=$unit, sd_path=$sd_path EXITING the script\n"; + close FILE; + exit; # Exit the script successfully + } + seek(FILE, $offset_after_second_line, 0);#torna alla posizione dopo la seconda riga letta + } } elsif ( $filecsvname =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) { - my @strings = $filecsvname =~ -/(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; $unittype = $strings[0]; $unit = $strings[1]; $tool = $strings[2]; @@ -430,6 +574,81 @@ elsif ( $filecsvname =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) { $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; $tooltype = 'MUX'; } +elsif ( $filecsvname =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'MUX'; +} +elsif ( $filecsvname =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'TLP'; +} +elsif ( $filecsvname =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'TLP'; +} +elsif ( $filecsvname =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'GS1'; + if($unit eq "ID0273" && $tool eq "DT0001"){ + $tool = "DT0002"; + } +} +elsif ( $filecsvname =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'GS1'; + if($unit eq "ID0273" && $tool eq "DT0001"){ + $tool = "DT0002"; + } +} +elsif ( $filecsvname =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) {#per id con 1 cifra in + + my @strings = $filecsvname =~ /(.{1,4})_(.{1,7})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'GS1'; + if($unit eq "ID00279" && $tool eq "DT0008"){ + $unit = "ID0279"; + } +} +elsif ( $filecsvname =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d\d*_\d*$/i ) {#per id con 1 cifra in + + my @strings = $filecsvname =~ /(.{1,4})_(.{1,7})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'GS1'; + if($unit eq "ID00279" && $tool eq "DT0008"){ + $unit = "ID0279"; + } +} elsif ( $filecsvname =~ m/^D2W_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { my @strings = $filecsvname =~ /(.{1,3})_(.{1,6})_(.{1,6}).*/; $unittype = $strings[0]; @@ -444,6 +663,15 @@ elsif ( $filecsvname =~ m/^CR1000X_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { $tool = $strings[2]; $tooltype = 'CR1000X'; } +elsif ( $filecsvname =~ m/^Hortus_ID\d\d\d\d_DT\d\d\d\d_\d*_\d*$/i ) { + my @strings = $filecsvname =~ /(.{1,6})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $tool = $strings[2]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + $tooltype = 'CR1000X'; +} elsif ( $filecsvname =~ m/^(\d*_|)(G301_ID\d\d\d\d_DT\d\d\d\d_\d*)$/i ) { my $filecsvname_clean = substr( $filecsvname, index( $filecsvname, "G301" ) ); @@ -453,18 +681,39 @@ elsif ( $filecsvname =~ m/^(\d*_|)(G301_ID\d\d\d\d_DT\d\d\d\d_\d*)$/i ) { $tool = $strings[2]; $tooltype = 'G301'; } - +#print getTimeStamp("log") . " - pid $$ >> DEBUG SONO QUA!!!!!\n"; while ( my $line = ) { - #if ( $line =~ m/\A [[:ascii:]]* \Z/xms ) { + #print getTimeStamp("log") . " - pid $$ >> DEBUG $unittype , $tooltype\n"; + #print getTimeStamp("log") . " - pid $$ >> DEBUG !!!!!!! $line\n"; if ( $line !~ /\x00/ ) { $line =~ tr /\,/\;/ if ( $line =~ m/^\"\d\d\d\d.*/i ); #CR1000X $line =~ s/\"//g; + + #print getTimeStamp("log") . " - pid $$ >> DEBUG line: $line\n"; my ( $first, $NodeData ) = split( /;/, $line, 2 ); + #print getTimeStamp("log") . " - pid $$ >> DEBUG nodedata: $NodeData\n"; if ( defined $first and ( $first ne '' ) ) { + #print getTimeStamp("log") . " - pid $$ >> DEBUG first:" .$first ."\n"; $first =~ s/;+$//; $first =~ tr /\-/\//; + #print getTimeStamp("log") . " - pid $$ >> DEBUG first: $first\n"; + if ( ( $NodeData =~ m/^;+/ ) ) {#se bat e/o temp sono vuoti metto -1 + #print getTimeStamp("log") . " - pid $$ >> DEBUG nodedata: $NodeData\n"; + my (@batTempVuotiSplit) = split( /;/, $NodeData ); + if($batTempVuotiSplit[0] eq "" || $batTempVuotiSplit[1] eq ""){ + if($batTempVuotiSplit[0] eq ""){#bat + $batTempVuotiSplit[0] = "-1"; + } + if($batTempVuotiSplit[1] eq ""){#temp + $batTempVuotiSplit[1] = "-273"; + } + $NodeData = join(';', @batTempVuotiSplit); + #print getTimeStamp("log") . " - pid $$ >> DEBUG nodedata modificato: $NodeData\n"; + } + } if ( !defined $NodeData or ( $NodeData =~ m/^;+/ ) ) { + #print getTimeStamp("log") . " - pid $$ >> DEBUG NodeData3:" .$NodeData."\n"; my @info = ( split( /[\/,\.]/, $first ) ); if ( defined $info[3] && $info[3] =~ m/^DT\d\d\d\d$/i ) { #G801 $tool = uc $info[3]; @@ -502,6 +751,11 @@ while ( my $line = ) { print getTimeStamp("log") . " - pid $$ >> Found $tooltype tool name: $tool\n"; } + elsif($unittype eq 'Hortus' and $tooltype eq 'CR1000X'){ #Hortus CR1000X + print getTimeStamp("log") + . " - pid $$ >> Found Hortus $tooltype tool name: $tool\n"; + getNodesType(); + } } else { $NodeData =~ s/\x0d{0,1}\x0a\Z//s; @@ -514,6 +768,18 @@ while ( my $line = ) { getNodesType(); $G201_fcheck = 1; } + if ( $unittype eq 'TLP' and $TLP_fcheck eq 0 ) { + print getTimeStamp("log") + . " - pid $$ >> Found $tooltype tool name: $tool\n"; + getNodesType(); + $TLP_fcheck = 1; + } + if ( $unittype eq 'GS1' and $GS1_fcheck eq 0 ) { + print getTimeStamp("log") + . " - pid $$ >> Found $tooltype tool name: $tool\n"; + getNodesType(); + $GS1_fcheck = 1; + } if ( $unittype eq 'D2W' and $D2W_fcheck eq 0 ) { print getTimeStamp("log") . " - pid $$ >> Found $tooltype tool name: $tool\n"; @@ -532,6 +798,11 @@ while ( my $line = ) { getNodesType(); $G301_fcheck = 1; } + if($unittype eq 'Hortus' and $tooltype eq 'CR1000X'){ #Hortus CR1000X + print getTimeStamp("log") + . " - pid $$ >> Found Hortus $tooltype tool name: $tool\n"; + getNodesType(); + } if ( $tooltype eq "MUX" or $tooltype eq "D2W" @@ -586,6 +857,8 @@ while ( my $line = ) { my $used_din = 0; my $used_ain = 0; for my $i ( 0 .. $#din ) { + #print getTimeStamp("log") . " - pid $$ >> DEBUG LOC din: ". $din[$i] ." ain1:".$Ain1." ain2:".$Ain2." din1:". $Din1. " din2:". $Din2. "\n"; + #print getTimeStamp("log") . " - pid $$ >> DEBUG LOC ain: ". $ain[$i] ." ain1:".$Ain1." ain2:".$Ain2." din1:". $Din1. " din2:". $Din2. "\n"; if ( $din[$i] eq 1 ) { if ( $used_din eq 0 ) { $CSVData[ $idx++ ] = $Din1; @@ -605,10 +878,14 @@ while ( my $line = ) { } } elsif ( $din[$i] eq 2 ) { - $CSVData[ $idx++ ] = $Din1 . ";" . $Din2; + #$CSVData[ $idx++ ] = $Din1 . ";" . $Din2; + #$CSVData[ $idx++ ] = $Din1; + $CSVData[ $idx++ ] = $Din2; } elsif ( $ain[$i] eq 2 ) { - $CSVData[ $idx++ ] = $Ain1 . ";" . $Ain2; + #$CSVData[ $idx++ ] = $Ain1 . ";" . $Ain2; + #$CSVData[ $idx++ ] = $Ain1; + $CSVData[ $idx++ ] = $Ain2; } else { $CSVData[ $idx++ ] = "N/A"; @@ -630,46 +907,126 @@ while ( my $line = ) { . $h . ':' . ( $min + 1 ); } + elsif( $tooltype eq "TLP") { + @NewData = grep /\S/, split( /\||;/, $NodeData ); + if ( scalar(@NewData) != 0 ) { + my $idx = 0; + my $batTempPressione = join( ';', splice( @NewData, 0, 3 ) );#3 valori togliere il terzo e metterlo nell'ultimo nodo che dovrebbe essere sempre vuoto + my @batTempPressioneParts = split(/;/, $batTempPressione); + + $CSVData[ $idx++ ] = join( ';', @batTempPressioneParts[0,1] ); + #print "inzio\n"; + #print $idx++."\n"; + #print join( ';', @batTempPressioneParts[0,1] )."\n"; + #print "inizio for\n"; + foreach my $ch (@channels) { + $CSVData[ $idx++ ] = join( ';', splice( @NewData, 0, $ch ) ); + #print $idx++."\n"; + #print "canale: $ch\n"; + #print join( ';', splice( @NewData, 0, $ch ) )."\n"; + #print "fine giro\n"; + } + $CSVData[ $idx ] = $batTempPressioneParts[2]; + #print $batTempPressioneParts[2]; + } + } + elsif( $tooltype eq "GS1") { + @NewData = grep /\S/, split( /\||;/, $NodeData ); + if ( scalar(@NewData) != 0 ) { + my $idx = 0; + my $batTempPressione = join( ';', splice( @NewData, 0, 3 ) );#3 valori togliere il terzo e metterlo nell'ultimo nodo che dovrebbe essere sempre vuoto + my @batTempPressioneParts = split(/;/, $batTempPressione); + + $CSVData[ $idx++ ] = join( ';', @batTempPressioneParts[0,1] ); + #print "inzio\n"; + #print $idx++."\n"; + #print join( ';', @batTempPressioneParts[0,1] )."\n"; + #print "inizio for\n"; + foreach my $ch (@channels) { + $CSVData[ $idx++ ] = join( ';', splice( @NewData, 0, $ch ) ); + #print $idx++."\n"; + #print "canale: $ch\n"; + #print join( ';', splice( @NewData, 0, $ch ) )."\n"; + #print "fine giro\n"; + } + $CSVData[ $idx ] = $batTempPressioneParts[2]; + #print $batTempPressioneParts[2]; + } + } else { @CSVData = split( /\|/, $NodeData ); } my $nodenum = 0; foreach (@CSVData) { - $sql[ ( $outcount % $maxsqllines ) ] = ""; - my (@data) = grep { /\S/ } split( /\;/, $_ ); - if ( $nodenum eq 0 ) { - $toolbatt = $data[0]; - $tooltemp = $data[1]; + + #print getTimeStamp("log") . " - pid $$ >> CSVdata: ". $_ ."\n"; + if($_ ne ""){ + $sql[ ( $outcount % $maxsqllines ) ] = ""; + my (@data) = grep { /\S/ } split( /\;/, $_ ); + if ( $nodenum eq 0 ) { + #print getTimeStamp("log") . " - pid $$ >> DEBUG batt: ". $data[0] . " " . $data[1] ."\n"; + $toolbatt = $data[0]; + $tooltemp = $data[1]; + } + else { + my ( $y, $m, $d, $t ) = split( /[\s\/]/, $first ); + if ( length($y) != 4 ) + { # G201/G301 con la data invertita + my $w = $y; + $y = $d; + $m = sprintf( '%02d', $m ); + $d = sprintf( '%02d', $w ); + + } + #print getTimeStamp("log") . " - pid $$ >> DEBUG data $y-$m-$d\n"; + foreach (@data) { + if ( $sql[ ( $outcount % $maxsqllines ) ] eq "" ) { + $sql[ ( $outcount % $maxsqllines ) ] = "('$unit','$tool','$nodenum','$y-$m-$d','$t','$toolbatt','$tooltemp'"; + } + $sql[ ( $outcount % $maxsqllines ) ] .= ",'" . $_ . "'"; + } + my $InsCompl = ",NULL" x ( 15 - $#data ); + $sql[ ( $outcount % $maxsqllines ) ] .= $InsCompl . ")"; + if ( ++$outcount % $maxsqllines eq 0 ) { + $sql[ ( $outcount % $maxsqllines ) - 1 ] .= ";\n"; + my $tool_status2 = ""; + my $dbh2 = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; + my $sth2 = $dbh2->prepare( + 'select m.matcall, t.ftp_send , t.unit_id, s.`desc` as statustools 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 . '";' + ) or die getTimeStamp("log") . " - pid $$ >> $DBI::errstr"; + $sth2->execute(); + if ( $sth2->rows eq 0 ) { + die getTimeStamp("log") + . " - pid $$ >> Check tool status later - No tool's matlab function selected.\n"; + } + else { + while ( my $results2 = $sth2->fetchrow_hashref ) { + $tool_status2 = $results2->{'statustools'}; + } + } + $sth2->finish; + # Disconnect + $dbh2->disconnect; + if($tool_status2 eq "Test"){ + print getTimeStamp("log") . " - pid $$ >> tool status: $tool_status2 nothing to do.\n"; + }else{ + if(($unit eq "ID0070" && $tool eq "DT0111") || ($unit eq "ID0071" && $tool eq "DT0112") || ($unit eq "ID0072" && $tool eq "DT0113") || ($unit eq "ID0073" && $tool eq "DT0114") || ($unit eq "ID0273" && $tool eq "DT0001") || ($unit eq "ID0279" && $tool eq "DT0008")){ + modifyAndWriteOutSql($tool); + } + writeOutSql($tool); + } + } + else { + $sql[ ( $outcount % $maxsqllines ) - 1 ] .= ",\n"; + } + } + $nodenum++; } - else { - my ( $y, $m, $d, $t ) = split( /[\s\/]/, $first ); - if ( length($y) != 4 ) - { # G201/G301 con la data invertita - my $w = $y; - $y = $d; - $m = sprintf( '%02d', $m ); - $d = sprintf( '%02d', $w ); - } - foreach (@data) { - if ( $sql[ ( $outcount % $maxsqllines ) ] eq "" ) { - $sql[ ( $outcount % $maxsqllines ) ] = -"('$unit','$tool','$nodenum','$y-$m-$d','$t','$toolbatt','$tooltemp'"; - } - $sql[ ( $outcount % $maxsqllines ) ] .= - ",'" . $_ . "'"; - } - my $InsCompl = ",NULL" x ( 15 - $#data ); - $sql[ ( $outcount % $maxsqllines ) ] .= $InsCompl . ")"; - if ( ++$outcount % $maxsqllines eq 0 ) { - $sql[ ( $outcount % $maxsqllines ) - 1 ] .= ";\n"; - writeOutSql($tool); - } - else { - $sql[ ( $outcount % $maxsqllines ) - 1 ] .= ",\n"; - } - } - $nodenum++; } } } @@ -677,29 +1034,151 @@ while ( my $line = ) { } close FILE; $sql[ ( $outcount % $maxsqllines ) - 1 ] =~ s/,$/;/g; -writeOutSql($tool); +my $tool_status3 = ""; +#FTP INOLTRO RAW +my $inoltro_ftp_raw = 0; +my $ftp_send_raw = ""; +my $ftp_mode_raw = ""; +my $ftp_addrs_raw = ""; +my $ftp_user_raw = ""; +my $ftp_passwd_raw = ""; +my $ftp_filename_raw = ""; +my $ftp_target_raw = ""; +#api raw +my $inoltro_api_raw = 0; +my $inoltro_api_url_raw = ""; +my $inoltro_api_bearer_token_raw = ""; +my $api_send_raw = 0; +# +my $dbh3 = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; +my $sth3 = $dbh3->prepare( + 'select m.matcall, t.ftp_send_raw, IFNULL(u.ftp_mode_raw, "") as ftp_mode_raw, IFNULL(u.ftp_addrs_raw, "") as ftp_addrs_raw, IFNULL(u.ftp_user_raw, "") as ftp_user_raw, IFNULL(u.ftp_passwd_raw, "") as ftp_passwd_raw, IFNULL(u.ftp_filename_raw, "") as ftp_filename_raw, IFNULL(u.ftp_parm_raw, "") as ftp_parm_raw, IFNULL(u.ftp_target_raw, "") as ftp_target_raw, t.unit_id, s.`desc` as statustools, u.inoltro_ftp_raw, + u.inoltro_api_raw, IFNULL(u.inoltro_api_url_raw, "") as inoltro_api_url_raw, IFNULL(u.inoltro_api_bearer_token_raw, "") as inoltro_api_bearer_token_raw, t.api_send_raw, 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 . '";' +) or die getTimeStamp("log") . " - pid $$ >> $DBI::errstr"; +$sth3->execute(); +if ( $sth3->rows eq 0 ) { + die getTimeStamp("log") + . " - pid $$ >> Check tool status later - No tool's matlab function selected.\n"; +} +else { + while ( my $results3 = $sth3->fetchrow_hashref ) { + $tool_status3 = $results3->{'statustools'}; + $ftp_send_raw = $results3->{'ftp_send_raw'}; + $ftp_mode_raw = $results3->{'ftp_mode_raw'}; + $ftp_addrs_raw = $results3->{'ftp_addrs_raw'}; + $ftp_user_raw = $results3->{'ftp_user_raw'}; + $ftp_passwd_raw = $results3->{'ftp_passwd_raw'}; + $ftp_filename_raw = $results3->{'ftp_filename_raw'}; + $ftp_target_raw = $results3->{'ftp_target_raw'}; + $inoltro_ftp_raw = $results3->{'inoltro_ftp_raw'}; + # + $inoltro_api_raw = $results3->{'inoltro_api_raw'}; + $inoltro_api_url_raw = $results3->{'inoltro_api_url_raw'}; + $inoltro_api_bearer_token_raw = $results3->{'inoltro_api_bearer_token_raw'}; + $api_send_raw = $results3->{'api_send_raw'}; + # + $unit_duedate = $results3->{'duedate'}; + } +} +$sth3->finish; +# Disconnect +$dbh3->disconnect; +#INOLTRO RAW CSV +print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW filename: $filename\n"; +#print getTimeStamp("log") . " - pid $$ >> $ftp_send_raw $ftp_addrs_raw $ftp_user_raw $ftp_passwd_raw\n"; +if($inoltro_ftp_raw eq 1 && $ftp_send_raw eq 1 && $ftp_addrs_raw ne "" && $ftp_user_raw ne "" && $ftp_passwd_raw ne ""){ + if($ftp_target_raw eq ""){ + $ftp_target_raw = "/"; + } + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW filenameraw: $ftp_filename_raw -- $tool\n"; + if($ftp_filename_raw eq ""){ + #print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW: 1\n"; + $ftp_filename_raw = $filecsvname; + }else{ + #print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW: 2 $filecsvname\n"; + $ftp_filename_raw =~ s/\$tool/$filecsvname/g; + } + #$ftp_filename_raw = "test"; + if (!defined $unit_duedate || $unit_duedate eq '' || $unit_duedate eq '0000-00-00 00:00:00') { + # duedate is empty or "0000-00-00 00:00:00", so proceed + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW: /home/battilo/scripts/FTPCSVRAW_v2.sh $ftp_addrs_raw $ftp_target_raw $filename $ftp_filename_raw$suffix $ftp_user_raw $ftp_passwd_raw\n"; + system("sh /home/battilo/scripts/FTPCSVRAW_v2.sh $ftp_addrs_raw $ftp_target_raw $filename $ftp_filename_raw$suffix $ftp_user_raw $ftp_passwd_raw"); + } else { + my $duedateTmp1 = Time::Piece->strptime($unit_duedate, "%Y-%m-%d %H:%M:%S"); + my $now1 = localtime; + if ($duedateTmp1 >= $now1) { + # duedate is valid and not expired, so proceed + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW: /home/battilo/scripts/FTPCSVRAW_v2.sh $ftp_addrs_raw $ftp_target_raw $filename $ftp_filename_raw$suffix $ftp_user_raw $ftp_passwd_raw\n"; + system("sh /home/battilo/scripts/FTPCSVRAW_v2.sh $ftp_addrs_raw $ftp_target_raw $filename $ftp_filename_raw$suffix $ftp_user_raw $ftp_passwd_raw"); + }else{ + print getTimeStamp("log") . " - pid $$ >> centralina ($filename) scaduta! no ftp inoltro raw.\n"; + } + } +} +#INOLTRO RAW API +if($inoltro_api_raw eq 1 && $api_send_raw eq 1 && $inoltro_api_url_raw ne ""){ + if (!defined $unit_duedate || $unit_duedate eq '' || $unit_duedate eq '0000-00-00 00:00:00') { + # duedate is empty or "0000-00-00 00:00:00", so proceed + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW API: /home/battilo/scripts/inoltroViaApiRaw.py $filename $inoltro_api_url_raw $inoltro_api_bearer_token_raw\n"; + exec("/home/battilo/scripts/inoltroViaApiRaw.py \"$filename\" \"$inoltro_api_url_raw\" \"$inoltro_api_bearer_token_raw\" >> /home/asega/log/logInoltroViaApiRaw.log 2>&1"); + } else { + my $duedateTmp2 = Time::Piece->strptime($unit_duedate, "%Y-%m-%d %H:%M:%S"); + my $now2 = localtime; + if ($duedateTmp2 >= $now2) { + # duedate is valid and not expired, so proceed + print getTimeStamp("log") . " - pid $$ >> DEBUG inoltro RAW API: /home/battilo/scripts/inoltroViaApiRaw.py $filename $inoltro_api_url_raw $inoltro_api_bearer_token_raw\n"; + exec("/home/battilo/scripts/inoltroViaApiRaw.py \"$filename\" \"$inoltro_api_url_raw\" \"$inoltro_api_bearer_token_raw\" >> /home/asega/log/logInoltroViaApiRaw.log 2>&1"); + }else{ + print getTimeStamp("log") . " - pid $$ >> centralina ($filename) scaduta! no api inoltro raw.\n"; + } + } +} +# +if($tool_status3 eq "Test"){ + print getTimeStamp("log") . " - pid $$ >> tool status: $tool_status3 nothing to do.\n"; +}else{#insert in RAW table + if(($unit eq "ID0070" && $tool eq "DT0111") || ($unit eq "ID0071" && $tool eq "DT0112") || ($unit eq "ID0072" && $tool eq "DT0113") || ($unit eq "ID0073" && $tool eq "DT0114") || ($unit eq "ID0273" && $tool eq "DT0001") || ($unit eq "ID0279" && $tool eq "DT0008")){ + modifyAndWriteOutSql($tool); + } + writeOutSql($tool); +} if ( $tooltype eq "GD" ) { print getTimeStamp("log") . " - pid $$ >> tool GD: nothing to do.\n"; } else { getMatlabCmd(); - print getTimeStamp("log") - . " - pid $$ >> $unit - $tool - Status $tool_status.\n"; - if ( $tool_status eq 'Monitoring Completed' ) { - print getTimeStamp("log") - . " - pid $$ >> $unit - $tool - Monitoring completed: MatLab calc by-passed.\n"; - } - else { - + print getTimeStamp("log") . " - pid $$ >> $unit - $tool - Status $tool_status.\n"; + if ( $tool_status eq 'Active' || $tool_status eq 'Manual Upload' ) { matlabCalc(); - if ($ftp_send) { if ( $tool eq 'DT0076' ) { sleep(600); } trxelab(); } + if($inoltro_api eq 1 && $api_send eq 1){ + if (!defined $unit_duedate || $unit_duedate eq '' || $unit_duedate eq '0000-00-00 00:00:00') { + # duedate is empty or "0000-00-00 00:00:00", so proceed + trxelabApi(); + } else { + my $duedateTmp = Time::Piece->strptime($unit_duedate, "%Y-%m-%d %H:%M:%S"); + my $now = localtime; + if ($duedateTmp >= $now) { + # duedate is valid and not expired, so proceed + trxelabApi(); + }else{ + print getTimeStamp("log") . " - pid $$ >> $unit: scaduta! no api inoltro elab.\n"; + } + } + } + } + else { + print getTimeStamp("log") . " - pid $$ >> $unit - $tool - $tool_status: MatLab calc by-passed.\n"; } } diff --git a/LoadCSVData.py b/LoadCSVData.py new file mode 100644 index 0000000..e69de29 diff --git a/SendFtpElabData.pl b/SendFtpElabData.pl index 6a14eec..8a62e91 100755 --- a/SendFtpElabData.pl +++ b/SendFtpElabData.pl @@ -7,10 +7,10 @@ use Net::FTP; $|++; # Autoflush -my $username = 'ase_lar'; +my $username = 'aselar'; my $password = 'laravel'; my $db_name = 'ase_lar'; -my $server = 'localhost'; +my $server = '85.235.153.201'; my $matlab_timestamp; my $ftp_send = 1; my $ftp_addrs; @@ -21,6 +21,7 @@ my $ftp_filename = ''; my $ftp_target; my $duedate = ''; my ( $unit, $tool ); +my $dest = '/tmp/'; sub getTimeStamp { # parm [ts] => timestamp for filename; log => timestamp for log @@ -71,6 +72,7 @@ sub trxelab { # Disconnect my $fileelab; + my $filetosend; if ( !defined $ftp_filename or $ftp_filename eq "" ) { $fileelab = @@ -78,6 +80,11 @@ sub trxelab { . $tool . '_' . getTimeStamp() . '.csv'; #mettere quello che si prende da query *** aggiungere $unit + $filetosend = + '/tmp/' + . $tool . '_' + . getTimeStamp() + . '.csv'; #mettere quello che si prende da query *** aggiungere $unit } else { $ftp_filename =~ s/(\$\w+)/$1/eeg; @@ -86,6 +93,10 @@ sub trxelab { '/var/lib/mysql-files/' . $ftp_filename . '_' . getTimeStamp() . '.csv'; + $filetosend = + '/tmp/' + . $ftp_filename . '_' + . getTimeStamp() . '.csv'; } my $sthdo = $dbh->do( @@ -108,6 +119,8 @@ sub trxelab { $dbh->disconnect; + system("scp -i /home/battilo/scripts/key -P6229 alex\@" . $server . ":" . $fileelab . " /tmp"); + $ftp_parm //= ""; $ftp_parm =~ s/\s//g; @@ -154,7 +167,7 @@ sub trxelab { . " - pid $$ >> ftp target: " . $ftp->pwd() . ".\n"; - $ftp->put($fileelab) + $ftp->put($filetosend) or die getTimeStamp("log") . " - pid $$ >> Put failed: " . $ftp->message . "\n"; diff --git a/TS_PiniScript.py b/TS_PiniScript.py new file mode 100755 index 0000000..41ca2d3 --- /dev/null +++ b/TS_PiniScript.py @@ -0,0 +1,2553 @@ +#!/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" + 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 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] + 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 """ + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate]) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppie[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + 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""" + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0]]) + 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] + 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 """ + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate]) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppieMuro[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + 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""" + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0]]) + 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(",") + 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 + ORDER BY lavoro_name, EventTimestamp ASC""" + cursor.execute(sql, (progetto_id, lavoro_id, coppia_mira[0], fdate, ldate)) + 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: + 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 + ORDER BY lavoro_name, EventTimestamp ASC""" + cursor.execute(sql, (progetto_id, lavoro_id, coppia_mira[0])) + 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(",") + 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 + ORDER BY lavoro_name, EventTimestamp ASC + """ + cursor.execute(sql, (progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0], fdate, ldate)) + #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: + 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 + ORDER BY lavoro_name, EventTimestamp ASC + """ + cursor.execute(sql, (progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0])) + #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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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:#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/TS_PiniScript_old.py b/TS_PiniScript_old.py new file mode 100755 index 0000000..02d88f5 --- /dev/null +++ b/TS_PiniScript_old.py @@ -0,0 +1,2536 @@ +#!/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 "[TS_test]" in pathFile: + folder_name = "TS_test" + 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 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] + 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 """ + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate]) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppie[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + 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""" + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0]]) + 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] + 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 """ + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0], fdate, ldate]) + resultDataCoppie = cursor.fetchall() + if(len(resultDataCoppie) > 0): + arrayCoppieMuro[lavoro_name][coppia[1]][coppiaMira[1]].append(resultDataCoppie) + else: + 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""" + query += " order by lavoro_name, EventTimestamp asc" + cursor.execute(query, [progetto_id, lavoro_id, coppiaMira[0]]) + 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(",") + 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 + ORDER BY lavoro_name, EventTimestamp ASC""" + cursor.execute(sql, (progetto_id, lavoro_id, coppia_mira[0], fdate, ldate)) + 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: + 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 + ORDER BY lavoro_name, EventTimestamp ASC""" + cursor.execute(sql, (progetto_id, lavoro_id, coppia_mira[0])) + 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(",") + 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 + ORDER BY lavoro_name, EventTimestamp ASC + """ + cursor.execute(sql, (progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0], fdate, ldate)) + #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: + 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 + ORDER BY lavoro_name, EventTimestamp ASC + """ + cursor.execute(sql, (progressiva_mira[5], progetto_id, lavoro_id, progressiva_mira[0])) + #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]) + 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("index_of_higher_first_date_array: ",index_of_higher_first_date_array, "highest_value: ",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") + #qua + 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) + 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(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] + spost_long_vert_dx = ((float(zdx) - float(zdxPrev)) - (float(arrDx[0][1]) - float(arrDxPrev[0][1]))) * 1000 + spost_long_vert_sx = ((float(zsx) - float(zsxPrev)) - (float(arrSx[0][1]) - float(arrSxPrev[0][1]))) * 1000 + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_vert_dx) + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_vert_sx) + 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] + spost_long_vert_dx_penultimo = ((float(zdx) - float(zdxPrev)) - (float(arrDx[0][1]) - float(arrDxPrev[0][1]))) * 1000 + spost_long_vert_sx_penultimo = ((float(zsx) - float(zsxPrev)) - (float(arrSx[0][1]) - float(arrSxPrev[0][1]))) * 1000 + print("prev: ", str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"R", spost_long_vert_dx_penultimo) + 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_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(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]) + 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) + #print(nearestElementDxPenultimo) + #print(nearestElementSxPenultimo) + #print(nearestElementDxPrevPenultimo) + #print(nearestElementSxPrevPenultimo) + 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): + ndx = nearestElementDx[1] + ndx0 = arrDx[0][1] + ndxPrev = nearestElementDxPrev[1] + ndxPrev0 = arrDxPrev[0][1] + nsx = nearestElementSx[1] + nsx0 = arrSx[0][1] + nsxPrev = nearestElementSxPrev[1] + nsxPrev0 = arrSxPrev[0][1] + edx = nearestElementDx[5] + edx0 = arrDx[0][5] + esx = nearestElementSx[5] + esx0 = arrSx[0][5] + edxPrev = nearestElementDxPrev[5] + edxPrev0 = arrDxPrev[0][5] + esxPrev = nearestElementSxPrev[5] + esxPrev0 = arrSxPrev[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 + 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)+"R", spost_long_oriz_dx) + print(dato_date, str(keyProgressivaPrev)+" - "+str(keyProgressiva)+"L", spost_long_oriz_sx) + 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): + ndx = nearestElementDxPenultimo[1] + ndx0 = arrDx[0][1] + nsx = nearestElementSxPenultimo[1] + nsx0 = arrSx[0][1] + edx = nearestElementDxPenultimo[5] + edx0 = arrDx[0][5] + esx = nearestElementSxPenultimo[5] + esx0 = arrSx[0][5] + ndxPrev = nearestElementDxPrevPenultimo[1] + ndxPrev0 = arrDxPrev[0][1] + nsxPrev = nearestElementSxPrevPenultimo[1] + nsxPrev0 = arrSxPrev[0][1] + edxPrev = nearestElementDxPrevPenultimo[5] + edxPrev0 = arrDxPrev[0][5] + esxPrev = nearestElementSxPrevPenultimo[5] + esxPrev0 = arrSxPrev[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 + 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)+"R", spost_long_oriz_dx_penultimo) + 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_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(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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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, soglieCoppieUnitaMisura, 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:#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/UnitCsvReceiverSmart.pl b/UnitCsvReceiverSmart.pl index 7c812d4..4f3eaa0 100644 --- a/UnitCsvReceiverSmart.pl +++ b/UnitCsvReceiverSmart.pl @@ -7,10 +7,16 @@ use File::Basename qw( fileparse ); use File::Path qw( make_path ); use File::Copy qw( move ); use POSIX; +use DBI; $SIG{CHLD} = 'IGNORE'; $|++; # Autoflush +my $username = 'aselar'; +my $password = 'laravel'; +my $db_lar = 'ase_lar'; +my $server = '85.235.153.201'; + sub getTimeStamp { # parm [ts] => timestamp for filename; log => timestamp for log my $format = "%04d%02d%02d%02d%02d%02d"; @@ -29,23 +35,79 @@ sub getUnitName { # parm => file received ($trfile) my ($filename) = @_; my ( $fileDate, $fileTime ); my ( $unittype, $unit ); + my ( $ipdescgd, $ipgd ); #per gd modb + my ( $subnetdescgd, $subnetgd ); #per gd modb + my ( $gatewaydescgd, $gatewaygd ); #per gd modb + my ( $sdpathdescgd, $dfpathdescpathgd, $sdpathgd ); #per gd modb my ( $filenamecsv, $path, $suffix ) = fileparse( $filename, qr/\.[^.]*/ ); + #print getTimeStamp("log") . " >> DEBUG -> $filenamecsv\n"; if ( $path =~ m/ID\d\d\d\d\/*$/i ) { my @strings = $path =~ /.*\/(ID.{1,4})\/*$/; $unit = $strings[0]; } - + elsif( $path =~ m/TS[^\/]*\/*$/i ){#cartelle stazioni totale, per le stazioni totali la cartella deve iniziare con TS seguito da qualsiasi carattere non / + #print getTimeStamp("log") . " >> DEBUG DENTRO!\n"; + my @strings = $path =~ /.*\/(TS[^\/]*)\/*$/; + $unit = $strings[0]; + } if ( $filenamecsv =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { - my @strings = $filenamecsv =~ -/(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d\d*$/i ) {#se manca _ prima della data + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d\d*$/i ) {#se manca _ prima della data + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d\d*$/i ) {#se manca _ prima della data + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,6})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d_\d*$/i ) { + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,7})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + $unittype = $strings[0]; + $unit = $strings[1]; + $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; + $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; + } + elsif ( $filenamecsv =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d\d*$/i ) {#se manca _ prima della data + my @strings = $filenamecsv =~ /(.{1,4})_(.{1,7})_(.{1,6})(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; $unittype = $strings[0]; $unit = $strings[1]; $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; $fileTime = $strings[6] . ":" . $strings[7] . ":" . $strings[8]; } elsif ( $filenamecsv =~ m/^GFLOW_ID\d\d\d\d_DT\d\d\d\d_\d*$/i ) { - my @strings = $filenamecsv =~ -/(.{1,5})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; + my @strings = $filenamecsv =~ /(.{1,5})_(.{1,6})_(.{1,6})_(.{1,4})(.{1,2})(.{1,2})(.{1,2})(.{1,2})(.{1,2}).*/; $unittype = $strings[0]; $unit = $strings[1]; $fileDate = $strings[3] . "/" . $strings[4] . "/" . $strings[5]; @@ -75,21 +137,53 @@ sub getUnitName { # parm => file received ($trfile) $unittype = $strings[0]; $unit = $strings[1]; } + elsif( $filenamecsv =~ m/^(\d*-|)health-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i ){ # sisgeo unit + #56371-health-2022_12_01_05_31_05.csv + #56371-readings-2022_12_01_06_00_00.csv + $unittype = "SISGEO"; + } + elsif( $filenamecsv =~ m/^(\d*-|)readings-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i ){ # sisgeo unit + #56371-health-2022_12_01_05_31_05.csv + #56371-readings-2022_12_01_06_00_00.csv + $unittype = "SISGEO"; + } + elsif($filenamecsv =~ m/^MesspunktePini_/ or $filenamecsv =~ m/^Integrity Monitor /){ #stazione totale mire + $unittype = "STAZIONETOTALE"; + } + elsif($filenamecsv =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d$/i ){#sorotec pini + $unittype = "SOROTECPINI"; + } + elsif($filenamecsv =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i ){#sorotec pini + $unittype = "SOROTECPINI"; + } + elsif($filenamecsv =~ m/^HIRPINIA/){#hirpinia + $unittype = "HIRPINIA"; + } + elsif ( $filenamecsv =~ m/^\d\d\d\d\d\d\d_\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d_\d.log$/i ) {#vulink pini + $unittype = "VULINK"; + } else { open FILE, $filename or warn getTimeStamp("log") . " >> Error: opening input file $filename\n"; ( $fileDate, $fileTime ) = split( /\s/, ); ( $unittype, $unit ) = split( /\s/, uc ); + if($filenamecsv =~ m/^GD\d\d\d\d$/i){ #per gd modb + ( $ipdescgd, $ipgd ) = split( /\s/, ); + ( $subnetdescgd, $subnetgd ) = split( /\s/, ); + ( $gatewaydescgd, $gatewaygd ) = split( /\s/, ); + ( $sdpathdescgd, $dfpathdescpathgd, $sdpathgd ) = split( /\s/, ); + #print getTimeStamp("log"). " >> DEBUG unittype: $unittype unit: $unit SD path: $sdpathgd\n"; + } $unit =~ s/;+$//; close FILE; } - return ( $unit, $unittype ); + return ( $unit, $unittype, $sdpathgd ); } my $readingFile; my $recvOKstr = "OK UPLOAD"; -my @ext = ( ".csv", ".txt" ); +my @ext = ( ".csv", ".txt", ".ods" ); GetOptions( "file=s" => \$readingFile ) or die("Error in command line arguments\n"); @@ -102,32 +196,132 @@ $tail->WatchFile( -file => $readingFile, -type => "UNIX", -timeout => '10' ); while ( my $line = $tail->GetLine() ) { if ( index( $line, $recvOKstr ) != -1 ) { my ( - undef, undef, undef, $truser, undef, - $trip, undef, $trfile, $trstat - ) = split( /[\"\[\]]/, $line ); + undef, undef, undef, $truser, undef, + $trip, undef, $trfile, $trstat + ) = split( /[\"\[\]]/, $line ); + + if(index($line, "Integrity Monitor [") != -1){#se รจ stazione di pini + #print getTimeStamp("log") . " >> DEBUG line $line\n"; + #my @sssa = split( /[\"\[\]]/, $line); + #foreach my $value (@sssa) { + # print "$value\n"; + #} + my ( + undef, undef, undef, $trusertmp, undef, undef, + $triptmp, $trfileuno, $trfiledue, $trfiletre, $trstattmp + ) = split( /[\"\[\]]/, $line ); + $trfile = $trfileuno."[".$trfiledue."]".$trfiletre;#per pini ts + $truser = $trusertmp; + $trip = $triptmp; + $trstat = $trstattmp; + #print("######\n"); + #print($trfile."\n"); + #print("---\n"); + #print($truser."\n"); + #print("---\n"); + #print($trip."\n"); + #print("---\n"); + #print($trstat."\n"); + #print("---\n"); + } + + #print getTimeStamp("log") . " >> DEBUG line $line\n"; my ( $login, $pass, $uid, $gid ) = getpwnam($truser) or warn getTimeStamp("log") . " >> $truser not in passwd file.\n"; + my $dbh = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; + my $sth = $dbh->prepare("SELECT stop_elab FROM admin_panel LIMIT 1"); + $sth->execute(); + my $stop_elab; + if (my $row = $sth->fetchrow_hashref) { + $stop_elab = $row->{'stop_elab'}; + } else { + $stop_elab = 0; + } + print getTimeStamp("log") . " >> stop_elab value -> $stop_elab.\n"; + $sth->finish; + if ($stop_elab == 0) { + my $sth2 = $dbh->prepare("SELECT id, command, truser FROM elaborazioni_stoppate WHERE eseguito = 0"); + $sth2->execute(); + my $sth3 = $dbh->prepare("UPDATE elaborazioni_stoppate SET eseguito = 1 WHERE eseguito = 0"); + $sth3->execute(); + $sth3->finish; + while (my $row2 = $sth2->fetchrow_hashref) { + my $id = $row2->{'id'}; + my $command = $row2->{'command'}; + my $truser2 = $row2->{'truser'}; + my ( $login2, $pass2, $uid2, $gid2 ) = getpwnam($truser2) + or warn getTimeStamp("log") . " >> $truser2 not in passwd file.\n"; + print getTimeStamp("log") . " >> DEBUG exec command -> $command.\n"; + my $pid = fork(); + unless ($pid) { + setgid($gid2); + setuid($uid2); + $ENV{"HOME"} = 'home/' . $truser2; + exec($command) or die "Failed to exec command for id $id: $!"; + exit(0); + } + waitpid($pid, 0); + } + $sth2->finish; + } + $dbh->disconnect; + + #print getTimeStamp("log") . " >> DEBUG $trfile \n"; my ( $filename, $path, $suffix ) = fileparse( $trfile, qr/\.[^.]*/ ); + #print getTimeStamp("log") . " >> DEBUG $filename --- $path --- $suffix \n"; $path = "/home/" . $truser . "/"; $trfile = "/home/" . $truser . $trfile; if ( ( grep( /^$suffix$/i, @ext ) ) - and ( $filename =~ - m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d\d\d\d|GD\d\d\d\d)$/i + and ( $filename =~ m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d\d\d\d|GD\d\d\d\d)$/i or $filename =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d\d*$/i or $filename =~ m/^D2W_ID\d\d\d\d_DT\d\d\d\d$/i or $filename =~ m/^CR1000X_ID\d\d\d\d_DT\d\d\d\d$/i + or $filename =~ m/^Hortus_ID\d\d\d\d_DT\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i or $filename =~ m/^(\d*_|)G301_ID\d\d\d\d_DT\d\d\d\d$/i or $filename =~ m/^GFLOW_ID\d\d\d\d_DT\d\d\d\d_\d*$/i or $filename =~ m/^measurements_\d\d_\d\d_\d\d\d\d__\d\d_\d\d$/i - or $filename =~ m/^\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i ) + or $filename =~ m/^\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i + or $filename =~ m/^(\d*-|)health-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i + or $filename =~ m/^(\d*-|)readings-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i + or $filename =~ m/^MesspunktePini_/ + or $filename =~ m/^Integrity Monitor/ + or $filename =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d$/i + or $filename =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i + or $filename =~ m/^HIRPINIA/ + or $filename =~ m/^\d\d\d\d\d\d\d_\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d_\d.log$/i ) ) { - my ( $unit, $unittype ) = getUnitName($trfile); - print getTimeStamp("log") . " >> Unit $unit - Filename $trfile\n"; + if($filename =~ m/Hortus_ID\d\d\d\d_DT\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d/){#mancano i ; nelle prime 6 righe, aggiungo ; alla fine delle prime 6 righe dell'header + open my $hortus_file, '+<', $trfile; + my @hortus_file_lines = <$hortus_file>; + $hortus_file_lines[0] =~ tr /\r/\n/; + my @line_splitted = split(/\n/, $hortus_file_lines[0]); + for(my $i_var_for=0; $i_var_for < 6; $i_var_for++){ + unless($line_splitted[$i_var_for] =~ m';'){ + $line_splitted[$i_var_for] = $line_splitted[$i_var_for].';'; + } + } + $hortus_file_lines[0] = join("\n", @line_splitted); + + seek($hortus_file, 0, 0); + print $hortus_file @hortus_file_lines; + truncate($hortus_file, tell($hortus_file)); + close $hortus_file; + #print getTimeStamp("log") . " >> DEBUG Filename $trfile, $hortus_file_lines[0]\n"; + } + my ( $unit, $unittype, $sdpathgd ) = getUnitName($trfile); + #print getTimeStamp("log") . " >> Unit $unit - Filename $trfile\n"; if ( !-d "$path/log" ) { make_path "$path/log", @@ -137,6 +331,9 @@ while ( my $line = $tail->GetLine() ) { } my $outpath = $path . $unit; + if ($trfile =~ /home.*home/ && $trfile !~ /Integrity Monitor/) { + $outpath = $path . "home/".$unit; + } if ( !-d "$outpath/SQL" ) { make_path "$outpath/SQL", { mode => 0755, owner => $truser, group => $gid } @@ -152,25 +349,39 @@ while ( my $line = $tail->GetLine() ) { } else { print getTimeStamp("log") . " >> Moved $trfile -> $dest.\n"; - chmod 0664, $dest; + chmod 0666, $dest; my @fname = ($dest); chown $uid, $gid, @fname; if ( ( - $filename =~ - m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d.*|GD\d*)$/i + $filename =~ m/^(\d\d_\d\d\d\d_|)(DT\d\d\d\d|LOC\d.*|GD\d*)$/i or $filename =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^G201_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^TLP_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d_DT\d\d\d\d\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d_\d*$/i + or $filename =~ m/^GS1_ID\d\d\d\d\d_DT\d\d\d\d\d*$/i or $filename =~ m/^D2W_ID\d\d\d\d_DT\d\d\d\d$/i or $filename =~ m/^CR1000X_ID\d\d\d\d_DT\d\d\d\d$/i + or $filename =~ m/^Hortus_ID\d\d\d\d_DT\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i or $filename =~ m/^(\d*_|)G301_ID\d\d\d\d_DT\d\d\d\d$/i or $filename =~ m/^GFLOW_ID\d\d\d\d_DT\d\d\d\d_\d*$/i - or $filename =~ - m/^measurements_\d\d_\d\d_\d\d\d\d__\d\d_\d\d$/i - or $filename =~ - m/^\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i + or $filename =~ m/^measurements_\d\d_\d\d_\d\d\d\d__\d\d_\d\d$/i + or $filename =~ m/^\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i + or $filename =~ m/^(\d*-|)health-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i + or $filename =~ m/^(\d*-|)readings-\d\d\d\d_\d\d_\d\d_\d\d_\d\d_\d\d$/i + or $filename =~ m/^MesspunktePini_/ + or $filename =~ m/^Integrity Monitor / + or $filename =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d$/i + or $filename =~ m/^CO_\d\d\d\d_\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d$/i + or $filename =~ m/^HIRPINIA/ + or $filename =~ m/^\d\d\d\d\d\d\d_\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d_\d.log$/i ) and ( $unit ne 'ID9999' ) and ( $truser ne 'corra' ) + #and ( $unit ne 'ID0008' ) ) { print getTimeStamp("log") @@ -193,15 +404,129 @@ while ( my $line = $tail->GetLine() ) { ); } + elsif ( $unittype eq 'SISGEO' ) { + exec( $scriptpath . "sisgeoLoadScript.py \"$dest\" >> /home/$truser/log/loadsisgeo.log 2>&1"); + } + elsif ($unittype eq 'STAZIONETOTALE'){ + #print getTimeStamp("log") . " >> DEBUG file STAZIONETOTALE\n"; + exec( $scriptpath . "TS_PiniScript.py \"$dest\" >> /home/$truser/log/loadTS.log 2>&1"); + } + elsif ( defined $sdpathgd and ($sdpathgd =~ m'/modb/GD' or $sdpathgd =~ m'/dsas/GD') ){ + #print getTimeStamp("log") . " >> DEBUG file GD e modb\n"; + exec( $scriptpath."loadCSVModbGDLora.py \"$dest\" >> /home/$truser/log/loadgdmodblora.log 2>&1"); + } + elsif( $unittype eq 'SOROTECPINI' ){ + exec( $scriptpath . "sorotecPini.py \"$dest\" >> /home/$truser/log/loadSorotecPini.log 2>&1"); + } + elsif($unittype eq 'HIRPINIA'){ + exec( $scriptpath . "hirpiniaLoadScript.py \"$dest\" >> /home/$truser/log/loadHirpinia.log 2>&1"); + } + elsif($unittype eq 'VULINK'){ + exec( $scriptpath . "vulinkScript.py \"$dest\" >> /home/$truser/log/loadVulink.log 2>&1"); + } else { - exec( $scriptpath - . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" - . "_" - . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" - ); + if (defined $stop_elab) { + if ($stop_elab == 1) { + print getTimeStamp("log") . " >> DEBUG 1 stop_elab 1\n"; + #exec( $scriptpath + # . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + # . "_" + # . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + #); + my $dbh2 = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; + my $insert_sth = $dbh2->prepare("INSERT IGNORE INTO elaborazioni_stoppate (type, command, truser) VALUES (0,?,?)"); + my $string_to_insert = $scriptpath. "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename". "_". "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1"; + print getTimeStamp("log") . " >> DEBUG 1 $string_to_insert\n"; + $insert_sth->execute($string_to_insert, $truser); + $insert_sth->finish; + $dbh2->disconnect; + } elsif ($stop_elab == 0) { + print getTimeStamp("log") . " >> DEBUG 1 stop_elab 0\n"; + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } else { + print getTimeStamp("log") . " >> DEBUG 1 else\n"; + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } + } else { + print getTimeStamp("log") . " >> DEBUG 1 pre-else\n"; + #print getTimeStamp("log") . " >> DEBUG $dest\n";#debug + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } } exit(0); } + if ( ( $truser ne 'asega' ) and ( $truser ne 'corra' ) ) { + print getTimeStamp("log") + . " >> Sender user $truser: duplicate as asega user -> load data into DB.\n"; + my $realtruser = $truser; + $truser = "asega"; + $outpath =~ s/$realtruser/$truser/; + my ( $login, $pass, $uid, $gid ) = getpwnam($truser) + or warn getTimeStamp("log") + . " >> $truser not in passwd file.\n"; + unless ( fork() ) { + setgid($gid); + setuid($uid); + $ENV{"HOME"} = 'home/' . $truser; + if ( defined $sdpathgd and ($sdpathgd =~ m'/modb/GD' or $sdpathgd =~ m'/dsas/GD') ){ + #print getTimeStamp("log") . " >> DEBUG file GD e modb duplica\n";#debug + } + else { + if (defined $stop_elab) { + if ($stop_elab == 1) { + print getTimeStamp("log") . " >> DEBUG 2 stop_elab 1\n"; + #exec( $scriptpath + # . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + # . "_" + # . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + #); + my $dbh2 = DBI->connect( "DBI:mysql:$db_lar;host=$server", $username, $password ) or die getTimeStamp("log") . " - pid $$ >> Could not connect to database: $DBI::errstr"; + my $insert_sth = $dbh2->prepare("INSERT IGNORE INTO elaborazioni_stoppate (type, command, truser) VALUES (0,?,?)"); + my $string_to_insert = $scriptpath. "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename". "_". "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1"; + print getTimeStamp("log") . " >> DEBUG 2 $string_to_insert\n"; + $insert_sth->execute($string_to_insert, $truser); + $insert_sth->finish; + $dbh2->disconnect; + } elsif ($stop_elab == 0) { + print getTimeStamp("log") . " >> DEBUG 2 stop_elab 0\n"; + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } else { + print getTimeStamp("log") . " >> DEBUG 2 else\n"; + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } + } else { + print getTimeStamp("log") . " >> DEBUG 2 pre-else\n"; + #print getTimeStamp("log") . " >> DEBUG $dest\n";#debug + exec( $scriptpath + . "LoadCSVData.pl -f \"$dest\" -s \"$outpath/SQL/$filename" + . "_" + . "$timestamp.sql\" -d $truser >> /home/$truser/log/loadcsvdata.log 2>&1" + ); + } + } + exit(0); + } + } } } } diff --git a/dbconfig.py b/dbconfig.py new file mode 100755 index 0000000..7415831 --- /dev/null +++ b/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/gflowScript.py b/gflowScript.py new file mode 100755 index 0000000..ada6a94 --- /dev/null +++ b/gflowScript.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config + +def insertData(dati): + if dati != "null": + query = "INSERT INTO ELABDATAGFLOW(unit_name, tool_name, EventDateTime, xacc, yacc, zacc, cacc, battery_level, wifi_signal) " \ + "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)" + + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.executemany(query, dati) + + conn.commit() + except Error as e: + print('Error:', e) + + finally: + os.system("cd /usr/local/matlab_func/; ./run_RSN_lnx.sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+"") + cursor.close() + conn.close() + +def getDataFromFile(pathFile): + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + header = data[0].split(",") + unitName = header[0] + if unitName.startswith('ID'): + toolName = header[1] + batteryLevel = header[2].replace("V","") + wifiSignal = header[3].replace("dBm","") + data.pop(0) + dati = [] + for row in data: + row = row.split(",") + if row[5] != "0.00": + row[0] = row[0].replace("/","-",2).split("-") + dateTime = row[0][2] + "-" + row[0][1] + "-" + row[0][0] + " " + row[1] + dati.append((unitName,toolName,dateTime,row[2],row[3],row[4],row[5],batteryLevel,wifiSignal)) + + return dati + else: + return "null" + +def main(): + insertData(getDataFromFile(sys.argv[1])) + +if __name__ == '__main__': + main() diff --git a/hirpiniaLoadScript.py b/hirpiniaLoadScript.py new file mode 100755 index 0000000..87e37e4 --- /dev/null +++ b/hirpiniaLoadScript.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config +from decimal import Decimal +from datetime import datetime +import ezodf + +def getDataFromCsv(pathFile): + try: + folder_path, file_with_extension = os.path.split(pathFile) + unit_name = os.path.basename(folder_path)#unitname + tool_name, _ = os.path.splitext(file_with_extension)#toolname + tool_name = tool_name.replace("HIRPINIA_", "") + tool_name = tool_name.split("_")[0] + print(unit_name, tool_name) + datiRaw = [] + doc = ezodf.opendoc(pathFile) + for sheet in doc.sheets: + node_num = sheet.name.replace("S-", "") + print(f"Sheet Name: {sheet.name}") + rows_to_skip = 2 + for i, row in enumerate(sheet.rows()): + if i < rows_to_skip: + continue + row_data = [cell.value for cell in row] + date_time = datetime.strptime(row_data[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S").split(" ") + date = date_time[0] + time = date_time[1] + val0 = row_data[2] + val1 = row_data[4] + val2 = row_data[6] + val3 = row_data[8] + datiRaw.append((unit_name, tool_name, node_num, date, time, -1, -273, val0, val1, val2, val3)) + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor(dictionary=True) + queryRaw = "insert ignore into RAWDATACOR(UnitName,ToolNameID,NodeNum,EventDate,EventTime,BatLevel,Temperature,Val0,Val1,Val2,Val3) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.executemany(queryRaw, datiRaw) + conn.commit() + except Error as e: + print('Error:', e) + finally: + queryMatlab = "select m.matcall from tools as t join units as u on u.id=t.unit_id join matfuncs as m on m.id=t.matfunc where u.name=%s and t.name=%s" + cursor.execute(queryMatlab, [unit_name, tool_name]) + resultMatlab = cursor.fetchall() + if(resultMatlab): + print("Avvio "+str(resultMatlab[0]["matcall"])) + os.system("cd /usr/local/matlab_func/; ./run_"+str(resultMatlab[0]["matcall"])+".sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+str(unit_name)+" "+str(tool_name)+"") + cursor.close() + conn.close() + except Exception as e: + print(f"An unexpected error occurred: {str(e)}\n") + +def main(): + print("Avviato.") + getDataFromCsv(sys.argv[1]) + print("Finito.") + +if __name__ == '__main__': + main() diff --git a/inoltroViaApiElab.py b/inoltroViaApiElab.py new file mode 100644 index 0000000..6e43845 --- /dev/null +++ b/inoltroViaApiElab.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +from decimal import Decimal +import sys +import json +import requests +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config + +def send_elab_data_as_json(matlab_timestamp, unit, tool, api_url, bearer_token): + """Function to fetch elaborated data from MySQL and send it as a JSON string via API""" + try: + # Connect to MySQL database + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor(dictionary=True) + # Query to select elaborated data + query = """SELECT UnitName, ToolNameID, EventTimestamp, NodeNum, NodeType, NodeDepth, + XShift, YShift, ZShift, X, Y, Z, HShift, HShiftDir, HShift_local, + speed, speed_local, acceleration, acceleration_local, + T_node, water_level, pressure, load_value, AlfaX, AlfaY, Area, calcerr + FROM elabdataview + WHERE UnitName = %s AND ToolNameID = %s AND updated_at > %s + ORDER BY ToolNameID DESC, EventTimestamp, CONVERT(NodeNum, UNSIGNED INTEGER) DESC""" + + # Execute query + cursor.execute(query, (unit, tool, matlab_timestamp)) + resultData = cursor.fetchall() + + # Close cursor and connection + cursor.close() + conn.close() + + # Convert Decimal objects to float in resultData + for row in resultData: + for key, value in row.items(): + if isinstance(value, Decimal): + row[key] = format(float(value), '.6f') # Convert Decimal to float with full precision + #print(resultData) + + payload = { + 'json': json.dumps(resultData) # Convert result to JSON string + } + print(payload) + #with open("payload.json", "w") as file: + # json.dump(payload, file, indent=4) + + headers = { + 'Content-Type': 'application/json' + } + + # Add Authorization header if the bearer token is provided + if bearer_token: + headers['Authorization'] = f'Bearer {bearer_token}' + else: + print("No Bearer token provided. Authorization header will be omitted.") + + # Send the JSON data via POST request + response = requests.post(api_url, headers=headers, json=payload) + response.raise_for_status() # Raise an error for bad responses (4xx or 5xx) + + # Log the response + print(f"Elab Data Response: {response.status_code} - {response.text}") + except Exception as e: + print(f"Error occurred while sending elab data as JSON: {e}") + +def main(): + if len(sys.argv) != 6: + print("Usage: python3 inoltroViaApiElab.py ") + sys.exit(1) + matlab_timestamp = sys.argv[1] + unit = sys.argv[2] + tool = sys.argv[3] + api_url = sys.argv[4] + bearer_token = sys.argv[5] + send_elab_data_as_json(matlab_timestamp, unit, tool, api_url, bearer_token) + +if __name__ == "__main__": + main() diff --git a/inoltroViaApiRaw.py b/inoltroViaApiRaw.py new file mode 100644 index 0000000..6a81f4a --- /dev/null +++ b/inoltroViaApiRaw.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import sys +import json +import requests + +def send_raw_csv_as_json(filename, api_url, bearer_token): + # Function to send raw CSV data as a JSON string + try: + # Read the CSV file and prepare it as a JSON string + with open(filename, 'r') as file: + csv_data = file.read() # Reading the CSV content as a string + + payload = { + 'json': csv_data # The key `json` with the CSV content as a string + } + print(payload) + + headers = { + 'Content-Type': 'application/json' # The API expects JSON payload + } + + # Add the Authorization header if the bearer token is not empty + if bearer_token: + headers['Authorization'] = f'Bearer {bearer_token}' + else: + print("No Bearer token provided. Authorization header will be omitted.") + + # Send the JSON data via POST request + response = requests.post(api_url, headers=headers, json=payload) + response.raise_for_status() # Raise an error for bad responses (4xx or 5xx) + + # Log the response + print(f"Raw Data Response: {response.status_code} - {response.text}") + except Exception as e: + print(f"Error occurred while sending raw file as JSON: {e}") + +def main(): + if len(sys.argv) != 4: + print("Usage: python3 inoltroViaApiRaw.py ") + sys.exit(1) + filename = sys.argv[1] + api_url = sys.argv[2] + bearer_token = sys.argv[3] + send_raw_csv_as_json(filename, api_url, bearer_token) + +if __name__ == "__main__": + main() diff --git a/loadCSVModbGDLora.py b/loadCSVModbGDLora.py new file mode 100755 index 0000000..08fb2a7 --- /dev/null +++ b/loadCSVModbGDLora.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +import sys +import os +from datetime import datetime +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config + +def insertData(dati): + print("DATI:") + print(dati) + if dati != "null" and dati is not None: + print(dati[0][1]) + print(dati[0][0]) + matlab_func = "" + conn_via_radio = 0 + operation_mode = 0 + queryMatFunc = "select m.matcall, t.conn_via_radio, t.operation_mode 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 = '"+dati[0][1]+"' and u.name = '"+dati[0][0]+"'" + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.execute(queryMatFunc) + + result = cursor.fetchall() + matlab_func = result[0][0] + conn_via_radio = result[0][1] + operation_mode = result[0][2] + except Error as e: + print('Error:', e) + + if conn_via_radio == 1: + if operation_mode == 1:#listening mode(no rssi 'al momento') + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, BatLevelModule, TemperatureModule, Val0, RssiModule) " \ + "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor = conn.cursor() + cursor.executemany(query, dati) + + conn.commit() + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> Inserito in RAWDATACOR "+dati[0][0]+" "+dati[0][1]) + + except Error as e: + print('Error:', e) + + finally: + if matlab_func != "": + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> Avvio "+matlab_func) + os.system("cd /usr/local/matlab_func/; ./run_"+matlab_func+".sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+" >> /home/asega/log/loadgdmodblora.log 2>&1") + else:#standard no val0 con rssi + try: + for drow in dati: + unit_name = drow[0] + tool_name = drow[1] + date = drow[3] + time = drow[4] + batM = drow[7] + tempM = drow[8] + rssiM = drow[10].replace("dB", "") + + query = "UPDATE RAWDATACOR SET BatLevelModule=%s, TemperatureModule=%s, RssiModule=%s where UnitName=%s and ToolNameID=%s and EventDate=%s and EventTime=%s" + + cursor = conn.cursor() + cursor.execute(query, [batM, tempM, rssiM, unit_name, tool_name, date, time]) + conn.commit() + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> Aggiornato in RAWDATACOR "+dati[0][0]+" "+dati[0][1]) + except Error as e: + print('Error:', e) + finally: + if matlab_func != "": + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> Avvio "+matlab_func) + os.system("cd /usr/local/matlab_func/; ./run_"+matlab_func+".sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+" >> /home/asega/log/loadgdmodblora.log 2>&1") + cursor.close() + conn.close() + print("-------") + +def getDataFromFile(pathFile): + print(pathFile) + path = pathFile.split("/") + unitname = path[len(path) - 2] + toolname = path[len(path) - 1].split("_")[0] + if(toolname.startswith("GD") and unitname): + dati = [] + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> apro "+pathFile) + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + if("/modb/" in data[5] or "/dsas/" in data[5]): #gd e modb (lora) + #print("modb") + pathFile = pathFile.replace("GD", "DT") + print(pathFile) + pathFileName = pathFile.split("_")[0] + pathFileDate = int(pathFile.split("_")[1].split(".")[0]) + pathFileExt = pathFile.split("_")[1].split(".")[1] + for xsec in range(1, 60): + if os.path.isfile(pathFile): + #print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> file DT trovato") + #print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> apro "+pathFile) + with open(pathFile, 'r') as fileDT: + dataDT = fileDT.readlines() + dataDT = [rowDT.rstrip() for rowDT in dataDT] + dataDT = dataDT[7:] + nodenum = 2 + toolname = toolname.replace("GD", "DT") + data = data[7:] + for index, row in enumerate(data): + #print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> index " + str(index)) + #print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> row " + row) + try: + lineDT = dataDT[index].split(";") + if(lineDT[1] == '' or lineDT[1] == '-.-'): + tempindex = index + for ind in range(len(data)): + tempindex-=1 + if(tempindex >= 0): + lineDT[1] = dataDT[tempindex].split(";")[1] + else: + lineDT[1] = 12.0 + if(lineDT[1] != '' and lineDT[1] != '-.-'): + break + print(lineDT[1]) + if(lineDT[2] == '' or lineDT[2] == '-.-'): + tempindex = index + for ind in range(len(data)): + tempindex-=1 + if(tempindex >= 0): + lineDT[2] = dataDT[tempindex].split(";")[2] + else: + lineDT[2] = 20.0 + if(lineDT[2] != '' and lineDT[2] != '-.-'): + break + batUnit = float(lineDT[1]) + tempUnit = float(lineDT[2]) + line = row.split(";") + if(line[2] == '' and line[3] == ''):#se bat e temp sono vuoti + continue + dt = lineDT[0].split(" ") + if("/" in dt[0]): + try: + date = str(datetime.strptime(dt[0], "%d/%m/%Y").strftime("%Y-%m-%d")) + #print("The string is a date with format " + "%d/%m/%Y") + except ValueError: + print() + #print("The string IS NOT a date with format " + "%d/%m/%Y")#debug + try: + date = str(datetime.strptime(dt[0], "%Y/%m/%d").strftime("%Y-%m-%d")) + #print("The string is a date with format " + "%Y/%m/%d") + except ValueError: + print() + #print("The string IS NOT a date with format " + "%Y/%m/%d")#debug + else: + date = dt[0] + time = dt[1] + batlevel = float(line[2]) + temp = float(line[3]) + if len(line) == 6: + if line[4] == "|": + val0 = line[5] + dati.append((unitname, toolname, nodenum, date, time, batUnit, tempUnit, batlevel, temp, val0, None)) + elif len(line) == 5: + rssi = line[4] + dati.append((unitname, toolname, nodenum, date, time, batUnit, tempUnit, batlevel, temp, None, rssi)) + except IndexError: + print("exception: different lenght break") + break + #print("The string IS NOT a date with format " + "%d/%m/%Y")#debug + return dati + pathFileDate -= 1 + pathFile = pathFileName + "_" + str(pathFileDate)+ "." + pathFileExt + print(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+"-> CHECK "+pathFile) + +def main(): + insertData(getDataFromFile(sys.argv[1])) + +if __name__ == '__main__': + main() diff --git a/nesaScript.py b/nesaScript.py new file mode 100755 index 0000000..95deaef --- /dev/null +++ b/nesaScript.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config + +def insertData(dati): + #print(dati) + if dati != "null": + query = "INSERT INTO ELABDATANESA(UnitName, ToolNameID, NodeNum, EventTimestamp, dataJSON) " \ + "VALUES(%s,%s,%s,%s,%s)" + + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.executemany(query, dati) + + conn.commit() + except Error as e: + print('Error:', e) + + finally: + os.system("cd /usr/local/matlab_func/; ./run_Tilt_lnx.sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+"") + cursor.close() + conn.close() + +def getDataFromCsv(pathFile): + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + #data.pop(0) #rimuove header + dati = [] + i = 0 + unit = "" + tool = "" + for row in data: + row = row.split(",") + if i == 0: + serial_number = row[1] + if serial_number[0] == "0": + serial_number = serial_number[1:] #rimuove primo char (se 0) del id nesa + query = "SELECT unit_name, tool_name FROM nesa_tools WHERE serial_number='"+serial_number+"'" + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.execute(query) + + result = cursor.fetchall() + except Error as e: + print('Error:', e) + unit = result[0][0] + tool = result[0][1] + #print(result[0][0]) + #print(result[0][1]) + date = row[7]+"-"+row[6]+"-"+row[5]+" "+row[2]+":"+row[3]+":"+row[4] + nodeNum = 1 + dataJSON = '{ "battery":"'+row[58]+'", "solarPanel":"'+row[61]+'", "tempAvg":"'+row[10]+'", "tempMin":"'+row[13]+'", "tempMax":"'+row[16]+'"}' + dati.append((unit, tool, nodeNum, date, dataJSON)) + nodeNum = 2 + dataJSON = '{ "battery":"'+row[58]+'", "solarPanel":"'+row[61]+'", "humAvg":"'+row[19]+'", "humMin":"'+row[22]+'", "humMax":"'+row[25]+'"}' + dati.append((unit, tool, nodeNum, date, dataJSON)) + nodeNum = 3 + dataJSON = '{ "battery":"'+row[58]+'", "solarPanel":"'+row[61]+'", "windDirAvg":"'+row[28]+'", "windDirMin":"'+row[31]+'", "windDirMax":"'+row[34]+'", "windSpeedAvg":"'+row[37]+'", "windSpeedMin":"'+row[40]+'", "windSpeedMax":"'+row[43]+'"}' + dati.append((unit, tool, nodeNum, date, dataJSON)) + nodeNum = 4 + dataJSON = '{ "battery":"'+row[58]+'", "solarPanel":"'+row[61]+'", "rain":"'+row[46]+'"}' + dati.append((unit, tool, nodeNum, date, dataJSON)) + nodeNum = 5 + dataJSON = '{ "battery":"'+row[58]+'", "solarPanel":"'+row[61]+'", "pressureAvg":"'+row[49]+'", "pressureMin":"'+row[52]+'", "pressureMax":"'+row[55]+'"}' + dati.append((unit, tool, nodeNum, date, dataJSON)) + i+=1 + + return dati + +def main(): + insertData(getDataFromCsv(sys.argv[1])) + +if __name__ == '__main__': + main() diff --git a/nesaScript_new.py b/nesaScript_new.py new file mode 100755 index 0000000..7bd8da1 --- /dev/null +++ b/nesaScript_new.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config +from collections import defaultdict + +def insertData(dati): + print("dati: ",dati) + if dati != "null" and dati is not None: + query = "INSERT IGNORE INTO ELABDATANESA(UnitName, ToolNameID, NodeNum, EventTimestamp, dataJSON) " \ + "VALUES(%s,%s,%s,%s,%s)" + + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.executemany(query, dati) + + conn.commit() + except Error as e: + print('Error:', e) + + finally: + os.system("cd /usr/local/matlab_func/; ./run_Tilt_lnx.sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+"") + cursor.close() + conn.close() + +def getDataFromCsv(pathFile): + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor(dictionary=True) + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + #data.pop(0) #rimuove header + dati = [] + i = 0 + unit = "" + tool = "" + #query = "SELECT tool_id, nodetype_id, nt.type as nodetype_name, num FROM nodes as n join nodetypes as nt on nt.id=n.nodetype_id join tools as t on t.id=n.tool_id join units as u on u.id=t.unit_id where u.name=%s and t.name=%s" + #cursor.execute(query, [unit, tool]) + #resultNodi = cursor.fetchall() + #resultNodi_dict = {item['nodetype_id']: item for item in resultNodi} + #print(resultNodi_dict) + for row in data: + row = row.split(",") + #print(row) + #print("-------") + if i == 0: + serial_number = row[1] + if serial_number[0] == "0": + serial_number = serial_number[1:] #rimuove primo char (se 0) del id nesa + query = "SELECT unit_name, tool_name FROM nesa_tools WHERE serial_number='"+serial_number+"'" + cursor.execute(query) + result = cursor.fetchall() + if(len(result) > 0): + unit = result[0]["unit_name"] + tool = result[0]["tool_name"] + query = "SELECT tool_id, nodetype_id, nt.type as nodetype_name, num FROM nodes as n join nodetypes as nt on nt.id=n.nodetype_id join tools as t on t.id=n.tool_id join units as u on u.id=t.unit_id where u.name=%s and t.name=%s" + cursor.execute(query, [unit, tool]) + resultNodi = cursor.fetchall() + resultNodi_dict = {item['nodetype_id']: item for item in resultNodi} + #print(result[0][0]) + #print(result[0][1]) + if(unit != "" and tool != ""): + date = row[7]+"-"+row[6]+"-"+row[5]+" "+row[2]+":"+row[3]+":"+row[4] + row = row[:-1] + chunks = [row[i:i+3] for i in range(8, len(row), 3)]# Start from index 8 and split into chunks of 3 + battery = -1 + solarPanel = -1 + grouped = defaultdict(list) + for chunk in chunks: + key = chunk[0] # First value as the key + grouped[key].append(chunk[1:]) # Store the rest of the values + #print(grouped) + if("108" in grouped): + battery = grouped["108"][0][1] + if("158" in grouped): + solarPanel = grouped["158"][0][1] + if("1" in grouped): + nodetype_id_to_find = 4 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + tempAvg = 0 + tempMin = 0 + tempMax = 0 + for item in grouped["1"]: + key, value = item + if key == '2': + tempAvg = value + elif key == '3': + tempMin = value + elif key == '4': + tempMax = value + #print("therm: ", tempAvg, tempMin, tempMax, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "tempAvg":"'+tempAvg+'", "tempMin":"'+tempMin+'", "tempMax":"'+tempMax+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + if("2" in grouped): + nodetype_id_to_find = 35 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + humidityAvg = 0 + humidityMin = 0 + humidityMax = 0 + for item in grouped["2"]: + key, value = item + if key == '2': + humidityAvg = value + elif key == '3': + humidityMin = value + elif key == '4': + humidityMax = value + #print("humidity: ", humidityAvg, humidityMin, humidityMax, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "humAvg":"'+humidityAvg+'", "humMin":"'+humidityMin+'", "humMax":"'+humidityMax+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + if("3" in grouped): + nodetype_id_to_find = 69 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + pyraAvg = 0 + pyraMin = 0 + pyraMax = 0 + for item in grouped["3"]: + key, value = item + if key == '2': + pyraAvg = value + elif key == '3': + pyraMin = value + elif key == '4': + pyraMax = value + #print("pyra: ", pyroAvg, pyroMin, pyroMax, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "pyraAvg":"'+pyraAvg+'", "pyraMin":"'+pyraMin+'", "pyraMax":"'+pyraMax+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + if("4" in grouped): + nodetype_id_to_find = 55 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + windDirAvg = 0 + windDirMin = 0 + windDirMax = 0 + windSpeedAvg = 0 + windSpeedMin = 0 + windSpeedMax = 0 + for item in grouped["4"]: + key, value = item + if key == '2': + windDirAvg = value + elif key == '9': + windDirMin = value + elif key == '8': + windDirMax = value + for item in grouped["9"]: + key, value = item + if key == '2': + windSpeedAvg = value + elif key == '3': + windSpeedMin = value + elif key == '4': + windSpeedMax = value + #print("windDir: ", windDirAvg, windDirMin, windDirMax, "-windSpeed: ", windSpeedAvg, windSpeedMin, windSpeedMax, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "windDirAvg":"'+windDirAvg+'", "windDirMin":"'+windDirMin+'", "windDirMax":"'+windDirMax+'", "windSpeedAvg":"'+windSpeedAvg+'", "windSpeedMin":"'+windSpeedMin+'", "windSpeedMax":"'+windSpeedMax+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + if("10" in grouped): + nodetype_id_to_find = 27 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + rain = 0 + for item in grouped["10"]: + key, value = item + rain = value + #print("rain: ", rain, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "rain":"'+rain+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + if("2013" in grouped): + nodetype_id_to_find = 3 + res = resultNodi_dict.get(nodetype_id_to_find) # Returns None if not found + if(res is not None): + node_num = res["num"] + pressureAvg = 0 + pressureMin = 0 + pressureMax = 0 + for item in grouped["2013"]: + key, value = item + if key == '2': + pressureAvg = value + elif key == '3': + pressureMin = value + elif key == '4': + pressureMax = value + #print("pressure: ", pressureAvg, pressureMin, pressureMax, " nodenum: ", node_num) + dataJSON = '{ "battery":"'+battery+'", "solarPanel":"'+solarPanel+'", "pressureAvg":"'+pressureAvg+'", "pressureMin":"'+pressureMin+'", "pressureMax":"'+pressureMax+'"}' + dati.append((unit, tool, node_num, date, dataJSON)) + else: + break + i+=1 + print(dati) + return dati + except Error as e: + print("Error: ", e) + +def main(): + insertData(getDataFromCsv(sys.argv[1])) + +if __name__ == '__main__': + main() diff --git a/run_ATD_lnx.sh b/run_ATD_lnx.sh new file mode 100755 index 0000000..0cfafb1 --- /dev/null +++ b/run_ATD_lnx.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname "$0"` +#echo "------------------------------------------" +if [ "x$1" = "x" ]; then + echo Usage: + echo $0 \ args +else +# echo Setting up environment variables + MCRROOT="$1" +# echo --- + LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/opengl/lib/glnxa64; + export LD_LIBRARY_PATH; +# echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH}; + shift 1 + args= + out= + while [ $# -gt 0 ]; do + token=$1 + args="${args} \"${token}\"" + out="${out}${token}" + shift + done + out="${out}_output_error.txt" + #eval "\"${exe_dir}/ATD_lnx\"" $args > /dev/null 2>&1 + eval "\"${exe_dir}/ATD_lnx\"" $args > /tmp/${out} 2>&1 +fi +exit + diff --git a/run_Musa_lnx.sh b/run_Musa_lnx.sh new file mode 100755 index 0000000..122a316 --- /dev/null +++ b/run_Musa_lnx.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname "$0"` +#echo "------------------------------------------" +if [ "x$1" = "x" ]; then + echo Usage: + echo $0 \ args +else +# echo Setting up environment variables + MCRROOT="$1" +# echo --- + LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/opengl/lib/glnxa64; + export LD_LIBRARY_PATH; +# echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH}; + shift 1 + args= + out= + while [ $# -gt 0 ]; do + token=$1 + args="${args} \"${token}\"" + out="${out}${token}" + shift + done + out="${out}_output_error.txt" + #eval "\"${exe_dir}/MUSA_lnx\"" $args > /dev/null 2>&1 + eval "\"${exe_dir}/MUSA_lnx\"" $args > /tmp/${out} 2>&1 +fi +exit + diff --git a/run_RSN_lnx.sh b/run_RSN_lnx.sh new file mode 100755 index 0000000..30c978b --- /dev/null +++ b/run_RSN_lnx.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname "$0"` +#echo "------------------------------------------" +if [ "x$1" = "x" ]; then + echo Usage: + echo $0 \ args +else +# echo Setting up environment variables + MCRROOT="$1" +# echo --- + LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/opengl/lib/glnxa64; + export LD_LIBRARY_PATH; +# echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH}; + shift 1 + args= + out= + while [ $# -gt 0 ]; do + token=$1 + args="${args} \"${token}\"" + out="${out}${token}" + shift + done + out="${out}_output_error.txt" + #eval "\"${exe_dir}/RSN_lnx\"" $args > /dev/null 2>&1 + eval "\"${exe_dir}/RSN_lnx\"" $args > /tmp/${out} 2>&1 +fi +exit + diff --git a/run_Tilt_lnx.sh b/run_Tilt_lnx.sh new file mode 100755 index 0000000..a8414e0 --- /dev/null +++ b/run_Tilt_lnx.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname "$0"` +#echo "------------------------------------------" +if [ "x$1" = "x" ]; then + echo Usage: + echo $0 \ args +else +# echo Setting up environment variables + MCRROOT="$1" +# echo --- + LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64; + LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/opengl/lib/glnxa64; + export LD_LIBRARY_PATH; +# echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH}; + shift 1 + args= + out= + while [ $# -gt 0 ]; do + token=$1 + args="${args} \"${token}\"" + out="${out}${token}" + shift + done + out="${out}_output_error.txt" + #eval "\"${exe_dir}/Tilt_lnx\"" $args > /dev/null 2>&1 + eval "\"${exe_dir}/Tilt_lnx\"" $args > /tmp/${out} 2>&1 +fi +exit + diff --git a/scp_aseweb_aruba.sh b/scp_aseweb_aruba.sh new file mode 100755 index 0000000..dfe79d7 --- /dev/null +++ b/scp_aseweb_aruba.sh @@ -0,0 +1,6 @@ +#!/bin/sh +echo 'Started at:' `date` +cd /var/www/www2.aseltd.eu +find sites/ase/ -type f \( ! -iname defines.php -and ! -iname UserManager.php \) -mtime -1 -exec ls -la {} \; +find sites/ase/ -type f \( ! -iname defines.php -and ! -iname UserManager.php \) -mtime -1 -exec scp {} alex@80.211.60.65:/var/www/aseltd.eu/{} \; +echo 'Ended at: ' `date` diff --git a/sisgeoLoadScript.py b/sisgeoLoadScript.py new file mode 100755 index 0000000..14735e0 --- /dev/null +++ b/sisgeoLoadScript.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config +from decimal import Decimal +from datetime import datetime + +def insertData(dati): + #print(dati) + #print(len(dati)) + if(len(dati) > 0): + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor() + if(len(dati) == 2): + u = "" + t = "" + rawdata = dati[0] + elabdata = dati[1] + if(len(rawdata) > 0): + for r in rawdata: + #print(r) + #print(len(r)) + if(len(r) == 6):#nodo1 + unitname = r[0] + toolname = r[1] + nodenum = r[2] + pressure = Decimal(r[3])*100 + date = r[4] + time = r[5] + query = "SELECT * from RAWDATACOR WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [unitname, toolname, nodenum]) + result = cursor.fetchall() + if(result): + if(result[0][8] is None): + datetimeOld = datetime.strptime(str(result[0][4]) + " " + str(result[0][5]), "%Y-%m-%d %H:%M:%S") + datetimeNew = datetime.strptime(str(date) + " " + str(time), "%Y-%m-%d %H:%M:%S") + dateDiff = datetimeNew - datetimeOld + if(dateDiff.total_seconds() / 3600 >= 5): + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, val0, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, pressure, -1, -273]) + conn.commit() + except Error as e: + print('Error:', e) + else: + query = "UPDATE RAWDATACOR SET val0=%s, EventDate=%s, EventTime=%s WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s AND val0 is NULL ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [pressure, date, time, unitname, toolname, nodenum]) + conn.commit() + except Error as e: + print('Error:', e) + elif(result[0][8] is not None): + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, val0, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, pressure, -1, -273]) + conn.commit() + except Error as e: + print('Error:', e) + else: + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, val0, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, pressure, -1, -273]) + conn.commit() + except Error as e: + print('Error:', e) + except Error as e: + print('Error:', e) + else:#altri 2->5 + unitname = r[0] + toolname = r[1] + nodenum = r[2] + freqinhz = r[3] + therminohms = r[4] + freqindigit = r[5] + date = r[6] + time = r[7] + query = "SELECT * from RAWDATACOR WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [unitname, toolname, nodenum]) + result = cursor.fetchall() + if(result): + if(result[0][8] is None): + query = "UPDATE RAWDATACOR SET val0=%s, val1=%s, val2=%s, EventDate=%s, EventTime=%s WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s AND val0 is NULL ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [freqinhz, therminohms, freqindigit, date, time, unitname, toolname, nodenum]) + conn.commit() + except Error as e: + print('Error:', e) + elif(result[0][8] is not None): + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, val0, val1, val2, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, freqinhz, therminohms, freqindigit, -1, -273]) + conn.commit() + except Error as e: + print('Error:', e) + else: + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, val0, val1, val2, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, freqinhz, therminohms, freqindigit, -1, -273]) + conn.commit() + except Error as e: + print('Error:', e) + except Error as e: + print('Error:', e) + + if(len(elabdata) > 0): + for e in elabdata: + #print(e) + #print(len(e)) + if(len(e) == 6):#nodo1 + unitname = e[0] + toolname = e[1] + nodenum = e[2] + pressure = Decimal(e[3])*100 + date = e[4] + time = e[5] + try: + query = "INSERT INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, pressure) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [unitname, toolname, nodenum, date, time, pressure]) + conn.commit() + except Error as e: + print('Error:', e) + else:#altri 2->5 + unitname = e[0] + toolname = e[1] + u = unitname + t = toolname + nodenum = e[2] + pch = e[3] + tch = e[4] + date = e[5] + time = e[6] + try: + query = "INSERT INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift, T_node) VALUES(%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(query, [unitname, toolname, nodenum, date, time, pch, tch]) + conn.commit() + except Error as e: + print('Error:', e) + #os.system("cd /usr/local/matlab_func/; ./run_ATD_lnx.sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+u+" "+t+"") + else: + for r in dati: + #print(r) + unitname = r[0] + toolname = r[1] + nodenum = r[2] + date = r[3] + time = r[4] + battery = r[5] + temperature = r[6] + query = "SELECT * from RAWDATACOR WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [unitname, toolname, nodenum]) + result = cursor.fetchall() + if(result): + if(result[0][25] is None or result[0][25] == -1.00): + datetimeOld = datetime.strptime(str(result[0][4]) + " " + str(result[0][5]), "%Y-%m-%d %H:%M:%S") + datetimeNew = datetime.strptime(str(date) + " " + str(time), "%Y-%m-%d %H:%M:%S") + dateDiff = datetimeNew - datetimeOld + #print(dateDiff.total_seconds() / 3600) + if(dateDiff.total_seconds() / 3600 >= 5): + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, battery, temperature]) + conn.commit() + except Error as e: + print('Error:', e) + else: + query = "UPDATE RAWDATACOR SET BatLevelModule=%s, TemperatureModule=%s WHERE UnitName=%s AND ToolNameID=%s AND NodeNum=%s AND (BatLevelModule is NULL or BatLevelModule = -1.00) ORDER BY EventDate desc,EventTime desc limit 1" + try: + cursor.execute(query, [battery, temperature, unitname, toolname, nodenum]) + conn.commit() + except Error as e: + print('Error:', e) + elif(result[0][25] is not None and result[0][25] != -1.00): + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, battery, temperature]) + conn.commit() + except Error as e: + print('Error:', e) + else: + query = "INSERT INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, BatLevelModule, TemperatureModule) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)" + try: + cursor.execute(query, [unitname, toolname, nodenum, date, time, -1, -273, battery, temperature]) + conn.commit() + except Error as e: + print('Error:', e) + except Error as e: + print('Error:', e) + cursor.close() + conn.close() + +def getDataFromCsv(pathFile): + with open(pathFile, 'r') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + serial_number = data[0].split(",")[1] + data = data[10:] #rimuove righe header + dati = [] + rawDatiReadings = []#tmp + elabDatiReadings = []#tmp + datiReadings = [] + i = 0 + unit = "" + tool = "" + #row = data[0]#quando non c'era il for solo 1 riga + for row in data:#se ci sono righe multiple + row = row.split(",") + if i == 0: + query = "SELECT unit_name, tool_name FROM sisgeo_tools WHERE serial_number='"+serial_number+"'" + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor() + cursor.execute(query) + result = cursor.fetchall() + except Error as e: + print('Error:', e) + unit = result[0][0] + tool = result[0][1] + #print(result[0][0]) + #print(result[0][1]) + if("health" in pathFile): + datetime = str(row[0]).replace("\"", "").split(" ") + date = datetime[0] + time = datetime[1] + battery = row[1] + temperature = row[2] + dati.append((unit, tool, 1, date, time, battery, temperature)) + dati.append((unit, tool, 2, date, time, battery, temperature)) + dati.append((unit, tool, 3, date, time, battery, temperature)) + dati.append((unit, tool, 4, date, time, battery, temperature)) + dati.append((unit, tool, 5, date, time, battery, temperature)) + else: + datetime = str(row[0]).replace("\"", "").split(" ") + date = datetime[0] + time = datetime[1] + atmpressure = row[1]#nodo1 + #raw + freqinhzch1 = row[2]#nodo2 + freqindigitch1 = row[3]#nodo2 + thermResInOhmsch1 = row[4]#nodo2 + freqinhzch2 = row[5]#nodo3 + freqindigitch2 = row[6]#nodo3 + thermResInOhmsch2 = row[7]#nodo3 + freqinhzch3 = row[8]#nodo4 + freqindigitch3 = row[9]#nodo4 + thermResInOhmsch3 = row[10]#nodo4 + freqinhzch4 = row[11]#nodo5 + freqindigitch4 = row[12]#nodo5 + thermResInOhmsch4 = row[13]#nodo5 + #elab + pch1 = row[18]#nodo2 + tch1 = row[19]#nodo2 + pch2 = row[20]#nodo3 + tch2 = row[21]#nodo3 + pch3 = row[22]#nodo4 + tch3 = row[23]#nodo4 + pch4 = row[24]#nodo5 + tch4 = row[25]#nodo5 + + rawDatiReadings.append((unit, tool, 1, atmpressure, date, time)) + rawDatiReadings.append((unit, tool, 2, freqinhzch1, thermResInOhmsch1, freqindigitch1, date, time)) + rawDatiReadings.append((unit, tool, 3, freqinhzch2, thermResInOhmsch2, freqindigitch2, date, time)) + rawDatiReadings.append((unit, tool, 4, freqinhzch3, thermResInOhmsch3, freqindigitch3, date, time)) + rawDatiReadings.append((unit, tool, 5, freqinhzch4, thermResInOhmsch4, freqindigitch4, date, time)) + + elabDatiReadings.append((unit, tool, 1, atmpressure, date, time)) + elabDatiReadings.append((unit, tool, 2, pch1, tch1, date, time)) + elabDatiReadings.append((unit, tool, 3, pch2, tch2, date, time)) + elabDatiReadings.append((unit, tool, 4, pch3, tch3, date, time)) + elabDatiReadings.append((unit, tool, 5, pch4, tch4, date, time)) + + #[ram],[elab]#quando c'era solo 1 riga + #dati = [ + # [ + # (unit, tool, 1, atmpressure, date, time), + # (unit, tool, 2, freqinhzch1, thermResInOhmsch1, freqindigitch1, date, time), + # (unit, tool, 3, freqinhzch2, thermResInOhmsch2, freqindigitch2, date, time), + # (unit, tool, 4, freqinhzch3, thermResInOhmsch3, freqindigitch3, date, time), + # (unit, tool, 5, freqinhzch4, thermResInOhmsch4, freqindigitch4, date, time), + # ], [ + # (unit, tool, 1, atmpressure, date, time), + # (unit, tool, 2, pch1, tch1, date, time), + # (unit, tool, 3, pch2, tch2, date, time), + # (unit, tool, 4, pch3, tch3, date, time), + # (unit, tool, 5, pch4, tch4, date, time), + # ] + # ] + i+=1 + #print(dati) + if(len(rawDatiReadings) > 0 or len(elabDatiReadings) > 0): + datiReadings = [rawDatiReadings, elabDatiReadings] + if(len(datiReadings) > 0): + return datiReadings + return dati + +def main(): + insertData(getDataFromCsv(sys.argv[1])) + +if __name__ == '__main__': + main() diff --git a/sorotecPini.py b/sorotecPini.py new file mode 100755 index 0000000..b46e9dc --- /dev/null +++ b/sorotecPini.py @@ -0,0 +1,306 @@ +#!/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 + +def removeDuplicates(lst): + return list(set([i for i in lst])) + +def getDataFromCsvAndInsert(pathFile): + try: + print(pathFile) + folder_name = pathFile.split("/")[-2]#cartella + 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): + if(folder_name == "ID0247"): + unit_name = "ID0247" + tool_name = "DT0001" + data.pop(0) #rimuove header + data.pop(0) + data.pop(0) + data.pop(0) + data = [element for element in data if element != ""] + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor() + queryElab = "insert ignore into ELABDATADISP(UnitName,ToolNameID,NodeNum,EventDate,EventTime,load_value) values (%s,%s,%s,%s,%s,%s)" + queryRaw = "insert ignore into RAWDATACOR(UnitName,ToolNameID,NodeNum,EventDate,EventTime,BatLevel,Temperature,Val0) values (%s,%s,%s,%s,%s,%s,%s,%s)" + if("_1_" in pathFile): + print("File tipo 1.\n") + #print(unit_name, tool_name) + dataToInsertElab = [] + dataToInsertRaw = [] + for row in data: + rowSplitted = row.replace("\"","").split(";") + eventTimestamp = rowSplitted[0].split(" ") + date = eventTimestamp[0].split("-") + date = date[2]+"-"+date[1]+"-"+date[0] + time = eventTimestamp[1] + an3 = rowSplitted[1] + an4 = rowSplitted[2]#V unit battery + OUTREG2 = rowSplitted[3] + E8_181_CH2 = rowSplitted[4]#2 + E8_181_CH3 = rowSplitted[5]#3 + E8_181_CH4 = rowSplitted[6]#4 + E8_181_CH5 = rowSplitted[7]#5 + E8_181_CH6 = rowSplitted[8]#6 + E8_181_CH7 = rowSplitted[9]#7 + E8_181_CH8 = rowSplitted[10]#8 + E8_182_CH1 = rowSplitted[11]#9 + E8_182_CH2 = rowSplitted[12]#10 + E8_182_CH3 = rowSplitted[13]#11 + E8_182_CH4 = rowSplitted[14]#12 + E8_182_CH5 = rowSplitted[15]#13 + E8_182_CH6 = rowSplitted[16]#14 + E8_182_CH7 = rowSplitted[17]#15 + E8_182_CH8 = rowSplitted[18]#16 + E8_183_CH1 = rowSplitted[19]#17 + E8_183_CH2 = rowSplitted[20]#18 + E8_183_CH3 = rowSplitted[21]#19 + E8_183_CH4 = rowSplitted[22]#20 + E8_183_CH5 = rowSplitted[23]#21 + E8_183_CH6 = rowSplitted[24]#22 + E8_183_CH7 = rowSplitted[25]#23 + E8_183_CH8 = rowSplitted[26]#24 + E8_184_CH1 = rowSplitted[27]#25 + E8_184_CH2 = rowSplitted[28]#26 + E8_184_CH3 = rowSplitted[29]#27 mv/V + E8_184_CH4 = rowSplitted[30]#28 mv/V + E8_184_CH5 = rowSplitted[31]#29 mv/V + E8_184_CH6 = rowSplitted[32]#30 mv/V + E8_184_CH7 = rowSplitted[33]#31 mv/V + E8_184_CH8 = rowSplitted[34]#32 mv/V + E8_181_CH1 = rowSplitted[35]#1 + an1 = rowSplitted[36] + an2 = rowSplitted[37] + #print(unit_name, tool_name, 1, E8_181_CH1) + #print(unit_name, tool_name, 2, E8_181_CH2) + #print(unit_name, tool_name, 3, E8_181_CH3) + #print(unit_name, tool_name, 4, E8_181_CH4) + #print(unit_name, tool_name, 5, E8_181_CH5) + #print(unit_name, tool_name, 6, E8_181_CH6) + #print(unit_name, tool_name, 7, E8_181_CH7) + #print(unit_name, tool_name, 8, E8_181_CH8) + #print(unit_name, tool_name, 9, E8_182_CH1) + #print(unit_name, tool_name, 10, E8_182_CH2) + #print(unit_name, tool_name, 11, E8_182_CH3) + #print(unit_name, tool_name, 12, E8_182_CH4) + #print(unit_name, tool_name, 13, E8_182_CH5) + #print(unit_name, tool_name, 14, E8_182_CH6) + #print(unit_name, tool_name, 15, E8_182_CH7) + #print(unit_name, tool_name, 16, E8_182_CH8) + #print(unit_name, tool_name, 17, E8_183_CH1) + #print(unit_name, tool_name, 18, E8_183_CH2) + #print(unit_name, tool_name, 19, E8_183_CH3) + #print(unit_name, tool_name, 20, E8_183_CH4) + #print(unit_name, tool_name, 21, E8_183_CH5) + #print(unit_name, tool_name, 22, E8_183_CH6) + #print(unit_name, tool_name, 23, E8_183_CH7) + #print(unit_name, tool_name, 24, E8_183_CH8) + #print(unit_name, tool_name, 25, E8_184_CH1) + #print(unit_name, tool_name, 26, E8_184_CH2) + #print(unit_name, tool_name, 27, E8_184_CH3) + #print(unit_name, tool_name, 28, E8_184_CH4) + #print(unit_name, tool_name, 29, E8_184_CH5) + #print(unit_name, tool_name, 30, E8_184_CH6) + #print(unit_name, tool_name, 31, E8_184_CH7) + #print(unit_name, tool_name, 32, E8_184_CH8) + #--------------------------------------------------------------------------------------- + dataToInsertRaw.append((unit_name, tool_name, 1, date, time, an4, -273, E8_181_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 2, date, time, an4, -273, E8_181_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 3, date, time, an4, -273, E8_181_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 4, date, time, an4, -273, E8_181_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 5, date, time, an4, -273, E8_181_CH5)) + dataToInsertRaw.append((unit_name, tool_name, 6, date, time, an4, -273, E8_181_CH6)) + dataToInsertRaw.append((unit_name, tool_name, 7, date, time, an4, -273, E8_181_CH7)) + dataToInsertRaw.append((unit_name, tool_name, 8, date, time, an4, -273, E8_181_CH8)) + dataToInsertRaw.append((unit_name, tool_name, 9, date, time, an4, -273, E8_182_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 10, date, time, an4, -273, E8_182_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 11, date, time, an4, -273, E8_182_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 12, date, time, an4, -273, E8_182_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 13, date, time, an4, -273, E8_182_CH5)) + dataToInsertRaw.append((unit_name, tool_name, 14, date, time, an4, -273, E8_182_CH6)) + dataToInsertRaw.append((unit_name, tool_name, 15, date, time, an4, -273, E8_182_CH7)) + dataToInsertRaw.append((unit_name, tool_name, 16, date, time, an4, -273, E8_182_CH8)) + dataToInsertRaw.append((unit_name, tool_name, 17, date, time, an4, -273, E8_183_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 18, date, time, an4, -273, E8_183_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 19, date, time, an4, -273, E8_183_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 20, date, time, an4, -273, E8_183_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 21, date, time, an4, -273, E8_183_CH5)) + dataToInsertRaw.append((unit_name, tool_name, 22, date, time, an4, -273, E8_183_CH6)) + dataToInsertRaw.append((unit_name, tool_name, 23, date, time, an4, -273, E8_183_CH7)) + dataToInsertRaw.append((unit_name, tool_name, 24, date, time, an4, -273, E8_183_CH8)) + dataToInsertRaw.append((unit_name, tool_name, 25, date, time, an4, -273, E8_184_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 26, date, time, an4, -273, E8_184_CH2)) + #--------------------------------------------------------------------------------------- + dataToInsertElab.append((unit_name, tool_name, 1, date, time, E8_181_CH1)) + dataToInsertElab.append((unit_name, tool_name, 2, date, time, E8_181_CH2)) + dataToInsertElab.append((unit_name, tool_name, 3, date, time, E8_181_CH3)) + dataToInsertElab.append((unit_name, tool_name, 4, date, time, E8_181_CH4)) + dataToInsertElab.append((unit_name, tool_name, 5, date, time, E8_181_CH5)) + dataToInsertElab.append((unit_name, tool_name, 6, date, time, E8_181_CH6)) + dataToInsertElab.append((unit_name, tool_name, 7, date, time, E8_181_CH7)) + dataToInsertElab.append((unit_name, tool_name, 8, date, time, E8_181_CH8)) + dataToInsertElab.append((unit_name, tool_name, 9, date, time, E8_182_CH1)) + dataToInsertElab.append((unit_name, tool_name, 10, date, time, E8_182_CH2)) + dataToInsertElab.append((unit_name, tool_name, 11, date, time, E8_182_CH3)) + dataToInsertElab.append((unit_name, tool_name, 12, date, time, E8_182_CH4)) + dataToInsertElab.append((unit_name, tool_name, 13, date, time, E8_182_CH5)) + dataToInsertElab.append((unit_name, tool_name, 14, date, time, E8_182_CH6)) + dataToInsertElab.append((unit_name, tool_name, 15, date, time, E8_182_CH7)) + dataToInsertElab.append((unit_name, tool_name, 16, date, time, E8_182_CH8)) + dataToInsertElab.append((unit_name, tool_name, 17, date, time, E8_183_CH1)) + dataToInsertElab.append((unit_name, tool_name, 18, date, time, E8_183_CH2)) + dataToInsertElab.append((unit_name, tool_name, 19, date, time, E8_183_CH3)) + dataToInsertElab.append((unit_name, tool_name, 20, date, time, E8_183_CH4)) + dataToInsertElab.append((unit_name, tool_name, 21, date, time, E8_183_CH5)) + dataToInsertElab.append((unit_name, tool_name, 22, date, time, E8_183_CH6)) + dataToInsertElab.append((unit_name, tool_name, 23, date, time, E8_183_CH7)) + dataToInsertElab.append((unit_name, tool_name, 24, date, time, E8_183_CH8)) + dataToInsertElab.append((unit_name, tool_name, 25, date, time, E8_184_CH1)) + dataToInsertElab.append((unit_name, tool_name, 26, date, time, E8_184_CH2)) + #--------------------------------------------------------------------------------------- + cursor.executemany(queryElab, dataToInsertElab) + cursor.executemany(queryRaw, dataToInsertRaw) + conn.commit() + #print(dataToInsertElab) + #print(dataToInsertRaw) + elif("_2_" in pathFile): + print("File tipo 2.\n") + #print(unit_name, tool_name) + dataToInsertElab = [] + dataToInsertRaw = [] + for row in data: + rowSplitted = row.replace("\"","").split(";") + eventTimestamp = rowSplitted[0].split(" ") + date = eventTimestamp[0].split("-") + date = date[2]+"-"+date[1]+"-"+date[0] + time = eventTimestamp[1] + an2 = rowSplitted[1] + an3 = rowSplitted[2] + an1 = rowSplitted[3] + OUTREG2 = rowSplitted[4] + E8_181_CH1 = rowSplitted[5]#33 mv/V + E8_181_CH2 = rowSplitted[6]#34 mv/V + E8_181_CH3 = rowSplitted[7]#35 mv/V + E8_181_CH4 = rowSplitted[8]#36 mv/V + E8_181_CH5 = rowSplitted[9]#37 mv/V + E8_181_CH6 = rowSplitted[10]#38 mv/V + E8_181_CH7 = rowSplitted[11]#39 mv/V + E8_181_CH8 = rowSplitted[12]#40 mv/V + E8_182_CH1 = rowSplitted[13]#41 + E8_182_CH2 = rowSplitted[14]#42 + E8_182_CH3 = rowSplitted[15]#43 + E8_182_CH4 = rowSplitted[16]#44 + E8_182_CH5 = rowSplitted[17]#45 mv/V + E8_182_CH6 = rowSplitted[18]#46 mv/V + E8_182_CH7 = rowSplitted[19]#47 mv/V + E8_182_CH8 = rowSplitted[20]#48 mv/V + E8_183_CH1 = rowSplitted[21]#49 + E8_183_CH2 = rowSplitted[22]#50 + E8_183_CH3 = rowSplitted[23]#51 + E8_183_CH4 = rowSplitted[24]#52 + E8_183_CH5 = rowSplitted[25]#53 mv/V + E8_183_CH6 = rowSplitted[26]#54 mv/V + E8_183_CH7 = rowSplitted[27]#55 mv/V + E8_183_CH8 = rowSplitted[28]#56 + E8_184_CH1 = rowSplitted[29]#57 + E8_184_CH2 = rowSplitted[30]#58 + E8_184_CH3 = rowSplitted[31]#59 + E8_184_CH4 = rowSplitted[32]#60 + E8_184_CH5 = rowSplitted[33]#61 + E8_184_CH6 = rowSplitted[34]#62 + E8_184_CH7 = rowSplitted[35]#63 mv/V + E8_184_CH8 = rowSplitted[36]#64 mv/V + an4 = rowSplitted[37]#V unit battery + #print(unit_name, tool_name, 33, E8_181_CH1) + #print(unit_name, tool_name, 34, E8_181_CH2) + #print(unit_name, tool_name, 35, E8_181_CH3) + #print(unit_name, tool_name, 36, E8_181_CH4) + #print(unit_name, tool_name, 37, E8_181_CH5) + #print(unit_name, tool_name, 38, E8_181_CH6) + #print(unit_name, tool_name, 39, E8_181_CH7) + #print(unit_name, tool_name, 40, E8_181_CH8) + #print(unit_name, tool_name, 41, E8_182_CH1) + #print(unit_name, tool_name, 42, E8_182_CH2) + #print(unit_name, tool_name, 43, E8_182_CH3) + #print(unit_name, tool_name, 44, E8_182_CH4) + #print(unit_name, tool_name, 45, E8_182_CH5) + #print(unit_name, tool_name, 46, E8_182_CH6) + #print(unit_name, tool_name, 47, E8_182_CH7) + #print(unit_name, tool_name, 48, E8_182_CH8) + #print(unit_name, tool_name, 49, E8_183_CH1) + #print(unit_name, tool_name, 50, E8_183_CH2) + #print(unit_name, tool_name, 51, E8_183_CH3) + #print(unit_name, tool_name, 52, E8_183_CH4) + #print(unit_name, tool_name, 53, E8_183_CH5) + #print(unit_name, tool_name, 54, E8_183_CH6) + #print(unit_name, tool_name, 55, E8_183_CH7) + #print(unit_name, tool_name, 56, E8_183_CH8) + #print(unit_name, tool_name, 57, E8_184_CH1) + #print(unit_name, tool_name, 58, E8_184_CH2) + #print(unit_name, tool_name, 59, E8_184_CH3) + #print(unit_name, tool_name, 60, E8_184_CH4) + #print(unit_name, tool_name, 61, E8_184_CH5) + #print(unit_name, tool_name, 62, E8_184_CH6) + #print(unit_name, tool_name, 63, E8_184_CH7) + #print(unit_name, tool_name, 64, E8_184_CH8) + #print(rowSplitted) + #--------------------------------------------------------------------------------------- + dataToInsertRaw.append((unit_name, tool_name, 41, date, time, an4, -273, E8_182_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 42, date, time, an4, -273, E8_182_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 43, date, time, an4, -273, E8_182_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 44, date, time, an4, -273, E8_182_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 49, date, time, an4, -273, E8_183_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 50, date, time, an4, -273, E8_183_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 51, date, time, an4, -273, E8_183_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 52, date, time, an4, -273, E8_183_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 56, date, time, an4, -273, E8_183_CH8)) + dataToInsertRaw.append((unit_name, tool_name, 57, date, time, an4, -273, E8_184_CH1)) + dataToInsertRaw.append((unit_name, tool_name, 58, date, time, an4, -273, E8_184_CH2)) + dataToInsertRaw.append((unit_name, tool_name, 59, date, time, an4, -273, E8_184_CH3)) + dataToInsertRaw.append((unit_name, tool_name, 60, date, time, an4, -273, E8_184_CH4)) + dataToInsertRaw.append((unit_name, tool_name, 61, date, time, an4, -273, E8_184_CH5)) + dataToInsertRaw.append((unit_name, tool_name, 62, date, time, an4, -273, E8_184_CH6)) + #--------------------------------------------------------------------------------------- + dataToInsertElab.append((unit_name, tool_name, 41, date, time, E8_182_CH1)) + dataToInsertElab.append((unit_name, tool_name, 42, date, time, E8_182_CH2)) + dataToInsertElab.append((unit_name, tool_name, 43, date, time, E8_182_CH3)) + dataToInsertElab.append((unit_name, tool_name, 44, date, time, E8_182_CH4)) + dataToInsertElab.append((unit_name, tool_name, 49, date, time, E8_183_CH1)) + dataToInsertElab.append((unit_name, tool_name, 50, date, time, E8_183_CH2)) + dataToInsertElab.append((unit_name, tool_name, 51, date, time, E8_183_CH3)) + dataToInsertElab.append((unit_name, tool_name, 52, date, time, E8_183_CH4)) + dataToInsertElab.append((unit_name, tool_name, 56, date, time, E8_183_CH8)) + dataToInsertElab.append((unit_name, tool_name, 57, date, time, E8_184_CH1)) + dataToInsertElab.append((unit_name, tool_name, 58, date, time, E8_184_CH2)) + dataToInsertElab.append((unit_name, tool_name, 59, date, time, E8_184_CH3)) + dataToInsertElab.append((unit_name, tool_name, 60, date, time, E8_184_CH4)) + dataToInsertElab.append((unit_name, tool_name, 61, date, time, E8_184_CH5)) + dataToInsertElab.append((unit_name, tool_name, 62, date, time, E8_184_CH6)) + #--------------------------------------------------------------------------------------- + cursor.executemany(queryElab, dataToInsertElab) + cursor.executemany(queryRaw, dataToInsertRaw) + conn.commit() + #print(dataToInsertElab) + #print(dataToInsertRaw) + except Error as e: + print('Error:', e) + finally: + cursor.close() + conn.close() + except Exception as e: + print(f"An unexpected error occurred: {str(e)}\n") + +def main(): + getDataFromCsvAndInsert(sys.argv[1]) + +if __name__ == '__main__': + main() diff --git a/vulinkScript.py b/vulinkScript.py new file mode 100755 index 0000000..71b74e5 --- /dev/null +++ b/vulinkScript.py @@ -0,0 +1,172 @@ +#!/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 json +import random + +def checkBatteryLevel(db_conn, db_cursor, unit, date_time, battery_perc): + print(date_time, battery_perc) + if(float(battery_perc) < 25):#sotto il 25% + query = "select unit_name, date_time from alarms where unit_name=%s and date_time < %s and type_id=2 order by date_time desc limit 1" + db_cursor.execute(query, [unit, date_time]) + result = db_cursor.fetchall() + if(len(result) > 0): + alarm_date_time = result[0]["date_time"]#datetime not str + format1 = "%Y-%m-%d %H:%M" + dt1 = datetime.strptime(date_time, format1) + time_difference = abs(dt1 - alarm_date_time) + if time_difference.total_seconds() > 24 * 60 * 60: + print("The difference is above 24 hours. Creo allarme battery") + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, unit_name, date_time, battery_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [2, unit, date_time, battery_perc, "75%", 1, 0]) + db_conn.commit() + else: + print("Creo allarme battery") + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, unit_name, date_time, battery_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [2, unit, date_time, battery_perc, "75%", 1, 0]) + db_conn.commit() + +def checkSogliePh(db_conn, db_cursor, unit, tool, node_num, date_time, ph_value, soglie_str): + soglie = json.loads(soglie_str) + soglia = next((item for item in soglie if item.get("type") == "PH Link"), None) + ph = soglia["data"]["ph"] + ph_uno = soglia["data"]["ph_uno"] + ph_due = soglia["data"]["ph_due"] + ph_tre = soglia["data"]["ph_tre"] + ph_uno_value = soglia["data"]["ph_uno_value"] + ph_due_value = soglia["data"]["ph_due_value"] + ph_tre_value = soglia["data"]["ph_tre_value"] + ph_uno_sms = soglia["data"]["ph_uno_sms"] + ph_due_sms = soglia["data"]["ph_due_sms"] + ph_tre_sms = soglia["data"]["ph_tre_sms"] + ph_uno_email = soglia["data"]["ph_uno_email"] + ph_due_email = soglia["data"]["ph_due_email"] + ph_tre_email = soglia["data"]["ph_tre_email"] + alert_uno = 0 + alert_due = 0 + alert_tre = 0 + ph_value_prev = 0 + #print(unit, tool, node_num, date_time) + query = "select XShift, EventDate, EventTime from ELABDATADISP where UnitName=%s and ToolNameID=%s and NodeNum=%s and concat(EventDate, ' ', EventTime) < %s order by concat(EventDate, ' ', EventTime) desc limit 1" + db_cursor.execute(query, [unit, tool, node_num, date_time]) + resultPhPrev = db_cursor.fetchall() + if(len(resultPhPrev) > 0): + ph_value_prev = float(resultPhPrev[0]["XShift"]) + #ph_value = random.uniform(7, 10) + print(tool, unit, node_num, date_time, ph_value) + #print(ph_value_prev, ph_value) + if(ph == 1): + if(ph_tre == 1 and ph_tre_value != '' and float(ph_value) > float(ph_tre_value)): + if(ph_value_prev <= float(ph_tre_value)): + alert_tre = 1 + if(ph_due == 1 and ph_due_value != '' and float(ph_value) > float(ph_due_value)): + if(ph_value_prev <= float(ph_due_value)): + alert_due = 1 + if(ph_uno == 1 and ph_uno_value != '' and float(ph_value) > float(ph_uno_value)): + if(ph_value_prev <= float(ph_uno_value)): + alert_uno = 1 + #print(ph_value, ph, " livelli:", ph_uno, ph_due, ph_tre, " value:", ph_uno_value, ph_due_value, ph_tre_value, " sms:", ph_uno_sms, ph_due_sms, ph_tre_sms, " email:", ph_uno_email, ph_due_email, ph_tre_email) + if(alert_tre == 1): + print("level3",tool, unit, node_num, date_time, ph_value) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 3, "pH", ph_tre_email, ph_tre_sms]) + db_conn.commit() + elif(alert_due == 1): + print("level2",tool, unit, node_num, date_time, ph_value) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 2, "pH", ph_due_email, ph_due_sms]) + db_conn.commit() + elif(alert_uno == 1): + print("level1",tool, unit, node_num, date_time, ph_value) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 1, "pH", ph_uno_email, ph_uno_sms]) + db_conn.commit() + +def getDataFromCsv(pathFile): + try: + folder_path, file_with_extension = os.path.split(pathFile) + file_name, _ = os.path.splitext(file_with_extension)#toolname + serial_number = file_name.split("_")[0] + query = "SELECT unit_name, tool_name FROM vulink_tools WHERE serial_number=%s" + query_node_depth = "SELECT depth, t.soglie, n.num as node_num FROM ase_lar.nodes as n left join tools as t on n.tool_id=t.id left join units as u on u.id=t.unit_id where u.name=%s and t.name=%s and n.nodetype_id=2" + query_nodes = "SELECT t.soglie, n.num as node_num, n.nodetype_id FROM ase_lar.nodes as n left join tools as t on n.tool_id=t.id left join units as u on u.id=t.unit_id where u.name=%s and t.name=%s" + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor(dictionary=True) + cursor.execute(query, [serial_number]) + result = cursor.fetchall() + unit = result[0]["unit_name"] + tool = result[0]["tool_name"] + cursor.execute(query_node_depth, [unit, tool]) + resultNode = cursor.fetchall() + cursor.execute(query_nodes, [unit, tool]) + resultAllNodes = cursor.fetchall() + #print(resultAllNodes) + node_num_piezo = next((item for item in resultAllNodes if item.get('nodetype_id') == 2), None)["node_num"] + node_num_baro = next((item for item in resultAllNodes if item.get('nodetype_id') == 3), None)["node_num"] + node_num_conductivity = next((item for item in resultAllNodes if item.get('nodetype_id') == 94), None)["node_num"] + node_num_ph = next((item for item in resultAllNodes if item.get('nodetype_id') == 97), None)["node_num"] + #print(node_num_piezo, node_num_baro, node_num_conductivity, node_num_ph) + # 2 piezo + # 3 baro + # 94 conductivity + # 97 ph + node_depth = float(resultNode[0]["depth"]) #node piezo depth + with open(pathFile, 'r', encoding='ISO-8859-1') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + for row in data: + row = row.split(",") + date_time = datetime.strptime(row[1], '%Y/%m/%d %H:%M').strftime('%Y-%m-%d %H:%M') + date_time = date_time.split(" ") + date = date_time[0] + time = date_time[1] + temperature_unit = float(row[2]) + battery_perc = float(row[3]) + pressure_baro = float(row[4])*1000#(kPa) da fare *1000 per Pa in elab->pressure + conductivity = float(row[6]) + ph = float(row[11]) + temperature_piezo = float(row[14]) + pressure = float(row[16])*1000 + depth = (node_depth * -1) + float(row[17])#da sommare alla quota del nodo (quota del nodo fare *-1) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, pressure) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, node_num_baro, date, time, battery_perc, temperature_unit, pressure_baro]) + cursor.execute(queryInsElab, [unit, tool, node_num_baro, date, time, pressure_baro]) + conn.commit() + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, node_num_conductivity, date, time, battery_perc, temperature_unit, conductivity]) + cursor.execute(queryInsElab, [unit, tool, node_num_conductivity, date, time, conductivity]) + conn.commit() + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, node_num_ph, date, time, battery_perc, temperature_unit, ph]) + cursor.execute(queryInsElab, [unit, tool, node_num_ph, date, time, ph]) + conn.commit() + checkSogliePh(conn, cursor, unit, tool, node_num_ph, date_time[0]+" "+date_time[1], ph, resultNode[0]["soglie"]) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0, Val1, Val2) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, T_node, water_level, pressure) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, node_num_piezo, date, time, battery_perc, temperature_unit, temperature_piezo, depth, pressure]) + cursor.execute(queryInsElab, [unit, tool, node_num_piezo, date, time, temperature_piezo, depth, pressure]) + conn.commit() + checkBatteryLevel(conn, cursor, unit, date_time[0]+" "+date_time[1], battery_perc) + except Error as e: + print('Error:', e) +def main(): + getDataFromCsv(sys.argv[1]) +if __name__ == '__main__': + main() diff --git a/vulinkScript_new_old.py b/vulinkScript_new_old.py new file mode 100755 index 0000000..915cf22 --- /dev/null +++ b/vulinkScript_new_old.py @@ -0,0 +1,125 @@ +#!/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 json +import random + +def checkSogliePh(db_conn, db_cursor, unit, tool, node_num, date_time, ph_value, soglie_str): + soglie = json.loads(soglie_str) + soglia = next((item for item in soglie if item.get("type") == "PH Link"), None) + ph = soglia["data"]["ph"] + ph_uno = soglia["data"]["ph_uno"] + ph_due = soglia["data"]["ph_due"] + ph_tre = soglia["data"]["ph_tre"] + ph_uno_value = soglia["data"]["ph_uno_value"] + ph_due_value = soglia["data"]["ph_due_value"] + ph_tre_value = soglia["data"]["ph_tre_value"] + ph_uno_sms = soglia["data"]["ph_uno_sms"] + ph_due_sms = soglia["data"]["ph_due_sms"] + ph_tre_sms = soglia["data"]["ph_tre_sms"] + ph_uno_email = soglia["data"]["ph_uno_email"] + ph_due_email = soglia["data"]["ph_due_email"] + ph_tre_email = soglia["data"]["ph_tre_email"] + alert_uno = 0 + alert_due = 0 + alert_tre = 0 + #ph_value = random.uniform(8, 10) + #print(ph_value) + if(ph == 1): + if(ph_tre == 1 and ph_tre_value != '' and float(ph_value) > float(ph_tre_value)): + alert_tre = 1 + if(ph_due == 1 and ph_due_value != '' and float(ph_value) > float(ph_due_value)): + alert_due = 1 + if(ph_uno == 1 and ph_uno_value != '' and float(ph_value) > float(ph_uno_value)): + alert_uno = 1 + #print(ph_value, ph, " livelli:", ph_uno, ph_due, ph_tre, " value:", ph_uno_value, ph_due_value, ph_tre_value, " sms:", ph_uno_sms, ph_due_sms, ph_tre_sms, " email:", ph_uno_email, ph_due_email, ph_tre_email) + if(alert_tre == 1): + print("level3",tool, unit, node_num, date_time) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 3, "pH", ph_tre_email, ph_tre_sms]) + db_conn.commit() + elif(alert_due == 1): + print("level2",tool, unit, node_num, date_time) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 2, "pH", ph_due_email, ph_due_sms]) + db_conn.commit() + elif(alert_uno == 1): + print("level1",tool, unit, node_num, date_time) + queryInsAlarm = "INSERT IGNORE INTO alarms(type_id, tool_name, unit_name, date_time, registered_value, node_num, alarm_level, description, send_email, send_sms) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + db_cursor.execute(queryInsAlarm, [3, tool, unit, date_time, ph_value, node_num, 1, "pH", ph_uno_email, ph_uno_sms]) + db_conn.commit() + +def getDataFromCsv(pathFile): + try: + folder_path, file_with_extension = os.path.split(pathFile) + file_name, _ = os.path.splitext(file_with_extension)#toolname + serial_number = file_name.split("_")[0] + query = "SELECT unit_name, tool_name FROM vulink_tools WHERE serial_number=%s" + query_node_depth = "SELECT depth, t.soglie, n.num as node_num FROM ase_lar.nodes as n left join tools as t on n.tool_id=t.id left join units as u on u.id=t.unit_id where u.name=%s and t.name=%s and n.nodetype_id=2" + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor(dictionary=True) + cursor.execute(query, [serial_number]) + result = cursor.fetchall() + unit = result[0]["unit_name"] + tool = result[0]["tool_name"] + cursor.execute(query_node_depth, [unit, tool]) + resultNode = cursor.fetchall() + node_depth = float(resultNode[0]["depth"]) #node piezo depth + with open(pathFile, 'r', encoding='ISO-8859-1') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + for row in data: + row = row.split(",") + date_time = datetime.strptime(row[1], '%Y/%m/%d %H:%M').strftime('%Y-%m-%d %H:%M') + date_time = date_time.split(" ") + date = date_time[0] + time = date_time[1] + temperature_unit = float(row[2]) + battery_perc = float(row[3]) + pressure_baro = float(row[4])*1000#(kPa) da fare *1000 per Pa in elab->pressure + conductivity = float(row[6]) + ph = float(row[11]) + temperature_piezo = float(row[14]) + pressure = float(row[16])*1000 + depth = (node_depth * -1) + float(row[17])#da sommare alla quota del nodo (quota del nodo fare *-1) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, pressure) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 1, date, time, battery_perc, temperature_unit, pressure_baro]) + cursor.execute(queryInsElab, [unit, tool, 1, date, time, pressure_baro]) + conn.commit() + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 2, date, time, battery_perc, temperature_unit, conductivity]) + cursor.execute(queryInsElab, [unit, tool, 2, date, time, conductivity]) + conn.commit() + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 3, date, time, battery_perc, temperature_unit, ph]) + cursor.execute(queryInsElab, [unit, tool, 3, date, time, ph]) + conn.commit() + checkSogliePh(conn, cursor, unit, tool, resultNode[0]["node_num"], date_time[0]+" "+date_time[1], ph, resultNode[0]["soglie"]) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0, Val1, Val2) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, T_node, water_level, pressure) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 4, date, time, battery_perc, temperature_unit, temperature_piezo, depth, pressure]) + cursor.execute(queryInsElab, [unit, tool, 4, date, time, temperature_piezo, depth, pressure]) + conn.commit() + except Error as e: + print('Error:', e) +def main(): + getDataFromCsv(sys.argv[1]) +if __name__ == '__main__': + main() diff --git a/vulinkScript_old.py b/vulinkScript_old.py new file mode 100755 index 0000000..da5fa3f --- /dev/null +++ b/vulinkScript_old.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +import sys +import os +from mysql.connector import MySQLConnection, Error +from dbconfig import read_db_config +from datetime import datetime + +def insertData(dati): + #print(dati) + if dati != "null": + query = "INSERT INTO ELABDATANESA(UnitName, ToolNameID, NodeNum, EventTimestamp, dataJSON) " \ + "VALUES(%s,%s,%s,%s,%s)" + + try: + db_config = read_db_config() + conn = MySQLConnection(**db_config) + + cursor = conn.cursor() + cursor.executemany(query, dati) + + conn.commit() + except Error as e: + print('Error:', e) + + finally: + os.system("cd /usr/local/matlab_func/; ./run_Tilt_lnx.sh /usr/local/MATLAB/MATLAB_Runtime/v93/ "+dati[0][0]+" "+dati[0][1]+"") + cursor.close() + conn.close() + +def getDataFromCsv(pathFile): + try: + folder_path, file_with_extension = os.path.split(pathFile) + file_name, _ = os.path.splitext(file_with_extension)#toolname + serial_number = file_name.split("_")[0] + query = "SELECT unit_name, tool_name FROM vulink_tools WHERE serial_number=%s" + query_node_depth = "SELECT depth FROM ase_lar.nodes as n left join tools as t on n.tool_id=t.id left join units as u on u.id=t.unit_id where u.name=%s and t.name=%s and n.nodetype_id=2" + db_config = read_db_config() + conn = MySQLConnection(**db_config) + cursor = conn.cursor() + cursor.execute(query, [serial_number]) + result = cursor.fetchall() + unit = result[0][0] + tool = result[0][1] + cursor.execute(query_node_depth, [unit, tool]) + resultNode = cursor.fetchall() + node_depth = float(resultNode[0][0]) #node piezo depth + with open(pathFile, 'r', encoding='ISO-8859-1') as file: + data = file.readlines() + data = [row.rstrip() for row in data] + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + data.pop(0) #rimuove header + for row in data: + row = row.split(",") + date_time = datetime.strptime(row[1], '%Y/%m/%d %H:%M').strftime('%Y-%m-%d %H:%M') + date_time = date_time.split(" ") + date = date_time[0] + time = date_time[1] + temperature_unit = float(row[2]) + battery_perc = float(row[3]) + pressure_baro = float(row[4])*1000#(kPa) da fare *1000 per Pa in elab->pressure + conductivity = float(row[6]) + ph = float(row[11]) + temperature_piezo = float(row[14]) + pressure = float(row[16])*1000 + depth = (node_depth * -1) + float(row[17])#da sommare alla quota del nodo (quota del nodo fare *-1) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, pressure) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 1, date, time, battery_perc, temperature_unit, pressure_baro]) + cursor.execute(queryInsElab, [unit, tool, 1, date, time, pressure_baro]) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 2, date, time, battery_perc, temperature_unit, conductivity]) + cursor.execute(queryInsElab, [unit, tool, 2, date, time, conductivity]) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, XShift) VALUES(%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 3, date, time, battery_perc, temperature_unit, ph]) + cursor.execute(queryInsElab, [unit, tool, 3, date, time, ph]) + queryInsRaw = "INSERT IGNORE INTO RAWDATACOR(UnitName, ToolNameID, NodeNum, EventDate, EventTime, BatLevel, Temperature, Val0, Val1, Val2) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" + queryInsElab = "INSERT IGNORE INTO ELABDATADISP(UnitName, ToolNameID, NodeNum, EventDate, EventTime, T_node, water_level, pressure) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)" + cursor.execute(queryInsRaw, [unit, tool, 4, date, time, battery_perc, temperature_unit, temperature_piezo, depth, pressure]) + cursor.execute(queryInsElab, [unit, tool, 4, date, time, temperature_piezo, depth, pressure]) + conn.commit() + except Error as e: + print('Error:', e) +def main(): + getDataFromCsv(sys.argv[1]) +if __name__ == '__main__': + main()