def db_execute(query: str, params: tuple) -> bool:
conn = None
cursor = None
try:
conn = mysql.connector.connect(
host= "db",
user="root",
password="test123",
database="robot_dynamic_status"
)
cursor = conn.cursor()
cursor.execute(query, params)
conn.commit()
return True
except mysql.connector.Error as e:
logging.error(f"Database error: {e}")
print(f"Database error: {e.errno}, {e.sqlstate}, {e.msg}")
if conn:
conn.rollback()
return False
except Exception as e:
logging.error(f"Unexpected error: {e}")
print(f"Unexpected error: {e}")
return False
finally:
if cursor:
cursor.close()
if conn and conn.is_connected():
conn.close()
def ip_execute(ip):
try:
status_ip = f"status_{ip.replace('.', '_')}"
connection = mysql.connector.connect(
host="db",
user="root",
password="test123",
database="robot_dynamic_status"
)
cursor = connection.cursor()
create_table_query = f"""
CREATE TABLE IF NOT EXISTS {status_ip} (
`robot_ip` varchar(17) NOT NULL DEFAULT {ip},
`status_busy` tinyint(1) NOT NULL DEFAULT 0,
`status_base` tinyint(1) NOT NULL DEFAULT 0,
`status_error` tinyint(1) NOT NULL DEFAULT 0,
`status_warning` tinyint(1) NOT NULL DEFAULT 0,
`external_voltage` int(11) NOT NULL DEFAULT 0,
`battery_capacity` int(11) NOT NULL DEFAULT 100,
`can_be_started` tinyint(1) NOT NULL DEFAULT 1,
`last_entry_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_event` varchar(255) NOT NULL DEFAULT 'not-initialized',
`remote_rf_port` int(11) DEFAULT 8970,
`installed_firmware` varchar(50) NOT NULL DEFAULT 'not-initialized',
`queue_status` varchar(255) NOT NULL DEFAULT 'not-initialized',
`queue_length` varchar(255) NOT NULL DEFAULT 'not-initialized',
`queue_task` varchar(255) NOT NULL DEFAULT 'not-initialized',
UNIQUE KEY `robot_ip` (`robot_ip`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
"""
cursor.execute(create_table_query)
connection.commit()
return True
except mysql.connector.Error as e:
if 'connection' in locals():
connection.rollback()
return False
finally:
if connection and connection.is_connected():
connection.close()
return False
if not all([sn, ip, fp, device_type]):
return [True, False] # 表单有误时不关闭主模态框
try:
columns = ["serialnumber", "dut_ip", "floorplan", "device_type", "team", "available", "pi_ip"]
values = [sn, ip, fp, device_type, "local", "1", ""]
if pi_ip:
values.pop()
values.append(pi_ip)
query = f"""
INSERT INTO devices
({', '.join(columns)})
VALUES ({', '.join(['%s'] * len(values))})
"""
robot_success = db_execute(query, tuple(values))
status_success = ip_execute(ip)
if robot_success and status_success:
return [True, True]
else:
return [True, False]
最新发布