I must prepare a python program to do the following:
From a table read record addresses (someuserid1 = "10502") which in turn I must send the result of that query to another variable (result1), there is also a variable called (coils) that must know all the time its current state so it is inside a timer, at the time of changing its state from False to True this must do an INSERT of the value that is in (result1).
I am sending variables from (someuserid1 = "10502") to (result1) because the records that I must read are more than 6000 and those record addresses will change several times so in each change I will have to update manually more than 6000 records, but if I put those records to a table I will only have to make an import and the program will update the addresses automatically.
The code I have is this, however for now I have many errors on the one hand I am not familiar with the python indenting and some particular issues.
#!/usr/bin/env python
import os
import time
import psycopg2
from easymodbus.modbusClient import *
#SELECT CONDITIONAL VALUE
someuserid1 = "10502"
someuserid2 = "10504"
someuserid3 = "10506"
try:
connection = psycopg2.connect(user="myuser",
password="mypasswd",
host="127.0.0.1",
port="5432",
database="mydb")
cursor = connection.cursor()
cur.execute(""" SELECT a_field FROM mytable u WHERE u.a_field = %s; """,
[someuserid1,])
cur.execute(""" SELECT a_field FROM mytable u WHERE u.a_field = %s; """,
[someuserid2,])
cur.execute(""" SELECT a_field FROM mytable u WHERE u.a_field = %s; """,
[someuserid3,])
result1 = cur.fetchone()
result2 = cur.fetchone()
result3 = cur.fetchone()
modbusClient = ModbusClient('127.0.0.1', 502)
modbusClient.connect()
coils = modbusClient.read_coils(2, 1)
os.system('cls')
print(i)
print(coils)
i+=1
if coils=True:
print('value changed')
holdingRegisters1 = convert_registers_to_float(modbusClient.read_holdingregisters(result1, 2))
holdingRegisters2 = convert_registers_to_float(modbusClient.read_holdingregisters(result2, 2))
holdingRegisters3 = convert_registers_to_float(modbusClient.read_holdingregisters(result3, 2))
postgres_insert_query = """ INSERT INTO mytblresult (a_data, detail) VALUES (%s,%s)"""
record_to_insert = (holdingRegisters1, 'tg1010_10502')
postgres_insert_query = """ INSERT INTO mytblresult (a_data, detail) VALUES (%s,%s)"""
record_to_insert = (holdingRegisters2, 'tg1010_10504')
postgres_insert_query = """ INSERT INTO mytblresult (a_data, detail) VALUES (%s,%s)"""
record_to_insert = (holdingRegisters3, 'tg1010_10506')
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into mobile table")
modbusClient.close()
time.sleep(1)
except (Exception, psycopg2.Error) as error:
print("Failed to insert record into mobile table", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
I thank you for your kind attention.