orezebta creat
This commit is contained in:
215
app.py
215
app.py
@@ -1,3 +1,4 @@
|
|||||||
|
#App version 2.1
|
||||||
import rdm6300
|
import rdm6300
|
||||||
import os, time
|
import os, time
|
||||||
import logging
|
import logging
|
||||||
@@ -5,15 +6,29 @@ from gpiozero import OutputDevice
|
|||||||
from multiprocessing import Process
|
from multiprocessing import Process
|
||||||
import requests
|
import requests
|
||||||
import subprocess
|
import subprocess
|
||||||
import urllib3
|
|
||||||
import threading
|
import threading
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from datetime import datetime, timedelta # Import datetime and timedelta
|
from datetime import datetime, timedelta # Import datetime and timedelta
|
||||||
|
import socket
|
||||||
|
import signal
|
||||||
|
import aiohttp
|
||||||
|
import asyncio
|
||||||
|
#configurare variabile
|
||||||
|
hostname = socket.gethostname()
|
||||||
|
device_ip = socket.gethostbyname(hostname)
|
||||||
|
|
||||||
urllib3.disable_warnings()
|
print(hostname, device_ip)
|
||||||
|
|
||||||
# Configure logging
|
# Configure logging
|
||||||
logging.basicConfig(filename='./data/log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
logging.basicConfig(filename='./data/log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
#logging.basicConfig(
|
||||||
|
# level=logging.DEBUG, # Set the logging level to DEBUG to capture all logs
|
||||||
|
# format='%(asctime)s [%(threadName)s] %(levelname)s: %(message)s', # Include thread name in logs
|
||||||
|
# handlers=[
|
||||||
|
# logging.StreamHandler() # Print logs to the terminal
|
||||||
|
# ]
|
||||||
|
#)
|
||||||
|
|
||||||
|
# function to delete old logs
|
||||||
def delete_old_logs():
|
def delete_old_logs():
|
||||||
log_dir = './data/'
|
log_dir = './data/'
|
||||||
log_file = 'log.txt'
|
log_file = 'log.txt'
|
||||||
@@ -23,80 +38,131 @@ def delete_old_logs():
|
|||||||
file_mod_time = datetime.fromtimestamp(os.path.getmtime(log_path))
|
file_mod_time = datetime.fromtimestamp(os.path.getmtime(log_path))
|
||||||
if datetime.now() - file_mod_time > timedelta(days=10):
|
if datetime.now() - file_mod_time > timedelta(days=10):
|
||||||
os.remove(log_path)
|
os.remove(log_path)
|
||||||
logging.info("Deleted old log file: %s", log_file)
|
log_info_with_server(f"Deleted old log file: {log_file}")
|
||||||
else:
|
else:
|
||||||
logging.info("Log file is not older than 10 days: %s", log_file)
|
log_info_with_server(f"Log file is not older than 10 days: {log_file}")
|
||||||
else:
|
else:
|
||||||
logging.info("Log file does not exist: %s", log_file)
|
log_info_with_server(f"Log file does not exist: {log_file}")
|
||||||
|
|
||||||
|
# Function to read the name (idmasa) from the file
|
||||||
|
def read_name_from_file():
|
||||||
|
try:
|
||||||
|
with open("./data/idmasa.txt", "r") as file:
|
||||||
|
n_masa = file.readline().strip()
|
||||||
|
return n_masa
|
||||||
|
except FileNotFoundError:
|
||||||
|
logging.error("File ./data/idmasa.txt not found.")
|
||||||
|
return "unknown"
|
||||||
|
|
||||||
|
# Function to send logs to a remote server for the Server_monitorizare APP
|
||||||
|
def send_log_to_server(log_message, n_masa, hostname, device_ip):
|
||||||
|
host = hostname
|
||||||
|
device = device_ip
|
||||||
|
try:
|
||||||
|
|
||||||
|
log_data = {
|
||||||
|
"hostname": str(host),
|
||||||
|
"device_ip": str(device),
|
||||||
|
"nume_masa": str(n_masa),
|
||||||
|
"log_message": str(log_message)
|
||||||
|
}
|
||||||
|
server_url = "http://rpi-ansible:80/logs" # Replace with your server's URL
|
||||||
|
print(log_data) # Debugging: Print log_data to verify its contents
|
||||||
|
response = requests.post(server_url, json=log_data, timeout=5)
|
||||||
|
response.raise_for_status()
|
||||||
|
logging.info("Log successfully sent to server: %s", log_message)
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
logging.error("Failed to send log to server: %s", e)
|
||||||
|
# Wrapper for logging.info to also send logs to the server Monitorizare APP
|
||||||
|
def log_info_with_server(message):
|
||||||
|
n_masa = read_name_from_file() # Read name (idmasa) from the file
|
||||||
|
formatted_message = f"{message} (n_masa: {n_masa})" # Format the message
|
||||||
|
logging.info(formatted_message) # Log the formatted message
|
||||||
|
send_log_to_server(message, n_masa, hostname, device_ip) # Send the original message to the server
|
||||||
# Call the function to delete old logs
|
# Call the function to delete old logs
|
||||||
delete_old_logs()
|
delete_old_logs()
|
||||||
|
|
||||||
|
|
||||||
def config():
|
def config():
|
||||||
import config
|
import config
|
||||||
|
# function for posting data to the harting server
|
||||||
def post_backup_data():
|
def post_backup_data():
|
||||||
logging.info("Reading backup data from tag.txt...")
|
|
||||||
try:
|
try:
|
||||||
with open("./data/tag.txt", "r") as file:
|
with open("./data/tag.txt", "r") as file:
|
||||||
lines = file.readlines()
|
lines = file.readlines()
|
||||||
|
|
||||||
remaining_lines = lines[:]
|
remaining_lines = lines[:]
|
||||||
|
|
||||||
for line in lines:
|
for line in lines:
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line:
|
if line:
|
||||||
logging.info(f"Posting backup data: {line}")
|
|
||||||
try:
|
try:
|
||||||
response = requests.post(line, verify=False, timeout=3)
|
response = requests.post(line, verify=False, timeout=3)
|
||||||
logging.info("Request sent, awaiting response...")
|
#
|
||||||
response.raise_for_status() # Raise an error for bad status codes
|
response.raise_for_status() # Raise an error for bad status codes
|
||||||
logging.info("Data posted successfully: %s", response.text)
|
log_info_with_server(f"Data posted successfully:")
|
||||||
remaining_lines.remove(line + "\n")
|
remaining_lines.remove(line + "\n")
|
||||||
except requests.exceptions.Timeout:
|
except requests.exceptions.Timeout:
|
||||||
logging.warning("Request timed out.")
|
log_info_with_server("Request timed out.")
|
||||||
break
|
break
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
logging.error("An error occurred: %s", e)
|
log_info_with_server(f"An error occurred: {e}")
|
||||||
break
|
break
|
||||||
|
|
||||||
with open("./data/tag.txt", "w") as file:
|
with open("./data/tag.txt", "w") as file:
|
||||||
file.writelines(remaining_lines)
|
file.writelines(remaining_lines)
|
||||||
logging.info("Backup data updated.")
|
#log_info_with_server("Backup data updated.")
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
logging.warning("No backup file found.")
|
log_info_with_server("No backup file found.")
|
||||||
except Exception as e:
|
|
||||||
logging.error("An error occurred while reading the backup file: %s", e)
|
|
||||||
|
|
||||||
|
|
||||||
|
# Function to check internet connection
|
||||||
def check_internet_connection():
|
def check_internet_connection():
|
||||||
hostname = "10.76.140.17" # "https://google.com"
|
hostname = "10.76.140.17"
|
||||||
cmd_block_wifi = 'sudo rfkill block wifi'
|
cmd_block_wifi = 'sudo rfkill block wifi'
|
||||||
cmd_unblock_wifi = 'sudo rfkill unblock wifi'
|
cmd_unblock_wifi = 'sudo rfkill unblock wifi'
|
||||||
logging.info('Internet connection check loaded')
|
log_info_with_server('Internet connection check loaded')
|
||||||
delete_old_logs()
|
delete_old_logs()
|
||||||
|
chromium_process_name = "chromium"
|
||||||
def manage_wifi_connection():
|
|
||||||
if var1 == 0:
|
|
||||||
logging.info("Internet is up! Waiting 45 minutes.")
|
|
||||||
post_backup_data()
|
|
||||||
time.sleep(2700)
|
|
||||||
else:
|
|
||||||
os.system(cmd_block_wifi)
|
|
||||||
logging.info('System is rebooting WiFi, please wait until it finishes the job 20 minutes')
|
|
||||||
time.sleep(1200) # 20 minutes
|
|
||||||
os.system(cmd_unblock_wifi)
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
response = os.system("ping -c 1 " + hostname)
|
try:
|
||||||
if response == 0:
|
# Use subprocess to execute the ping command
|
||||||
var1 = 0
|
response = subprocess.run(
|
||||||
manage_wifi_connection()
|
["ping", "-c", "1", hostname],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL
|
||||||
|
)
|
||||||
|
if response.returncode == 0:
|
||||||
|
log_info_with_server("Internet is up! Waiting 45 minutes.")
|
||||||
|
post_backup_data()
|
||||||
|
time.sleep(2700) # 45 minutes
|
||||||
|
else:
|
||||||
|
log_info_with_server("Internet is down. Rebooting WiFi.")
|
||||||
|
os.system(cmd_block_wifi)
|
||||||
|
time.sleep(1200) # 20 minutes
|
||||||
|
os.system(cmd_unblock_wifi)
|
||||||
|
|
||||||
else:
|
# Refresh Chromium process
|
||||||
var1 = 1
|
log_info_with_server("Refreshing Chromium process.")
|
||||||
manage_wifi_connection()
|
try:
|
||||||
|
# Find and terminate Chromium processes
|
||||||
|
subprocess.run(["pkill", "-f", chromium_process_name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
time.sleep(5) # Wait for processes to terminate
|
||||||
|
|
||||||
|
# Relaunch Chromium
|
||||||
|
url = "10.76.140.17/iweb_v2/index.php/traceability/production"
|
||||||
|
subprocess.Popen(
|
||||||
|
["chromium", "--test-type", "--noerrors", "--kiosk", "--start-fullscreen",
|
||||||
|
"--unsafely-treat-insecure-origin-as-secure=http://10.76.140.17", url],
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, start_new_session=True
|
||||||
|
)
|
||||||
|
log_info_with_server("Chromium process restarted successfully.")
|
||||||
|
except Exception as e:
|
||||||
|
log_info_with_server(f"Failed to refresh Chromium process: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
log_info_with_server(f"An error occurred during internet check: {e}")
|
||||||
|
time.sleep(60) # Retry after 1 minute in case of an error
|
||||||
|
|
||||||
# Start the internet connection check in a separate process
|
# Start the internet connection check in a separate process
|
||||||
internet_check_process = Process(target=check_internet_connection)
|
internet_check_process = Process(target=check_internet_connection)
|
||||||
@@ -106,28 +172,45 @@ url = "10.76.140.17/iweb_v2/index.php/traceability/production" # pentru cazul in
|
|||||||
subprocess.Popen(["chromium", "--test-type", "--noerrors", "--kiosk", "--start-fullscreen", "--unsafely-treat-insecure-origin-as-secure=http://10.76.140.17", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, start_new_session=True)
|
subprocess.Popen(["chromium", "--test-type", "--noerrors", "--kiosk", "--start-fullscreen", "--unsafely-treat-insecure-origin-as-secure=http://10.76.140.17", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, start_new_session=True)
|
||||||
|
|
||||||
info = "0"
|
info = "0"
|
||||||
|
#function to post info
|
||||||
def post_info(info):
|
def post_info(info):
|
||||||
logging.info("Starting to post data...")
|
#log_info_with_server("Starting to post data...")
|
||||||
info1 = info.strip() # Remove any leading/trailing whitespace, including newlines
|
info1 = info.strip() # Remove any leading/trailing whitespace, including newlines
|
||||||
try:
|
try:
|
||||||
response = requests.post(info1, verify=False, timeout=3)
|
response = requests.post(info1, verify=False, timeout=3)
|
||||||
logging.info("Request sent, awaiting response...")
|
|
||||||
response.raise_for_status() # Raise an error for bad status codes
|
response.raise_for_status() # Raise an error for bad status codes
|
||||||
logging.info("Data posted successfully: %s", response.text)
|
log_info_with_server("Data posted successfully")
|
||||||
except requests.exceptions.Timeout:
|
except requests.exceptions.Timeout:
|
||||||
logging.warning("Request timed out. Saving data to backup file.")
|
|
||||||
with open("./data/tag.txt", "a") as file: # Open in append mode
|
with open("./data/tag.txt", "a") as file: # Open in append mode
|
||||||
file.write(info)
|
file.write(info)
|
||||||
logging.info("Value %s was saved to tag.txt", info)
|
log_info_with_server(f"Value {info} was saved to tag.txt")
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
logging.error("An error occurred: %s", e)
|
|
||||||
with open("./data/tag.txt", "a") as file: # Open in append mode
|
with open("./data/tag.txt", "a") as file: # Open in append mode
|
||||||
file.write(info)
|
file.write(info)
|
||||||
logging.info("Value %s was saved to tag.txt", info)
|
log_info_with_server("Value was saved to tag.txt")
|
||||||
|
|
||||||
|
async def post_info_async(info):
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
try:
|
||||||
|
async with session.post(info, ssl=False, timeout=3) as response:
|
||||||
|
response_text = await response.text()
|
||||||
|
log_info_with_server(f"Data posted successfully")
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
log_info_with_server("Request timed out. Saving data to backup file.")
|
||||||
|
with open("./data/tag.txt", "a") as file:
|
||||||
|
file.write(info)
|
||||||
|
log_info_with_server(f"Value was saved to tag.txt due to timeout error ")
|
||||||
|
except Exception as e:
|
||||||
|
|
||||||
|
with open("./data/tag.txt", "a") as file:
|
||||||
|
file.write(info)
|
||||||
|
log_info_with_server(f"Value was saved to tag.txt due to an error {e}")
|
||||||
|
|
||||||
def post_info_thread(info):
|
def post_info_thread(info):
|
||||||
thread = threading.Thread(target=post_info, args=(info,))
|
thread = threading.Thread(target=asyncio.run, args=(post_info_async(info),), daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
led1 = OutputDevice(23)
|
led1 = OutputDevice(23)
|
||||||
@@ -138,48 +221,44 @@ f = open("./data/idmasa.txt", "r") # deschid fisierul
|
|||||||
name = f.readline().strip() # citesc toate liniile
|
name = f.readline().strip() # citesc toate liniile
|
||||||
f.close() # inchid fisierul
|
f.close() # inchid fisierul
|
||||||
logging.info(name)
|
logging.info(name)
|
||||||
|
#clasa reader
|
||||||
class Reader(rdm6300.BaseReader):
|
class Reader(rdm6300.BaseReader):
|
||||||
global info
|
global info
|
||||||
def card_inserted(self, card):
|
def card_inserted(self, card):
|
||||||
if card.value == 12886709:
|
if card.value == 12886709:
|
||||||
logging.info("Inserting Config Card")
|
|
||||||
config()
|
config()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
afisare = time.strftime("%Y-%m-%d&%H:%M:%S")
|
afisare = time.strftime("%Y-%m-%d&%H:%M:%S")
|
||||||
date = 'https://dataswsibiusb01.sibiusb.harting.intra/RO_Quality_PRD/api/record/' + name + '/' + str(card.value) + "/1/" + afisare + "\n"
|
date = f'https://dataswsibiusb01.sibiusb.harting.intra/RO_Quality_PRD/api/record/{name}/{card.value}/1/{afisare}\n'
|
||||||
info = date
|
info = date
|
||||||
if name == "noconfig":
|
if name == "noconfig":
|
||||||
led1.on()
|
led1.on()
|
||||||
logging.info(info)
|
time.sleep(5)
|
||||||
logging.info(f"card inserted {card}")
|
led1.off()
|
||||||
|
log_info_with_server(f"card inserted {card} but no")
|
||||||
else:
|
else:
|
||||||
logging.info(info)
|
|
||||||
post_info_thread(info)
|
post_info_thread(info)
|
||||||
led1.on()
|
led1.on()
|
||||||
logging.info(f"card inserted {card}")
|
#log_info_with_server(f"card inserted {card}")
|
||||||
logging.info(f"card removed {card}")
|
|
||||||
|
|
||||||
def card_removed(self, card):
|
def card_removed(self, card):
|
||||||
if card.value == 12886709:
|
if card.value == 12886709:
|
||||||
logging.info("Removing Config card")
|
log_info_with_server("Removing Config card")
|
||||||
return
|
return
|
||||||
# config()
|
|
||||||
afisare=time.strftime("%Y-%m-%d&%H:%M:%S")
|
afisare = time.strftime("%Y-%m-%d&%H:%M:%S")
|
||||||
date='https://dataswsibiusb01.sibiusb.harting.intra/RO_Quality_PRD/api/record/'+name+'/'+str(card.value)+"/0/"+afisare+"\n"
|
date = f'https://dataswsibiusb01.sibiusb.harting.intra/RO_Quality_PRD/api/record/{name}/{card.value}/0/{afisare}\n'
|
||||||
info = date
|
info = date
|
||||||
if name == "noconfig":
|
if name == "noconfig":
|
||||||
led1.of()
|
led1.off()
|
||||||
logging.info(info)
|
log_info_with_server(f"card removed {card}")
|
||||||
logging.info(f"card card removed {card}")
|
|
||||||
else:
|
else:
|
||||||
logging.info(info)
|
|
||||||
post_info_thread(info)
|
post_info_thread(info)
|
||||||
led1.off()
|
led1.off()
|
||||||
logging.info(f"card removed {card}")
|
log_info_with_server(f"card removed {card}")
|
||||||
logging.info(f"card removed {card}")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
28
cert.sh
28
cert.sh
@@ -1,28 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Instalare certificate
|
|
||||||
echo -e "\e[1;32m Copiem si instalam certificatele Harting \e[0m"
|
|
||||||
sudo mkdir /usr/local/share/ca-certificates/Harting
|
|
||||||
sudo cp -R /home/pi/Desktop/Prezenta/Files/reposytory/Harting/ /usr/local/share/ca-certificates/Harting/
|
|
||||||
|
|
||||||
sudo update-ca-certificates
|
|
||||||
sleep 3
|
|
||||||
echo -e "\e[1;32m Instalam Libnss3-tool ca sa actualizam certificatele in Browser \e[0m"
|
|
||||||
sudo apt install libnss3-tools
|
|
||||||
echo -e "\e[1;32m Libnss3-tools este instalat \e[0m"
|
|
||||||
echo -e "\e[1;32m Cream baza de date pentru certutil \e[0m"
|
|
||||||
#sudo mkdir -p $HOME/.pki/nssdb
|
|
||||||
#sudo certutil -d $HOME/.pki/nssdb -N --empty-password
|
|
||||||
echo -e "\e[1;32m Baza de date a fost creata \e[0m"
|
|
||||||
echo -e "\e[1;32m Actualizam Certificate \e[0m"
|
|
||||||
certutil -d sql:$HOME/.pki/nssdb -A -t "CT,C,C" -n HA_MWG_new_cert -i /etc/ssl/certs/HA_MWG_new_cert.pem
|
|
||||||
echo "cert 1 ok"
|
|
||||||
sleep 3
|
|
||||||
certutil -d sql:$HOME/.pki/nssdb -A -t "CT,C,C" -n HartingIssuingCA1.pem -i /etc/ssl/certs/HartingIssuingCA1.pem
|
|
||||||
echo "cert 2 Ok"
|
|
||||||
sleep 3
|
|
||||||
certutil -d sql:$HOME/.pki/nssdb -A -t "CT,C,C" -n HartingRootCA.pem -i /etc/ssl/certs/HartingRootCA.pem
|
|
||||||
echo "cert 3 ok"
|
|
||||||
echo -e "\e[1;32m Certificatele au fost instalate \e[0m"
|
|
||||||
sleep 3
|
|
||||||
certutil -d sql:$HOME/.pki/nssdb -L
|
|
||||||
sleep 3
|
|
||||||
14
libraries.sh
14
libraries.sh
@@ -1,14 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#install python libraries
|
|
||||||
echo -e "\e[1;32m Incepem Instalarea Librariilor Python \e[0m"
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/six-1.16.0-py2.py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/PyAutoGUI-0.9.54-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/pynput-1.7.6-py2.py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/pyserial-3.5-py2.py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages --no-warn-script-location
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/python_xlib-0.31-py2.py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/python3_xlib-0.15-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/rdm6300-0.1.1-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/typing_extensions-4.11.0-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/FreeSimpleGUI-5.0.0-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
pip3 install /home/pi/Desktop/Prezenta/Files/reposytory/func_timeout-4.3.5-py3-none-any.whl -f ./ --no-index --no-deps --break-system-packages
|
|
||||||
echo -e "\e[1;32m Librariile au fost instalate cu succes \e[0m"
|
|
||||||
Reference in New Issue
Block a user