From 2290c8dbf859f7a15e4b916013733dae74a187b9 Mon Sep 17 00:00:00 2001 From: ske087 Date: Tue, 18 Mar 2025 12:20:06 +0200 Subject: [PATCH] created utils py --- app.py | 88 ++++++++++++++----- app_schema.txt | 29 ++++++- instances/__pycache__/db.cpython-311.pyc | Bin 1029 -> 2379 bytes instances/db.py | 17 +++- instances/logs.db | Bin 0 -> 36864 bytes logs.db | Bin 16384 -> 0 bytes mission_utils.py | 106 +++++++++++++++++++++++ query_db.py | 24 +++++ 8 files changed, 241 insertions(+), 23 deletions(-) create mode 100644 instances/logs.db delete mode 100644 logs.db create mode 100644 mission_utils.py create mode 100644 query_db.py diff --git a/app.py b/app.py index c612c21..8879ef5 100644 --- a/app.py +++ b/app.py @@ -1,14 +1,23 @@ from flask import Flask, request, jsonify from datetime import datetime import sqlite3 -from instances.db import init_db +import requests +import os +from instances.db import init_db, DB_PATH +from mission_utils import delayed_post_mission, post_mission, get_robots, get_status app = Flask(__name__) # Variable to store the status of inputs and outputs status = { "input1": "off", - "relay1": "off" + "input2": "off", + "input3": "off", + "input4": "off", + "relay1": "off", + "relay2": "off", + "relay3": "off", + "relay4": "off" } @app.route('/log', methods=['POST']) @@ -26,28 +35,65 @@ def log(): print(f"Board IP address: {ip_address}") print(f"Message: {message}") - # Update the status of inputs and relays based on the message - if 'input1' in message: - status['input1'] = 'on' if 'input1 on' in message else 'off' - print(f"Input 1 is {status['input1']}") - if 'relay1' in message: - status['relay1'] = 'on' if 'relay1 on' in message else 'off' - print(f"Relay 1 status is {status['relay1']}") - # Record the log in the database - conn = sqlite3.connect('logs.db') + conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute("INSERT INTO logs (timestamp, hostname, ip_address, message) VALUES (?, ?, ?, ?)", (datetime.now().isoformat(), hostname, ip_address, message)) conn.commit() + print(f"Log entry added: {hostname}, {ip_address}, {message}") + + # Check if the board exists in the database + c.execute("SELECT * FROM boards WHERE ip_address = ?", (ip_address,)) + board = c.fetchone() + + if not board: + # Create a new board entry if it doesn't exist + c.execute('''INSERT INTO boards (hostname, ip_address, input1, input2, input3, input4, relay1, relay2, relay3, relay4) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', + (hostname, ip_address, 'off', 'off', 'off', 'off', 'off', 'off', 'off', 'off')) + conn.commit() + print(f"New board entry created: {hostname}, {ip_address}") + + # Update the status of inputs and relays based on the message + for i in range(1, 5): + if f"Input {i} pressed" in message: + status[f"input{i}"] = 'on' + print(f"Input {i} is {status[f'input{i}']}") + if i == 1: + print("Input 1 is on, triggering delayed_post_mission") + delayed_post_mission({"mission_id": "a1343edc-975c-11ef-87e6-0242ac120002"}) # Example mission ID + c.execute(f'''UPDATE boards SET input{i} = ? WHERE ip_address = ?''', + (status[f"input{i}"], ip_address)) + conn.commit() + print(f"Board status updated: {hostname}, {ip_address}, input{i}={status[f'input{i}']}") + + if f"Input {i} released" in message: + status[f"input{i}"] = 'off' + print(f"Input {i} is {status[f'input{i}']}") + c.execute(f'''UPDATE boards SET input{i} = ? WHERE ip_address = ?''', + (status[f"input{i}"], ip_address)) + conn.commit() + print(f"Board status updated: {hostname}, {ip_address}, input{i}={status[f'input{i}']}") + + for i in range(1, 5): + if f"Relay {i} turned ON" in message: + status[f"relay{i}"] = 'on' + print(f"Relay {i} status is {status[f'relay{i}']}") + c.execute(f'''UPDATE boards SET relay{i} = ? WHERE ip_address = ?''', + (status[f"relay{i}"], ip_address)) + conn.commit() + print(f"Board status updated: {hostname}, {ip_address}, relay{i}={status[f'relay{i}']}") + + if f"Relay {i} turned OFF" in message: + status[f"relay{i}"] = 'off' + print(f"Relay {i} status is {status[f'relay{i}']}") + c.execute(f'''UPDATE boards SET relay{i} = ? WHERE ip_address = ?''', + (status[f"relay{i}"], ip_address)) + conn.commit() + print(f"Board status updated: {hostname}, {ip_address}, relay{i}={status[f'relay{i}']}") - # Update the board status in the database - c.execute('''INSERT OR REPLACE INTO boards (hostname, ip_address, input1, relay1) - VALUES (?, ?, ?, ?)''', - (hostname, ip_address, status['input1'], status['relay1'])) - conn.commit() conn.close() - return jsonify({"message": "Log received"}), 200 @app.route('/control', methods=['POST']) @@ -57,12 +103,14 @@ def control(): return jsonify({"error": "No data provided"}), 400 # Control the relays based on the received data - if 'relay1' in data: - status['relay1'] = data['relay1'] - print(f"Setting Relay 1 to {data['relay1']}") + for i in range(1, 5): + if f'relay{i}' in data: + status[f'relay{i}'] = data[f'relay{i}'] + print(f"Setting Relay {i} to {data[f'relay{i}']}") return jsonify({"message": "Control command received"}), 200 if __name__ == '__main__': init_db() + get_robots() app.run(host='0.0.0.0', port=80) \ No newline at end of file diff --git a/app_schema.txt b/app_schema.txt index 24e4822..040c922 100644 --- a/app_schema.txt +++ b/app_schema.txt @@ -18,13 +18,30 @@ - relay3: TEXT - relay4: TEXT +## Table: mir_server_missions +- ip: TEXT +- authorization: TEXT +- username: TEXT +- password: TEXT +- mission_id: TEXT + +## Table: requested_missions +- state: TEXT +- start_time: TEXT +- mission: TEXT +- mission_name: TEXT +- robot_id: INTEGER +- id: INTEGER PRIMARY KEY + # Explanation of Functions in app.py ## Function: init_db - Initializes the SQLite database. -- Creates two tables: logs and boards. +- Creates four tables: logs, boards, mir_server_missions, and requested_missions. - The logs table stores log entries with timestamp, hostname, IP address, and message. - The boards table stores the status of each board with hostname, IP address, and status of inputs and relays. +- The mir_server_missions table stores the information required to create a JSON post for a mission. +- The requested_missions table stores the response data from the mission post request. ## Function: log - Endpoint: /log @@ -35,6 +52,7 @@ - Updates the status of inputs and relays based on the message. - Records the log in the logs table. - Updates the board status in the boards table. +- Triggers the post_mission function if input1 is turned on. ## Function: control - Endpoint: /control @@ -42,4 +60,11 @@ - Receives control commands to update the status of relays. - Extracts the relay status from the JSON payload. - Prints the new relay status. -- Updates the status of the relays. \ No newline at end of file +- Updates the status of the relays. + +## Function: post_mission +- Sends a mission post request to the MIR server. +- Retrieves the IP, authorization, username, and password from the mir_server_missions table. +- Formats the headers and sends a POST request to the mission scheduler endpoint. +- Prints the result of the mission post request. +- Stores the response data in the requested_missions table. \ No newline at end of file diff --git a/instances/__pycache__/db.cpython-311.pyc b/instances/__pycache__/db.cpython-311.pyc index 932f3dc5f39304de68870ff3b43bf8f3928eab42..0cc4feedff9f043b860cecbed436782e0e53193f 100644 GIT binary patch literal 2379 zcmb7G-A~(A6u%DnDk)=~CUuXNI%#AL#EFvt5*-RlpaEj4BxOxrEXVgkY!W-Qol&ep zQ^ZuQLh3Y4VlR_;qMG`$|6i+)hoG zN1g);fH(MV59m6;m~YN-OI|pz14=$f4>96QUsYYz$6#6PIN1|{CrO;X#bA5D zID-U0KI08X61{;p!PAdy;sArbu|p8DNj;_Z9VllCT%2A+3VhVkb#2RmYg@XnZF!;O zI8U(OZT0zfFxR{DKKt=PUvJy~2PW9}_5|$+7h^+!4}hOD)o*j@WFbu#k~52GIx|ai zO9eXpD3dSbX>u$E>5F5;kZMRbgj$_0q#qSRbVbz-MW~^UDAjoZLJjG9X8~L5!fIO` zH2>@qu&fFiyeec*2>L-TlTGG|^g_BAqA!J$lzPL6bdw=M)G4q|A=VKzR24S5KDN;H zv4yUWEwp`t=C6G=Qj;`ZN80yD<7<+xOR93!uB2`Sg@#d4HOUkVY}rYvf&Cp-tqZ!o zu4=HO?V$2fd%;e)Us-j%raad zJ(tem9-Z;MiRStxN>KV#&50DE8(P&)C}{qW;qvKRfnLhdnK^DLhYvMZSfa1!2t6Xz zLv&B=F;J)MA-Y@f5caiOh_@8H{5UKp7aykc^vHCGKK})S9y1VO#>Nw4kvKaRGnE-Z zmqfZWS2f}N`Fc@VX3A_PQHAQ#VqCC5n zjg~6eR1(YS^=wMq$eN|KY>Hc3np>`La(07DEo1#ETa@S5O38cotN@gBLzBu4L)ENl z5sDM#1jC9E0kUEu4iP&6R}zzGvK)czioh_5NleD0YyvVYoIpZ?jmF{vGcjI{LTG*| zMA#UMpg1}?9v4R=5wtQoF^&?WOf(i1#7LB3m}t;v`SizC$v~{-6IDe)qG9<`GyH>O z;lAY+8=8)D@u4S3Y#0bHsI{78SRS#e>L}>4+{DMCM4f!BX!^t5a7C@5a9s+gkiKT9 z^>7wHReAfV3QGz;mx_q=Ff5PNH!Po|NCpqf+Nao=ya07S{zx^!UxCkdr+*ti4BR;i z+-atc{Wo6)UIu;~+8t^pkKLXZne9vqP{VoZ9iTh~>b*_z3g%DF)sl;-WfxJ)E~1uQ z4t34;R%~yDB5K9yy=kkrZ1t9{-g2sA1UpWkrd|+w;#CcNUxWbxJ-0LBB={W4Tn_a@Pf;V!35i zQY;^o>=%vY=lK<>ig;f0V>`Q&zXR7c1uU>^-hJMn1S>Jp1^RxXYhqsxd+sq%q!@;Se!KtRN<^G(y)dH7^ G9rQmRL^5Ik delta 369 zcmX>t)XGu6oR^o20SFkcUQfTz$iVOz#DM`ODC4sTkTIPhg&~D8harj~g{g%hiZO*T zm_d{IB}j>1GE^a$Vg`~R{P`D;H;AD9^# W8E-J~HGts<77j+i4-A+D*dPG5CPy^@ diff --git a/instances/db.py b/instances/db.py index b1b8311..a5505ba 100644 --- a/instances/db.py +++ b/instances/db.py @@ -1,11 +1,26 @@ import sqlite3 +import os + +DB_PATH = os.path.join(os.path.dirname(__file__), 'logs.db') def init_db(): - conn = sqlite3.connect('logs.db') + conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS logs (timestamp TEXT, hostname TEXT, ip_address TEXT, message TEXT)''') c.execute('''CREATE TABLE IF NOT EXISTS boards (hostname TEXT PRIMARY KEY, ip_address TEXT, input1 TEXT, input2 TEXT, input3 TEXT, input4 TEXT, relay1 TEXT, relay2 TEXT, relay3 TEXT, relay4 TEXT)''') + c.execute('''CREATE TABLE IF NOT EXISTS mir_server_missions + (ip TEXT, authorization TEXT, username TEXT, password TEXT, mission_id TEXT PRIMARY KEY)''') + c.execute('''CREATE TABLE IF NOT EXISTS requested_missions + (state TEXT, start_time TEXT, mission TEXT, mission_name TEXT, robot_id INTEGER, id INTEGER PRIMARY KEY)''') + c.execute('''CREATE TABLE IF NOT EXISTS robots + (ip TEXT PRIMARY KEY, url TEXT)''') + conn.commit() + + # Insert a first row into the mir_server_missions table + c.execute('''INSERT OR IGNORE INTO mir_server_missions (ip, authorization, username, password, mission_id) + VALUES (?, ?, ?, ?, ?)''', + ("10.76.153.4", "Basic ZGlzdHJpYnV0b3I6Y2RjYjhiNjAzYzFhZDNjNjVkZTM4ZGY2OWU5YjFkM2ZhMDA2OWEwMDcyMzZkMDNkOGVhNjMyNDVhMDg3YjJkZA==", "distributor", "cdc8b603c1ad3c65de38df69e9b1d3fa0069a007236d03d8ea63245a087b2dd", "a1343edc-975c-11ef-87e6-0242ac120002")) conn.commit() conn.close() \ No newline at end of file diff --git a/instances/logs.db b/instances/logs.db new file mode 100644 index 0000000000000000000000000000000000000000..5ab4637a90f9f6e89000e40a646eb625dfd3e085 GIT binary patch literal 36864 zcmeI)O>g2x7zc2BvjMVA!d@bj%gWUrTC^nc3m9^UwrpY3qzh?TlGaF-HF%t0-pqQ; zra|fpIrX#j6ZPYCY(oNBr>b(PlKw4h&olPK^ZaHwjI8kf`*)6SOJ}Y(Aikst&jnEw zzLF$C5E6V}EDIa`U@fb$L6o;_Zt_R#q~eeU#$Of zS0mIz00Izz00bZa0SG_<0{?};PswCvdt01t`J~;qJ-6-pEIOvXZdA+7s?;pMc~_O9 zx@Xeu?Mr7QHLE{1rSBStwQ|FdzO5QLY3%jG+U%=TBJ+A%6r3Toe`X*0d?jL%vG0bl z8U0aHiOy@&qeL>JDB{)Ys5AD5vCVv&ngfS1#~m{7lbYmmCqKC!(_!Wlz8nhroRfIj z^G)9w%qwP3nq8hn=8#<95O&pcsB~CwRu8I;oODxOG{{c(pC&V!CSH9WCNpq6liA)! z+q=#trfPL5otPV9@|g`lPU5Z|*K;Ps=T@@}#{8KJy&nBwI-$I7AOFYV=^`}iw+VxJn=qKS34^Fj_SMQi&FUxv_ula!0%?{Jet$ljo{(Wg9A1QKmY;|fB*y_ z009U<00Izz00bVZ0M`GHb!3qj1Rwwb2tWV=5P$##AOHafK;TB;Sy06L{~HjLAOHaf zKmY;|fB*y_009U<00NItAb9^TrZ)xt!3F^cKmY;|fB*y_009U<00I#Bp9oA{G4*ol zyqtb^qR6{NeOD=HyZJYSIhNEq=uhZ3Mx)hhMg@xf`Q-mP8ME2sSWxn^{a zdad&QK6RMyIc@$k7@kF~Qd^fbOCeOV^a8cD5DJ6=Q*KBI->=g^vj-uFSJEfwn@5pLiC6=PfvaAO0|HbrQ0{>ux00bZa z0SG_<0uX=z1Rwwb2teS034F0~vi5J*|M>s^2R5+iE(9O|0SG_<0uX=z1Rwwb2teQ- z0$Bgw0}V|e009U<00Izz00bZa0SG_<0uM|8zyJ5Z1`OSW00bZa0SG_<0uX=z1Rwwb I2;4*9Z&AgV2mk;8 literal 0 HcmV?d00001 diff --git a/logs.db b/logs.db deleted file mode 100644 index 2c6aec5955657343e0aefe39dca6fd20de9ba67d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16384 zcmeI0%Wl&^6hQ5y&%9hHP1RMsDHN4jGvgUQvVlG#wNOM!v!JWUZJZJ*FJc#!O`)v# z03;+ngcTAJU%?6qi7(&_n2Bph+i8`o5Y-*oNvMosGG`^ zqN>URT~`#v;Ohuq*AAo@(Mm5M9nqF!EE-74zQwv>Lp zEk17tVasd!db#+ltZ$b#AFq^l^+(0sdwRW7@v7CX9|XOfd_${q7~=kb^ao~tKu?3N z-|$|==k$X3oL&&0(+i?=?k*+AX7A6bO1)L}kAfEs{(N2W4#RdYu0)koaP%#nrzgb4 zeW{Mm&djJMPkJI6?Snw9i8B(!7Kwte-t>deYj#dkKBGjUfgc@s2a&P6S^nSo$uElb zNo#0#azAn(a;01*`!#!%H8MXlA2ZvTvGnJ3H@%qpo_e2pm>T5=Ljwa~01SWuFaQR? z02ugJ2G;YVEAtD>1QE83%w=qsF)AQdV9c;hi#f~>I=z`D!N{;J12faWWK&Fpb)xfG ztM3JVb!|pamM&6=flbOBbS0%Drr3UU9^6T|LuN}7b!+N__ zZyjt*%So7%h>c8nQBu-P8HpBnPL_qRblMf^@B`zu@ z01SWuFaQR?02lxRU;qq&0Wbgtz`%cI;C4Pezc9^{7OV7KQoB~;ON#GSwO