orezebta creat
This commit is contained in:
219
app.py
219
app.py
@@ -1,3 +1,4 @@
|
||||
#App version 2.1
|
||||
import rdm6300
|
||||
import os, time
|
||||
import logging
|
||||
@@ -5,15 +6,29 @@ from gpiozero import OutputDevice
|
||||
from multiprocessing import Process
|
||||
import requests
|
||||
import subprocess
|
||||
import urllib3
|
||||
import threading
|
||||
import urllib.parse
|
||||
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
|
||||
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():
|
||||
log_dir = './data/'
|
||||
log_file = 'log.txt'
|
||||
@@ -23,80 +38,131 @@ def delete_old_logs():
|
||||
file_mod_time = datetime.fromtimestamp(os.path.getmtime(log_path))
|
||||
if datetime.now() - file_mod_time > timedelta(days=10):
|
||||
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:
|
||||
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:
|
||||
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
|
||||
delete_old_logs()
|
||||
|
||||
|
||||
def config():
|
||||
import config
|
||||
|
||||
# function for posting data to the harting server
|
||||
def post_backup_data():
|
||||
logging.info("Reading backup data from tag.txt...")
|
||||
|
||||
try:
|
||||
with open("./data/tag.txt", "r") as file:
|
||||
lines = file.readlines()
|
||||
|
||||
remaining_lines = lines[:]
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line:
|
||||
logging.info(f"Posting backup data: {line}")
|
||||
|
||||
try:
|
||||
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
|
||||
logging.info("Data posted successfully: %s", response.text)
|
||||
log_info_with_server(f"Data posted successfully:")
|
||||
remaining_lines.remove(line + "\n")
|
||||
except requests.exceptions.Timeout:
|
||||
logging.warning("Request timed out.")
|
||||
log_info_with_server("Request timed out.")
|
||||
break
|
||||
except requests.exceptions.RequestException as e:
|
||||
logging.error("An error occurred: %s", e)
|
||||
log_info_with_server(f"An error occurred: {e}")
|
||||
break
|
||||
|
||||
with open("./data/tag.txt", "w") as file:
|
||||
file.writelines(remaining_lines)
|
||||
logging.info("Backup data updated.")
|
||||
#log_info_with_server("Backup data updated.")
|
||||
|
||||
except FileNotFoundError:
|
||||
logging.warning("No backup file found.")
|
||||
except Exception as e:
|
||||
logging.error("An error occurred while reading the backup file: %s", e)
|
||||
log_info_with_server("No backup file found.")
|
||||
|
||||
|
||||
# Function to 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_unblock_wifi = 'sudo rfkill unblock wifi'
|
||||
logging.info('Internet connection check loaded')
|
||||
log_info_with_server('Internet connection check loaded')
|
||||
delete_old_logs()
|
||||
|
||||
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)
|
||||
chromium_process_name = "chromium"
|
||||
|
||||
while True:
|
||||
response = os.system("ping -c 1 " + hostname)
|
||||
if response == 0:
|
||||
var1 = 0
|
||||
manage_wifi_connection()
|
||||
|
||||
else:
|
||||
var1 = 1
|
||||
manage_wifi_connection()
|
||||
try:
|
||||
# Use subprocess to execute the ping command
|
||||
response = subprocess.run(
|
||||
["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)
|
||||
|
||||
# Refresh Chromium process
|
||||
log_info_with_server("Refreshing Chromium process.")
|
||||
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
|
||||
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)
|
||||
|
||||
info = "0"
|
||||
|
||||
#function to post 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
|
||||
try:
|
||||
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
|
||||
logging.info("Data posted successfully: %s", response.text)
|
||||
log_info_with_server("Data posted successfully")
|
||||
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
|
||||
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:
|
||||
logging.error("An error occurred: %s", e)
|
||||
|
||||
with open("./data/tag.txt", "a") as file: # Open in append mode
|
||||
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):
|
||||
thread = threading.Thread(target=post_info, args=(info,))
|
||||
thread = threading.Thread(target=asyncio.run, args=(post_info_async(info),), daemon=True)
|
||||
thread.start()
|
||||
|
||||
led1 = OutputDevice(23)
|
||||
@@ -138,48 +221,44 @@ f = open("./data/idmasa.txt", "r") # deschid fisierul
|
||||
name = f.readline().strip() # citesc toate liniile
|
||||
f.close() # inchid fisierul
|
||||
logging.info(name)
|
||||
|
||||
#clasa reader
|
||||
class Reader(rdm6300.BaseReader):
|
||||
global info
|
||||
def card_inserted(self, card):
|
||||
if card.value == 12886709:
|
||||
logging.info("Inserting Config Card")
|
||||
|
||||
config()
|
||||
return
|
||||
|
||||
|
||||
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
|
||||
if name == "noconfig":
|
||||
led1.on()
|
||||
logging.info(info)
|
||||
logging.info(f"card inserted {card}")
|
||||
time.sleep(5)
|
||||
led1.off()
|
||||
log_info_with_server(f"card inserted {card} but no")
|
||||
else:
|
||||
logging.info(info)
|
||||
post_info_thread(info)
|
||||
led1.on()
|
||||
logging.info(f"card inserted {card}")
|
||||
logging.info(f"card removed {card}")
|
||||
|
||||
#log_info_with_server(f"card inserted {card}")
|
||||
|
||||
def card_removed(self, card):
|
||||
if card.value == 12886709:
|
||||
logging.info("Removing Config card")
|
||||
log_info_with_server("Removing Config card")
|
||||
return
|
||||
# config()
|
||||
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"
|
||||
|
||||
afisare = time.strftime("%Y-%m-%d&%H:%M:%S")
|
||||
date = f'https://dataswsibiusb01.sibiusb.harting.intra/RO_Quality_PRD/api/record/{name}/{card.value}/0/{afisare}\n'
|
||||
info = date
|
||||
if name == "noconfig":
|
||||
led1.of()
|
||||
logging.info(info)
|
||||
logging.info(f"card card removed {card}")
|
||||
led1.off()
|
||||
log_info_with_server(f"card removed {card}")
|
||||
else:
|
||||
logging.info(info)
|
||||
post_info_thread(info)
|
||||
led1.off()
|
||||
logging.info(f"card removed {card}")
|
||||
logging.info(f"card removed {card}")
|
||||
log_info_with_server(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