Skip to content

feat: RoboticArm CSV import/export #256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 17, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions pslab/external/motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
import time
from typing import List
from typing import Union
import csv
import os

from pslab.instrument.waveform_generator import PWMGenerator
from datetime import datetime

MICROSECONDS = 1e6

Expand Down Expand Up @@ -96,7 +99,7 @@ def run_schedule(self, timeline: List[List[int]], time_step: float = 1.0) -> Non
with angles corresponding to each servo.

time_step : float, optional
Delay in seconds between each timestep. Default is 1.0.
Delay in seconds between each timestep. Default is 1.0.
"""
if len(timeline[0]) != len(self.servos):
raise ValueError("Each timestep must specify an angle for every servo")
Expand All @@ -107,5 +110,60 @@ def run_schedule(self, timeline: List[List[int]], time_step: float = 1.0) -> Non

for tl in timeline:
for i, s in enumerate(self.servos):
s.angle = tl[i]
if tl[i] is not None:
s.angle = tl[i]
time.sleep(time_step)

def import_timeline_from_csv(self, filepath: str) -> List[List[int]]:
"""Import timeline from a CSV file.

Parameters
----------
filepath : str
Absolute or relative path to the CSV file to be read.

Returns
-------
List[List[int]]
A timeline consisting of servo angle values per timestep.
"""
timeline = []

with open(filepath, mode="r", newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
angles = []
for key in ["Servo1", "Servo2", "Servo3", "Servo4"]:
value = row[key]
if value == "null":
angles.append(None)
else:
angles.append(int(value))
timeline.append(angles)

return timeline

def export_timeline_to_csv(
self, timeline: List[List[Union[int, None]]], folderpath: str
) -> None:
"""Export timeline to a CSV file.

Parameters
----------
timeline : List[List[Union[int, None]]]
A list of timesteps where each sublist contains servo angles.

folderpath : str
Directory path where the CSV file will be saved. The filename
will include a timestamp to ensure uniqueness.
"""
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"Robotic_Arm{timestamp}.csv"
filepath = os.path.join(folderpath, filename)

with open(filepath, mode="w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Timestep", "Servo1", "Servo2", "Servo3", "Servo4"])
for i, row in enumerate(timeline):
pos = ["null" if val is None else val for val in row]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Inconsistent handling of None values between import and export.

Consider using a single representation for None values (e.g., always 'null') in both import and export, and document this behavior for clarity.

Suggested implementation:

        # Export timeline to CSV, using 'null' to represent None values.
        # When importing, 'null' will be interpreted as None.
        with open(filepath, mode="w", newline="") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(["Timestamp", "Servo1", "Servo2", "Servo3", "Servo4"])
            for i, row in enumerate(timeline):
                pos = ["null" if val is None else val for val in row]
                writer.writerow([i] + pos)
def import_timeline_from_csv(filepath):
    """
    Import a timeline from a CSV file, interpreting 'null' as None.

    Args:
        filepath (str): Path to the CSV file.

    Returns:
        list: Timeline data as a list of lists, with None for 'null' values.
    """
    timeline = []
    with open(filepath, mode="r", newline="") as csvfile:
        reader = csv.reader(csvfile)
        headers = next(reader)  # Skip header
        for row in reader:
            # row[0] is the timestamp/index, skip or store as needed
            positions = [None if val == "null" else float(val) for val in row[1:]]
            timeline.append(positions)
    return timeline
  • If there is already an import function, update its logic to use None if val == "null" else ... for consistency.
  • Ensure that all documentation and usage of import/export functions mention that 'null' is the standard representation for missing values.
  • If the import function is used elsewhere, update those usages to use the new or updated function.

writer.writerow([i] + pos)
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy