58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
import asyncio
|
|
import aiohttp
|
|
import sys
|
|
import serial_asyncio # Ensure this package is installed
|
|
|
|
def parse_to_graphite(data):
|
|
results = []
|
|
|
|
lines = data.strip().split('\n')
|
|
for line in lines:
|
|
if line.startswith('>>>'):
|
|
metric_path = line[3:].strip() # Remove the ">>>" prefix and any leading/trailing whitespace
|
|
results.append(metric_path)
|
|
return results
|
|
|
|
async def send_to_graphite(data, session, api_url):
|
|
for message in data:
|
|
#print(f"Sending data to API: {message}") # Debug message for sending data
|
|
try:
|
|
# Sending raw metric path directly as plain text
|
|
headers = {'Content-Type': 'text/plain'}
|
|
async with session.post(api_url, data=message, headers=headers) as response:
|
|
if response.status != 200:
|
|
print(f"Failed to send data: {response.status}", await response.text())
|
|
except Exception as e:
|
|
print(f"Error sending data: {e}")
|
|
|
|
async def handle_serial(reader, api_url):
|
|
session = aiohttp.ClientSession()
|
|
try:
|
|
while True:
|
|
line = await reader.readline()
|
|
if not line:
|
|
break
|
|
line = line.decode('utf-8')
|
|
print(line.strip()) # echo output for received line
|
|
graphite_data = parse_to_graphite(line)
|
|
if graphite_data:
|
|
await send_to_graphite(graphite_data, session, api_url)
|
|
finally:
|
|
await session.close()
|
|
|
|
async def main():
|
|
if len(sys.argv) < 3:
|
|
print("Usage: python script.py <serial_device> <api_url>")
|
|
sys.exit(1)
|
|
|
|
serial_device = sys.argv[1]
|
|
api_url = sys.argv[2]
|
|
baud_rate = 115200 # You can modify this as needed
|
|
|
|
# Creating the connection to the serial port
|
|
reader, _ = await serial_asyncio.open_serial_connection(url=serial_device, baudrate=baud_rate)
|
|
await handle_serial(reader, api_url)
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(main())
|