Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Chaining vs. Methods in API extension

So I'm looking in to extending/adapting an API in my own need. I'm speaking about the Lego Mindstorms C# API. I'm building my own kind of API around it (based on the adapter pattern) so I can program the robot in a better OO way.

Here's the link about how the API works: Lego Mindstorms EV3 C# API

But now I'm stuck at a very strange way the C# API handles commands to the brick.

Definitely not the OO-way...

An example: To send a command to the brick you need to have an instance of the brick to send the command. But the DirectCommand instance has nothing to do with the brick.

await brick.DirectCommand.TurnMotorAtPowerAsync(OutputPort.A, 50, 5000);

So the thing I would like to do is make the brick and DirectCommand loosely coupled.

Here's another example: To execute a batch of commands. You have to write out all commands, and then execute a certain method. In the current API there is no way of looping through an array and adding them a stack element, to execute them at a later point.

brick.BatchCommand.TurnMotorAtSpeedForTime(OutputPort.A, 50, 1000, false);
brick.BatchCommand.TurnMotorAtPowerForTime(OutputPort.C, 50, 1000, false);
brick.BatchCommand.PlayTone(50, 1000, 500);
await brick.BatchCommand.SendCommandAsync();

So the thing I would like to do is:

Create a command like PlayTone(..) add it to an arrayList of commands and then loop through it...

List<Command> toBeExecuted = new List<Command>;
toBeExecuted.Add(DirectCommand.PlayTone(50, 1000, 500));
brick.DirectCommand(toBeExecuted[0]);

So if anyone could help... I would be very pleased :)

like image 800
Wouter Bloeyaert Avatar asked Nov 09 '22 04:11

Wouter Bloeyaert


1 Answers

Not exactly what they were designed for, but could you queue them up as a list of Tasks, and pass that around instead?

Like so:

static void Main(string[] args)
{
    //---- queue commands into a "batch"
    List<Task> toBeExecuted  = new List<Task>();
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));
    toBeExecuted.Add(Task.Run(() => dothing()));


    //---- elsewhere
    Task.WaitAll(toBeExecuted.ToArray()); //fire off the batch
    await brick.BatchCommand.SendCommandAsync(); //send to brick
}

Substituting dothing() for the batchcommand you want to queue:

.Add(Task.Run(() => brick.BatchCommand...()));

like image 152
Kaelan Fouwels Avatar answered Nov 14 '22 22:11

Kaelan Fouwels