0

I am trying to create a flight using the DJI SDK via Virtual Sticks. I've worked out how to fly the drone in the direction of a GPS coordinate using the atan2 function to calculate the angle between two GPS Coordinates, then Yaw the drone to that angle and pitch to move in that direction.

I want to re-calculate that compass bearing, yaw and pitch every couple of seconds to account for wind and drift etc but I don't want to run it on the main thread in case it blocks UI. Or a UI interaction causes the timer not to fire and there is a missed calculation.

Should I use dispatch_source_set_timer in conjunction with GCD or is there a better method to achieve this and avoid memory leaks? Sample code below:

code sample taken from another question answer

// Create a dispatch source that'll act as a timer on the concurrent queue
dispatch_source_t dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
                                                          dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); 

// Setup params for creation of a recurring timer
double interval = 2.0;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 0);
uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC);
dispatch_source_set_timer(dispatchSource, startTime, intervalTime, 0);

// Attach the block you want to run on the timer fire
dispatch_source_set_event_handler(dispatchSource, ^{
    // code to calculate bearing and send Virtual Stick commands to yaw and pitch drone
});

// Start the timer
dispatch_resume(dispatchSource);

// ----

// When you want to stop the timer, you need to suspend the source
dispatch_suspend(dispatchSource);

// If on iOS5 and/or using MRC, you'll need to release the source too
dispatch_release(dispatchSource);

Brien Crean
  • 2,599
  • 5
  • 21
  • 46
  • 1
    Disclaimer - not familiar with dji-sdk. What you do appears fine if you do on a background thread but if you interact heavily with the UI the alternative here is NSTimer which is nice and easy to integrate with the UI. – skaak Aug 05 '20 at 06:57
  • Anyhow, with this approach maybe you can create your own queue just for this and schedule using dispatch_after and reschedule each time in the block, but hey, if it is working, don't fix it. – skaak Aug 05 '20 at 07:03
  • i would implement a proper NSThread subclass which comes with its own runloop and thread priority (actually same as GCD of course) you want and will just focus on doing what you want. Its an easier to handle code design because you have less mix up with existent written classes and your app can arrange how to handle the thread when it goes in background or similar. Apart from that i would suggest @skaak is right, using dispatching timers is easy and works fine. – Ol Sen Aug 05 '20 at 15:25

0 Answers0