Я написал скрипт Python для своего проекта автоматизации, который прослушивает тему MQTT и обрабатывает события с именем _PLC_Status. Предполагается, что скрипт вставляет или обновляет записи в базе данных. Однако когда я планирую этот сценарий с помощью cron, записи только вставляются, а не обновляются.
Проблема:
Когда сценарий выполняется через cron, он только вставляет новые записи в базу данных вместо обновления существующих.
Что я пробовал:
Проверил журналы cron, чтобы убедиться, что сценарий выполняется.
Проверил путь к базе данных и разрешения.
Убедился, что брокер MQTT и тема указаны правильно.
Желаемый результат:
Я хочу скрипт для обновления существующих записей в базе данных вместо вставки новых при выполнении через cron.
Просьба о помощи:
Кто-нибудь может предложить исправления или улучшения моего сценария для достижения желаемого результата? Любая помощь приветствуется!
import paho.mqtt.client as mqtt
import json
import mysql.connector
# Replace these with your actual database credentials
db_config = {
'host': '103.195.185.168',
'user': 'indiscpx_BLVL',
'password': 'indiscpx_BLVL@123',
'database': 'indiscpx_BLVL',
}
# Initialize a dictionary to store the previous values for each tag
previous_values = {}
def connect_to_database():
return mysql.connector.connect(\*\*db_config)
def on_message(client, userdata, message):
global previous_values # Declare it as a global variable to maintain its value between function calls
payload = message.payload.decode("utf-8")
# Check if the topic contains "_PLC_Status"
if "_PLC_Status" in message.topic:
try:
conn = connect_to_database()
cursor = conn.cursor(buffered=True)
data = json.loads(payload)
print("data ; ",data)
date = data.get("time")
name = data.get("name")
value1 = data.get("value")
value = str(value1).strip()
print("value ; ",value)
# Check if the tag already exists in the database
check_query = "SELECT * FROM Plcstatus2 WHERE name = %s"
cursor.execute(check_query, (name,))
result = cursor.fetchall()
if result:
existing_value = result[0][3]
trimmed_value = str(existing_value).strip()
print("trimmed_value ; ",trimmed_value)
# Assuming the value is in the third column, adjust if necessary
select_mid_query = "SELECT Eid FROM Matchine_Details WHERE PLC_Name = %s"
cursor.execute(select_mid_query, (name,))
mid_result = cursor.fetchone()
if trimmed_value != value:
# Value has changed, insert new record
insert_query = "INSERT INTO Plcstatus2 (Time, name, value, MID) VALUES (%s, %s, %s, %s)"
cursor.execute(insert_query, (date, name, value, mid_result[0] ))
conn.commit()
print(f"Data inserted for tag '{name}'.")
else:
# Check if the tag already exists in the PLCStatus table
check_query = "SELECT * FROM Plcstatus2 WHERE name = %s"
cursor.execute(check_query, (name,))
result = cursor.fetchall()
if result:
# Value has not changed, update the timestamp
update_query = "UPDATE Plcstatus2 SET Time = %s WHERE name = %s"
cursor.execute(update_query, (date, name))
conn.commit()
print(f"Timestamp updated for tag '{name}'.")
else:
if mid_result is not None:
if mid_result[0]:
insert_query = "INSERT INTO Plcstatus2 (Time, name, value, MID) VALUES (%s, %s, %s, %s)"
cursor.execute(insert_query, (date, name, value, mid_result[0]))
conn.commit()
print(f"Data inserted for tag '{name}'.")
else:
print("Error: MID is None or empty")
else:
print("Error: Unable to fetch MID")
# else:
# Tag doesn't exist, insert new record
# insert_query = "INSERT INTO PLCStatus (Time, name, value) VALUES (%s, %s, %s)"
# cursor.execute(insert_query, (date, name, value))
# conn.commit()
# print(f"New tag '{name}' added with value {value}.")
# Update the previous value for the tag
previous_values[name] = value
except Exception as e:
print(f"Error: {e}")
finally:
cursor.close()
conn.close()
# Create an MQTT client
client = mqtt.Client()
# Set the callback function for message reception
client.on_message = on_message
# Connect to the MQTT broker
client.connect("43.225.52.207", 1883)
# Subscribe to all topics
client.subscribe("WinCC/BLVL_05_04_2023/#")
print("Waiting for MQTT messages...")
# Start the MQTT client loop to listen for messages
client.loop_forever()
Подробнее здесь: https://stackoverflow.com/questions/786 ... n-script-w
Как обновить записи базы данных вместо вставки при запуске сценария Python с помощью задания Cron? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение