#!/usr/bin/env python3 from decimal import Decimal import sys import json import requests from mysql.connector import MySQLConnection, Error from dbconfig import read_db_config def send_elab_data_as_json(matlab_timestamp, unit, tool, api_url, bearer_token): """Function to fetch elaborated data from MySQL and send it as a JSON string via API""" try: # Connect to MySQL database db_config = read_db_config() conn = MySQLConnection(**db_config) cursor = conn.cursor(dictionary=True) # Query to select elaborated data query = """SELECT UnitName, ToolNameID, EventTimestamp, NodeNum, NodeType, NodeDepth, XShift, YShift, ZShift, X, Y, Z, HShift, HShiftDir, HShift_local, speed, speed_local, acceleration, acceleration_local, T_node, water_level, pressure, load_value, AlfaX, AlfaY, Area, calcerr FROM elabdataview WHERE UnitName = %s AND ToolNameID = %s AND updated_at > %s ORDER BY ToolNameID DESC, EventTimestamp, CONVERT(NodeNum, UNSIGNED INTEGER) DESC""" # Execute query cursor.execute(query, (unit, tool, matlab_timestamp)) resultData = cursor.fetchall() # Close cursor and connection cursor.close() conn.close() # Convert Decimal objects to float in resultData for row in resultData: for key, value in row.items(): if isinstance(value, Decimal): row[key] = format(float(value), '.6f') # Convert Decimal to float with full precision #print(resultData) payload = { 'json': json.dumps(resultData) # Convert result to JSON string } print(payload) #with open("payload.json", "w") as file: # json.dump(payload, file, indent=4) headers = { 'Content-Type': 'application/json' } # Add Authorization header if the bearer token is provided if bearer_token: headers['Authorization'] = f'Bearer {bearer_token}' else: print("No Bearer token provided. Authorization header will be omitted.") # Send the JSON data via POST request response = requests.post(api_url, headers=headers, json=payload) response.raise_for_status() # Raise an error for bad responses (4xx or 5xx) # Log the response print(f"Elab Data Response: {response.status_code} - {response.text}") except Exception as e: print(f"Error occurred while sending elab data as JSON: {e}") def main(): if len(sys.argv) != 6: print("Usage: python3 inoltroViaApiElab.py ") sys.exit(1) matlab_timestamp = sys.argv[1] unit = sys.argv[2] tool = sys.argv[3] api_url = sys.argv[4] bearer_token = sys.argv[5] send_elab_data_as_json(matlab_timestamp, unit, tool, api_url, bearer_token) if __name__ == "__main__": main()