Esempio n. 1
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral

            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            motorHat = new MotorHat();
            await motorHat.InitAsync(1600).ConfigureAwait(false);

            stepper = motorHat.GetStepper(200, 1); //200 steps/revolution, motor port 1
            stepper.SetSpeed(10);                  //10 rpm

            while (true)
            {
                stepper.step(100, MotorHat.Stepper.Command.FORWARD, MotorHat.Stepper.Style.SINGLE);
                stepper.step(100, MotorHat.Stepper.Command.BACKWARD, MotorHat.Stepper.Style.SINGLE);

                stepper.step(100, MotorHat.Stepper.Command.FORWARD, MotorHat.Stepper.Style.DOUBLE);
                stepper.step(100, MotorHat.Stepper.Command.BACKWARD, MotorHat.Stepper.Style.DOUBLE);

                stepper.step(100, MotorHat.Stepper.Command.FORWARD, MotorHat.Stepper.Style.INTERLEAVE);
                stepper.step(100, MotorHat.Stepper.Command.BACKWARD, MotorHat.Stepper.Style.INTERLEAVE);

                stepper.step(100, MotorHat.Stepper.Command.FORWARD, MotorHat.Stepper.Style.MICROSTEP);
                stepper.step(100, MotorHat.Stepper.Command.BACKWARD, MotorHat.Stepper.Style.MICROSTEP);
            }
        }
Esempio n. 2
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            motorHat = new MotorHat();
            await motorHat.InitAsync(1600).ConfigureAwait(false);

            stepper1 = motorHat.GetStepper(200, 1); //200 steps/revolution, stepper port 1
            //           stepper2 = motorHat.GetStepper(200, 2);  //200 steps/revolution, stepper port 2
            stepper1.SetSpeed(10);                  //10 rpm
//            stepper2.SetSpeed(10); //10 rpm

            //dcMotor1 = motorHat.GetMotor(3);  //motor port 3
            dcMotor2 = motorHat.GetMotor(4);  //motor port 4

            Stepper1CancellationTokenSource = new CancellationTokenSource();
            //Stepper2CancellationTokenSource = new CancellationTokenSource();

            //Motor1CancellationTokenSource = new CancellationTokenSource();
            Motor2CancellationTokenSource = new CancellationTokenSource();

            Task stepper1Task = Task.Run(() => RunStepper(stepper1, Stepper1CancellationTokenSource.Token));
            //Task stepper2Task = Task.Run(() => RunStepper(stepper2, Stepper2CancellationTokenSource.Token));

            //Task motor1Task = Task.Run(() => RunMotor(dcMotor1, Motor1CancellationTokenSource.Token));
            Task motor2Task = Task.Run(() => RunMotor(dcMotor2, Motor2CancellationTokenSource.Token));

            List <Task> tasks = new List <Task>();

            tasks.Add(stepper1Task);
            // tasks.Add(stepper2Task);

            //tasks.Add(motor1Task);
            tasks.Add(motor2Task);

            Task.WaitAll(tasks.ToArray());

            deferral.Complete();
        }
Esempio n. 3
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            motorHat = new MotorHat();
            await motorHat.InitAsync(1600).ConfigureAwait(false);

            dcMotor = motorHat.GetMotor(4);  //motor port 4

            while (true)
            {
                dcMotor.Run(MotorHat.DCMotor.Command.FORWARD);
                for (uint i = 0; i < 255; i++)
                {
                    dcMotor.SetSpeed(i);
                    Task.Delay(10).Wait();
                }
                for (uint i = 255; i != 0; i--)
                {
                    dcMotor.SetSpeed(i);
                    Task.Delay(10).Wait();
                }

                dcMotor.Run(MotorHat.DCMotor.Command.BACKWARD);
                for (uint i = 0; i < 255; i++)
                {
                    dcMotor.SetSpeed(i);
                    Task.Delay(10).Wait();
                }
                for (uint i = 255; i != 0; i--)
                {
                    dcMotor.SetSpeed(i);
                    Task.Delay(10).Wait();
                }

                dcMotor.Run(MotorHat.DCMotor.Command.RELEASE);
                Task.Delay(1000).Wait();
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            const double Period = 10.0;
            Stopwatch    sw     = Stopwatch.StartNew();

            // Use the following code to generate an I2C address different from the default
            //var busId = 1;
            //var selectedI2cAddress = 0b000000;     // A5 A4 A3 A2 A1 A0
            //var deviceAddress = MotorHat.I2cAddressBase + selectedI2cAddress;
            //var settings = new I2cConnectionSettings(busId, deviceAddress);

            using (var motorHat = new MotorHat())
            {
                var motor = motorHat.CreateDCMotor(1);

                bool done = false;
                Console.CancelKeyPress += (o, e) =>
                {
                    done     = true;
                    e.Cancel = true;
                };

                string lastSpeedDisp = null;
                while (!done)
                {
                    double time = sw.ElapsedMilliseconds / 1000.0;

                    // Note: range is from -1 .. 1 (for 1 pin setup 0 .. 1)
                    motor.Speed = Math.Sin(2.0 * Math.PI * time / Period);
                    string disp = $"Speed = {motor.Speed:0.00}";
                    if (disp != lastSpeedDisp)
                    {
                        lastSpeedDisp = disp;
                        Console.WriteLine(disp);
                    }

                    Thread.Sleep(1);
                }
            }
        }
Esempio n. 5
0
        public static IServiceCollection AddControlLayer(this IServiceCollection services)
        {
            // Configure the Differencial Drive Controller
            services.AddHostedService <DifferentialDriveVelocityController>(s =>
            {
                // Create the motor Hat, and the drivers for left and right motors
                var motorHat         = new MotorHat();
                var leftMotorDriver  = new DCMotorDriver(motorHat.CreateDCMotor(1), s.GetService <ILogger <DCMotorDriver> >());
                var rightMotorDriver = new DCMotorDriver(motorHat.CreateDCMotor(3), s.GetService <ILogger <DCMotorDriver> >());

                // Create the SpeedController that controls left and right motors
                return(new DifferentialDriveVelocityController(
                           leftMotorDriver,
                           rightMotorDriver,
                           s.GetService <IMessageBroker>(),
                           s.GetService <ILogger <DifferentialDriveVelocityController> >()));
            });

            services.Configure <RemoteControlOptions>(options =>
            {
                options.GamepadKeyThrottle = 1;
                options.GamepadKeyYaw      = 0;
            });

            // Configure the Remote Control Controller
            services.AddHostedService <RemoteControlController>(s =>
            {
                var gamepadDriver = new GamepadDriver(s.GetService <ILogger <GamepadDriver> >());

                return(new RemoteControlController(
                           gamepadDriver,
                           s.GetService <IMessageBroker>(),
                           s.GetService <IOptions <RemoteControlOptions> >(),
                           s.GetService <ILogger <RemoteControlController> >()));
            });

            return(services);
        }
Esempio n. 6
0
        private async System.Threading.Tasks.Task GetTaskFromFMS()
        {
            // flag that we are running
            isRunning = true;

            // record the start time
            DateTime start = DateTime.Now;

            // figure out if we need to authenticate to FMS or if we're good
            if (token == null || token == string.Empty)
            {
                lc.LogMessage("Logging into FMS.", LoggingLevel.Information);
                token = await fmserver.Authenticate();

                if (token.ToLower().Contains("error"))
                {
                    lc.LogMessage("Authentication error: " + token, LoggingLevel.Information);
                    token = string.Empty;

                    // and exit but without throwing an exception, we'll just try again on the next timer event
                    return;
                }
                else
                {
                    tokenRecieved = DateTime.Now;
                    lc.LogMessage("Token " + token + " Received at " + tokenRecieved.ToLongTimeString(), LoggingLevel.Information);
                }
            }

            if (token != string.Empty)
            {
                // how old is the token?
                TimeSpan age = start - tokenRecieved;
                lc.LogMessage("Timed run; Token age = " + age, LoggingLevel.Information);

                // query FM to see if there are any outstanding tasks
                var find = fmserver.FindRequest();

                var request1 = find.SearchCriterium();
                request1.AddFieldSearch("flag_ready", "1");

                var foundResponse = await find.Execute();

                if (foundResponse.errorCode > 0)
                {
                    lc.LogMessage("Nothing to do. " + fmserver.lastErrorCode.ToString() + " - " + fmserver.lastErrorMessage, LoggingLevel.Error);
                    return;
                }

                // get the first FM record, we are just going to takcle that one
                var record = foundResponse.data.foundSet.records.First();

                // capture the record id, we'll need it to later update the record
                int taskId = Convert.ToInt32(record.recordId);

                // capture whatever is in the notes fields already so that we can append to it
                string notes         = record.fieldsAndData.Where(pair => pair.Key == "notes").Select(pair => pair.Value).First();
                string direction     = record.fieldsAndData.Where(pair => pair.Key == "motor_direction").Select(pair => pair.Value).First();
                uint   speed         = Convert.ToUInt16(record.fieldsAndData.Where(pair => pair.Key == "motor_speed").Select(pair => pair.Value).First());
                int    motor_number  = Convert.ToInt16(record.fieldsAndData.Where(pair => pair.Key == "motor_number").Select(pair => pair.Value).First());
                int    how_long      = Convert.ToInt16(record.fieldsAndData.Where(pair => pair.Key == "duration").Select(pair => pair.Value).First());
                uint   pwm_frequency = Convert.ToUInt16(record.fieldsAndData.Where(pair => pair.Key == "motor_PWM_frequency").Select(pair => pair.Value).First());


                string note = "";

                // hook into the mother hat
                // this part is not very reliable in the Adafruit library it errors out on every 2nd iteration
                // so we are going to loop until no exception
                MotorHat mh = null;

                int tryCount = 0;
                while (tryCount < 5)
                {
                    try
                    {
                        mh = new MotorHat();
                        await mh.InitAsync(pwm_frequency).ConfigureAwait(false);

                        lc.LogMessage("hat - initialized with PWM frequency of: " + pwm_frequency.ToString(), LoggingLevel.Information);
                    }
                    catch (Exception ex)
                    {
                        tryCount++;
                        note = "init error #" + tryCount + ":" + ex.Message + " - " + ex.InnerException;
                        lc.LogMessage("Error: " + note, LoggingLevel.Error);

                        // wait a little bit
                        Thread.Sleep(10);
                        // next loop iteration
                        continue;
                    }
                    // all is well
                    break;
                }


                // hook into the DC motor as specified
                try
                {
                    lc.LogMessage("motor - before hooking into motor: " + motor_number.ToString(), LoggingLevel.Information);
                    MotorHat.DCMotor motor = mh.GetMotor(motor_number);
                    lc.LogMessage("motor - before setting speed for motor: " + speed.ToString(), LoggingLevel.Information);
                    motor.SetSpeed(speed);
                    lc.LogMessage("motor - before creating direction command: " + direction, LoggingLevel.Information);
                    MotorHat.DCMotor.Command which_way = (MotorHat.DCMotor.Command)Enum.Parse(typeof(MotorHat.DCMotor.Command), direction);

                    // run he motor
                    lc.LogMessage("motor - before running the motor.", LoggingLevel.Information);
                    motor.Run(which_way);
                    lc.LogMessage("motor - before pausing the motor: " + how_long.ToString() + " milliseconds", LoggingLevel.Information);
                    await Task.Delay(how_long);

                    lc.LogMessage("motor - before stopping the motor.", LoggingLevel.Information);
                    motor.Run(MotorHat.DCMotor.Command.RELEASE);
                }
                catch (Exception ex)
                {
                    note = ex.Message + " - " + ex.InnerException;
                    lc.LogMessage("Error: " + note, LoggingLevel.Error);
                }
                // write an update to FMS
                var editRequest = fmserver.EditRequest(taskId);
                editRequest.AddField("flag_ready", "");

                editRequest.AddField("notes", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " - Done! " + Environment.NewLine + note + Environment.NewLine + notes);

                // execute the edit request
                var response = await editRequest.Execute();

                if (fmserver.lastErrorCode == 0)
                {
                    lc.LogMessage("Task finished.", LoggingLevel.Information);
                }
                else
                {
                    lc.LogMessage("Task failed. " + fmserver.lastErrorCode.ToString() + " - " + fmserver.lastErrorMessage, LoggingLevel.Error);
                }



                // don't log out, re-using the token for 14 minutes or so
                //await fmserver.Logout();
                //token = string.Empty;
                if (DateTime.Now >= tokenRecieved.AddMinutes(14))
                {
                    // don't really need to log out after 14 minutes, we can just re-use the same token

                    int logoutResponse = await fmserver.Logout();

                    token         = string.Empty;
                    tokenRecieved = DateTime.Now;
                    lc.LogMessage("Logging out of FMS.", LoggingLevel.Information);
                }
            }
        }