query channels ain din

This commit is contained in:
2025-05-01 15:34:55 +02:00
parent fd5429ee0d
commit a752210a33
13 changed files with 43 additions and 852 deletions

View File

@@ -13,7 +13,7 @@ def connetti_db(cfg):
A MySQL database connection object.
"""
try:
conn = mysql.connector.connect(user=cfg.dbuser, password=cfg.dbpass, host=cfg.dbhost, port=cfg.dbport)
conn = mysql.connector.connect(user=cfg.dbuser, password=cfg.dbpass, host=cfg.dbhost, port=cfg.dbport, database=cfg.dbname)
conn.autocommit = True
logger.info("Connected")
return conn

View File

@@ -1,96 +0,0 @@
import logging
import datetime
import os
import mysql.connector
from utils.database.connection import connetti_db
logger = logging.getLogger(__name__)
def get_timestamp(log_type):
"""Generates a timestamp string for logging."""
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
def get_nodes_type(db_lar, server, username, password, tool, unit, channels, nodetype, ain, din):
"""
Retrieves node type, Ain, Din, and channels from the database for a specific tool and unit.
Args:
db_lar (str): The name of the MySQL database.
server (str): The hostname or IP address of the MySQL server.
username (str): The MySQL username.
password (str): The MySQL password.
tool (str): The name of the tool.
unit (str): The name of the unit.
channels (list): An empty list to store the 'channels' values.
nodetype (list): An empty list to store the 'type' values.
ain (list): An empty list to store the 'ain' values.
din (list): An empty list to store the 'din' values.
"""
try:
conn = connetti_db(cfg)
cursor = conn.cursor(dictionary=True)
query = f"""
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
INNER JOIN nodetypes AS y ON n.nodetype_id = y.id
WHERE y.type NOT IN ('Anchor Link', 'None') AND t.name = '{tool}' AND u.name = '{unit}'
ORDER BY n.num;
"""
cursor.execute(query)
results = cursor.fetchall()
print(f"{get_timestamp('log')} - pid {os.getpid()} >> {unit} - {tool}: {cursor.rowcount} rows selected to get node type/Ain/Din/channels.")
if not results:
print(f"{get_timestamp('log')} - pid {os.getpid()} >> Node/Channels/Ain/Din not defined.")
print(f"{get_timestamp('log')} - pid {os.getpid()} >> Execution ended.")
exit()
else:
for row in results:
channels.append(row['channels'])
nodetype.append(row['type'])
ain.append(row['ain'])
din.append(row['din'])
cursor.close()
dbh.close()
except mysql.connector.Error as err:
error_message = f"{get_timestamp('log')} - pid {os.getpid()} >> Could not connect to database: {err}"
print(error_message)
raise # Re-raise the exception if you want the calling code to handle it
if __name__ == '__main__':
# Example usage (replace with your actual database credentials and values)
db_name = "your_database_name"
db_server = "your_server_address"
db_user = "your_username"
db_password = "your_password"
current_tool = "your_tool_name"
current_unit = "your_unit_name"
node_channels = []
node_types = []
node_ains = []
node_dins = []
try:
get_nodes_type(db_name, db_server, db_user, db_password, current_tool, current_unit, node_channels, node_types, node_ains, node_dins)
print("\nRetrieved Data:")
print(f"Channels: {node_channels}")
print(f"Node Types: {node_types}")
print(f"Ains: {node_ains}")
print(f"Dins: {node_dins}")
except Exception as e:
print(f"An error occurred: {e}")

View File

@@ -0,0 +1,37 @@
from utils.database.connection import connetti_db
import logging
logger = logging.getLogger(__name__)
def get_nodes_type(cfg, tool, unit):
with connetti_db(cfg) as conn:
cur = conn.cursor(dictionary=True)
query = f"""
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 {cfg.dbname}.{cfg.dbnodes} AS n
INNER JOIN tools AS t ON t.id = n.tool_id
INNER JOIN units AS u ON u.id = t.unit_id
INNER JOIN nodetypes AS y ON n.nodetype_id = y.id
WHERE y.type NOT IN ('Anchor Link', 'None') AND t.name = '{tool}' AND u.name = '{unit}'
ORDER BY n.num;
"""
logger.info(f"{unit} - {tool}: Executing query: {query}")
cur.execute(query)
results = cur.fetchall()
logger.info(f"{unit} - {tool}: {cur.rowcount} rows selected to get node type/Ain/Din/channels.")
cur.close()
conn.close()
if not results:
logger.info(f"{unit} - {tool}: Node/Channels/Ain/Din not defined.")
return None, None, None, None
else:
channels, types, ains, dins = [], [], [], []
for row in results:
channels.append(row['channels'])
types.append(row['type'])
ains.append(row['ain'])
dins.append(row['din'])
return channels, types, ains, dins