|
| 1 | +import socket |
| 2 | +import json |
| 3 | +import csv |
| 4 | +import os |
| 5 | + |
| 6 | +def listen_on_udp(ip, port, file_path): |
| 7 | + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 8 | + server_address = (ip, port) |
| 9 | + sock.bind(server_address) |
| 10 | + |
| 11 | + print(f"Listening on UDP {ip}:{port}...") |
| 12 | + |
| 13 | + while True: |
| 14 | + data, address = sock.recvfrom(4096) |
| 15 | + |
| 16 | + try: |
| 17 | + json_data = json.loads(data.decode('utf-8')) |
| 18 | + print(f"Received JSON data from {address}: {json_data}") |
| 19 | + |
| 20 | + with open(file_path, 'a', newline='') as csvfile: |
| 21 | + fieldnames = ['timestamp', 'acceleration_x', 'acceleration_y', 'acceleration_z'] |
| 22 | + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) |
| 23 | + |
| 24 | + acceleration_x = json_data.get('accelX', 0) |
| 25 | + acceleration_y = json_data.get('accelY', 0) |
| 26 | + acceleration_z = json_data.get('accelZ', 0) |
| 27 | + timestamp = json_data.get('accelTime', 0) |
| 28 | + |
| 29 | + writer.writerow({'timestamp': timestamp, 'acceleration_x': acceleration_x, 'acceleration_y': acceleration_y, 'acceleration_z': acceleration_z}) |
| 30 | + except json.JSONDecodeError as e: |
| 31 | + print(f"Failed to decode JSON data: {e}") |
| 32 | + |
| 33 | +if __name__ == "__main__": |
| 34 | + UDP_IP = "ur-ip" |
| 35 | + UDP_PORT = 8888 |
| 36 | + FILE_PATH = r"ur-path" |
| 37 | + |
| 38 | + with open(FILE_PATH, 'w', newline='') as csvfile: |
| 39 | + fieldnames = ['timestamp', 'acceleration_x', 'acceleration_y', 'acceleration_z'] |
| 40 | + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) |
| 41 | + writer.writeheader() |
| 42 | + |
| 43 | + listen_on_udp(UDP_IP, UDP_PORT, FILE_PATH) |
0 commit comments