組み込み(Arduino)からLinux/Windowsまで様々な環境で汎用的に使える協調型マルチスタスク・ライブラリを作ってみた。最近似たような物ばかり作ってるような気がするが気にしないでほしい。(笑)
【過去の投稿】
1.シンプルすぎる汎用C++タスクスケジューラー(CScheduler)を作ってみた。
2.Micro Core Library for Arduino
前回投稿のMicro Core Library for Arduino はハードウェアのタイマー割り込みをサポートしたために少し複雑になってしまったがタスク同期のタイムアウト機能についてはタイマー割り込みで起床したとしてもカレントタスクの自発的なタスク切り替え(yield)がない限りそのタスクが実行されないことからタイムアウト判断はタスク切り替え毎のポーリング判定でも問題ないという結論に落ち着いた。但し、アラームクラスのタイマー割り込みハンドラの呼び出しタイミングについてはタスク切り替えタイミングに依存してかなりズレてしまうことや処理遅延に伴う時間系の破綻がないという前提ではあるが。
今回のライブラリはLinux/Windows にも対応しタイムアウトを含む全機能が使えるようになっている。少し不思議に思われるかもしれないのはOSスレッド対応している点かも。このライブラリではハードウェア割り込みからタスク起床が可能となっている。組み込み用途であればハードウェア割り込みが使えるがOSの場合は直接ハードウェア割り込みを利用することが出来ない。そのためハードウェア割り込みの代わりにスレッドを使えるようにしてみた。
OSのスレッド上でさらにマルチタスク(サブ・スレッド?)なんて意味があるのかどうか分からないが、組み込み環境と同じライブラリがPCでも動作するのでマルチタスク・アプリのクロス開発環境として利用するなんてのもありかも。PC環境のほうがデバッグが楽だしね。
ちなみに、MinGW32は問題ないがMinGW64はsetjmp/longjmpの実装の問題により誤動作することに注意。詳しいことはわからないがWIN64特有の特殊なスタッフレームに対応できないという致命的な問題があるらしい。
【サンプル・プログラム】
※STACK_SIZEは実行環境に合わせて適切な調整が必要。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/* * Task Sample Program * */ #include <stdio.h> #include "task.h" #define STACK_SIZE TASK_STACK_SIZE(4096) // Windows or Linux //#define STACK_SIZE TASK_STACK_SIZE(128) // Embedded(avr,...) void task0(void *arg) { (void)arg; while (1) { printf("task0\n"); Task::sleep(1000); } } void task1(void *arg) { (void)arg; while (1) { printf("task1\n"); Task::sleep(1000); } } void setup(void) { Task::begin(STACK_SIZE); // setup main task stack size Task::start(task0, 0, -STACK_SIZE); Task::start(task1, 0, -STACK_SIZE); } void loop(void) { Task::yield(); } #if !defined(ARDUINO) int main(int argc, char **argv) { setup(); while (1) loop(); } #endif |
【ダウンロード】
u-kernel.zip (Eclipse Project)
arduino-u-kernel.zip (Arduino Library)
【ライブラリ】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
/* task.h - Smallest Non Preemptive Multi Task Library for Embedded System Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <setjmp.h> #include "hardware.h" #include "alarm.h" #define TASK_STACK_SIZE(n) ((n) + Task::TCB_SIZE) class Task : protected Hardware { public: typedef void (*func_t)(void *arg); protected: typedef struct tcb { struct tcb *next; jmp_buf context; void *alloc; void *arg; func_t start; } tcb_t; typedef struct { Alarm alarm; size_t save; bool retval; } ctrl_t; static void enqueue0(tcb_t *tcb); static void enqueue1(tcb_t *tcb); static tcb_t *dequeue(void); static void switching(void); static void dispatch(void); public: static const int TCB_SIZE = sizeof(tcb_t); static void begin(size_t size); static bool start(func_t func, void *arg, int size, void *stack = 0); static void stop(void); static bool yield(void); static size_t current(void); static void sleep(int32_t ms, uint8_t busyLoop = 0); static void sleepMicroseconds(int32_t us, uint8_t busyLoop = 0); static void delay(uint32_t ms, uint8_t busyLoop = 0); static void delayMicroseconds(uint32_t us, uint8_t busyLoop = 0); private: static tcb_t *_disp; static tcb_t *_curr; static tcb_t *_head; static tcb_t *_tail[2]; static size_t _used; }; class Sync : protected Task { public: Sync(void); bool sleep(int32_t timeout = -1); size_t wakeup(size_t task = 0); protected: bool sleep(ctrl_t& ctrl); static bool timeup(Alarm& alarm); tcb_t *_head; tcb_t *_tail; }; class Mutex : protected Sync { public: Mutex(void); bool lock(int32_t timeout = -1); void unlock(void); protected: size_t _owner; size_t _count; }; class Sem : protected Sync { public: Sem(size_t limit = (size_t)-1, size_t count = 0); bool wait(size_t count = 1, int32_t timeout = -1); void post(size_t count = 1); protected: size_t _limit; size_t _count; size_t _wait; }; class Event : protected Sem { protected: Event(void); bool wait(int32_t timeout = -1); void signal(void); }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
/* task.cpp - Smallest Non Preemptive Multi Task Library for Embedded System Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdlib.h> #if !defined(alloca) #include <alloca.h> #endif #include "task.h" Task::tcb_t *Task::_disp; Task::tcb_t *Task::_curr; Task::tcb_t *Task::_head; Task::tcb_t *Task::_tail[]; size_t Task::_used; void Task::begin(size_t size) { /* Registration of main task */ static tcb_t tcb; _curr = &tcb; _used = size; } bool Task::start(func_t func, void *arg, int size, void *stack) { tcb_t *tcb; if (size < 0) { /* Use the current stack area */ size_t n = - size; size = _used; stack = 0; _used += n; } else if (stack) { /* Set the stack area to the variable area */ size = (char *)&tcb - (char *)stack - size + sizeof(*tcb); stack = 0; } else { /* Dynamically allocate stack area */ stack = malloc(size); if (!stack) return false; size = (char *)&tcb - (char *)stack - size + sizeof(*tcb); } tcb = (tcb_t *)alloca(size); tcb->alloc = stack; tcb->arg = arg; tcb->start = func; enqueue0(tcb); if (setjmp(tcb->context)) { _curr = _disp; _curr->start(_curr->arg); stop(); } return true; } void Task::stop(void) { if (_curr->start) { if (_curr->alloc) free(_curr->alloc); dispatch(); } } void Task::enqueue0(tcb_t *tcb) { size_t save = disableAndSaveInterrupts(); if (_tail[0]) { tcb->next = _tail[0]->next; _tail[0] = (_tail[0]->next = tcb); } else { tcb->next = _head; _tail[0] = (_head = tcb); } restoreInterrupts(save); } void Task::enqueue1(tcb_t *tcb) { size_t save = disableAndSaveInterrupts(); (_tail[1] = *(_tail[1] ? &_tail[1]->next : (_tail[0] ? &_tail[0]->next : &_head)) = tcb)->next = 0; restoreInterrupts(save); } Task::tcb_t *Task::dequeue(void) { tcb_t *tcb; size_t save = disableAndSaveInterrupts(); if ((tcb = _head)) { if (_head == _tail[0]) _tail[0] = 0; else if (_head == _tail[1]) _tail[1] = 0; _head = _head->next; } restoreInterrupts(save); return tcb; } size_t Task::current(void) { return (size_t)_curr; } bool Task::yield(void) { AlarmTimer.handle(); enqueue1(_curr); switching(); return !_curr->start; } void Task::switching(void) { if (!setjmp(_curr->context)) dispatch(); _curr = _disp; } void Task::dispatch(void) { while (1) { if ((_disp = dequeue())) longjmp(_disp->context, 1); idle(); AlarmTimer.handle(); } } void Task::sleep(int32_t ms, uint8_t busyLoop) { sleepMicroseconds(ms * 1000L, busyLoop); } void Task::sleepMicroseconds(int32_t us, uint8_t busyLoop) { uint32_t t = micros(); if (us > busyLoop) { Sync sync; sync.sleep(us -= busyLoop); t += us; } if (busyLoop) { while (micros() - t < busyLoop) continue; } } void Task::delay(uint32_t ms, uint8_t busyLoop) { delayMicroseconds(ms * 1000UL, busyLoop); } void Task::delayMicroseconds(uint32_t us, uint8_t busyLoop) { uint32_t t = micros(); if (us > busyLoop) { us -= busyLoop; while (micros() - t < us) yield(); t += us; } if (busyLoop) { while (micros() - t < busyLoop) continue; } } Sync::Sync(void) : _head(0) , _tail(0) { } bool Sync::timeup(Alarm& alarm) { if (((Sync *)alarm.param(0))->wakeup((size_t)alarm.param(1))) *(bool *)alarm.param(2) = false; return false; } bool Sync::sleep(ctrl_t& ctrl) { tcb_t *tcb = (tcb_t *)current(); (_tail = *(_tail ? &_tail->next : &_head) = tcb)->next = 0; restoreInterrupts(ctrl.save); ctrl.alarm.param(0, this); ctrl.alarm.param(1, tcb); ctrl.alarm.param(2, &ctrl.retval); ctrl.alarm.handler(timeup); AlarmTimer.start(ctrl.alarm); switching(); return ctrl.retval; } bool Sync::sleep(int32_t timeout) { if (timeout == 0) return false; ctrl_t ctrl; ctrl.alarm.interval(timeout); ctrl.retval = true; ctrl.save = disableAndSaveInterrupts(); return sleep(ctrl); } size_t Sync::wakeup(size_t task) { tcb_t *tcb = 0; size_t save = disableAndSaveInterrupts(); if (task) { for (tcb_t **p = &_head; *p; p = &(*p)->next) { if (*p == (tcb_t *)task) { if (!(*p = (*p)->next)) _tail = (p == &_head ? 0 : (tcb_t *)p); tcb = (tcb_t *)task; break; } } } else _head = ((tcb = _head) != _tail ? _head->next : _tail = 0); restoreInterrupts(save); if (tcb) { AlarmTimer.cancel(1, tcb); enqueue0(tcb); } return (size_t)tcb; } Mutex::Mutex(void) : _owner(0) { } bool Mutex::lock(int32_t timeout) { ctrl_t ctrl; ctrl.alarm.interval(timeout); ctrl.retval = true; ctrl.save = disableAndSaveInterrupts(); size_t task = current(); if (!_owner) { _owner = task; _count = 1; } else if (_owner == task) ++_count; else if (timeout == 0) ctrl.retval = false; else return sleep(ctrl); restoreInterrupts(ctrl.save); return ctrl.retval; } void Mutex::unlock(void) { size_t save = disableAndSaveInterrupts(); if (_owner == current()) { if (--_count == 0) { _owner = wakeup(); _count = 1; } } restoreInterrupts(save); } Sem::Sem(size_t limit, size_t count) : _limit(limit) , _count(count) , _wait(0) { } bool Sem::wait(size_t count, int32_t timeout) { ctrl_t ctrl; ctrl.alarm.interval(timeout); ctrl.retval = true; ctrl.save = disableAndSaveInterrupts(); if ((count == 0) || (count > _limit)) ctrl.retval = false; else if (!_wait && (_count >= count)) _count -= count; else if (timeout == 0) ctrl.retval = false; else { ++_wait; ((tcb_t *)current())->arg = (void *)count; sleep(ctrl); disableAndSaveInterrupts(); --_wait; while (_head) { count = (size_t)_head->arg; if (_count < count) break; _count -= count; wakeup(); } } restoreInterrupts(ctrl.save); return ctrl.retval; } void Sem::post(size_t count) { size_t save = disableAndSaveInterrupts(); if (count && (count + _count <= _limit)) { _count += count; if (_head) { count = (size_t)_head->arg; if (_count >= count) { _count -= count; wakeup(); } } } restoreInterrupts(save); } Event::Event(void) : Sem(1) { } bool Event::wait(int32_t timeout) { return Sem::wait(1, timeout); } void Event::signal(void) { Sem::post(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
/* fifo.h - First-In First-Out Buffer Template Library Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <string.h> #include "task.h" #define FIFO_NO_WAIT 0 #define FIFO_INFINITE_WAIT -1 #define FIFO_OVERWRITE -2 template<typename T, size_t SIZE> class Fifo : protected Sync { private: size_t _wridx; size_t _rdidx; size_t _count; size_t _losts; T _buffer[SIZE]; void read(T *buf, size_t count) { _count -= count; if (_rdidx + count > SIZE) { size_t n = SIZE - _rdidx; memcpy(buf, _buffer + _rdidx, n * sizeof(T)); buf += n; count -= n; _rdidx = 0; } memcpy(buf, _buffer + _rdidx, count * sizeof(T)); _rdidx += count; } void write(const T *buf, size_t count) { _count += count; if (_wridx + count > SIZE) { size_t n = SIZE - _wridx; memcpy(_buffer + _wridx, buf, n * sizeof(T)); buf += n; count -= n; _wridx = 0; } memcpy(_buffer + _wridx, buf, count * sizeof(T)); _wridx += count; } public: Fifo(void) : _wridx(0) , _rdidx(0) , _count(0) , _losts(0) { } size_t available(void) { size_t save = disableAndSaveInterrupts(); size_t rv = _count; restoreInterrupts(save); return rv; } size_t availableForWrite(void) { return SIZE - available(); } size_t losts(void) { size_t save = disableAndSaveInterrupts(); size_t rv = _losts; _losts = 0; restoreInterrupts(save); return rv; } bool get(T *item, size_t count = 1, int32_t timeout = FIFO_INFINITE_WAIT) { size_t n, rv = 0; ctrl_t ctrl; while (count) { ctrl.alarm.interval(timeout); ctrl.retval = true; ctrl.save = disableAndSaveInterrupts(); if (_count) { n = count < _count ? count : _count; read(item, n); restoreInterrupts(ctrl.save); item += n; count -= n; rv += n; } else { if (timeout == FIFO_NO_WAIT) restoreInterrupts(ctrl.save); else if (sleep(ctrl)) continue; break; } } return rv; } size_t put(const T *item, size_t count = 1, int32_t timeout = FIFO_INFINITE_WAIT) { size_t n, rv = 0; Alarm alarm; alarm.interval(timeout); while (count) { size_t save = disableAndSaveInterrupts(); n = SIZE - _count; if (n) { if (count < n) n = count; write(item, n); restoreInterrupts(save); wakeup(); item += n; count -= n; rv += n; alarm.interval(timeout); } else if (timeout == FIFO_OVERWRITE) { n = _count < count ? _count : count; _count -= n; _losts += n; if ((_rdidx += n) >= SIZE) _rdidx -= SIZE; restoreInterrupts(save); } else { restoreInterrupts(save); if (timeout == FIFO_NO_WAIT) break; else if ((timeout > FIFO_NO_WAIT) && alarm.expire()) break; yield(); } } return rv; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
/* alarm.h - Alarm Library for Arduino Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include "hardware.h" class Alarm : protected Hardware { public: typedef bool (*handler_t)(Alarm& alarm); Alarm& interval(int32_t interval, bool fromnow = true); int32_t interval(void); Alarm& handler(handler_t handler); handler_t handler(void); Alarm& param(uint8_t num, void *val); void *param(uint8_t num); bool expire(void); protected: friend class AlarmClass; Alarm *_next; uint32_t _alarm; int32_t _interval; handler_t _handler; void *_params[4]; }; class AlarmClass : protected Hardware { public: AlarmClass(void); bool start(Alarm& alarm); void cancel(Alarm& alarm); void cancel(uint8_t num, void *arg); void handle(void); protected: bool add(Alarm& alarm); private: bool timeup(void); friend void AlarmClass_timeup(void); Alarm *_alarm_list; bool _poll_mode; }; extern AlarmClass AlarmTimer; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
/* alarm.cpp - Alarm Library for Arduino Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stddef.h> #include "alarm.h" #define lengthof(a) (sizeof(a)/sizeof(a[0])) AlarmClass AlarmTimer; Alarm& Alarm::interval(int32_t interval, bool fromnow) { if (fromnow) _alarm = micros() + interval; _interval = interval; return *this; } int32_t Alarm::interval(void) { return _interval; } Alarm& Alarm::handler(Alarm::handler_t handler) { _handler = handler; return *this; } Alarm::handler_t Alarm::handler(void) { return _handler; } Alarm& Alarm::param(uint8_t num, void *val) { if (num < lengthof(_params)) _params[num] = val; return *this; } void *Alarm::param(uint8_t num) { return num < lengthof(_params) ? _params[num] : NULL; } bool Alarm::expire(void) { if ((int32_t)(micros() - _alarm) < 0) return false; _alarm += _interval; return true; } AlarmClass::AlarmClass(void) : _alarm_list(nullptr) { _poll_mode = !setupAlarmTimer(); } bool AlarmClass::start(Alarm& alarm) { if ((alarm._interval < 1) || !alarm._handler) return false; size_t save = disableAndSaveInterrupts(); if (add(alarm) && !_poll_mode) startAlarmTimer(_alarm_list->_alarm - micros()); restoreInterrupts(save); return true; } void AlarmClass::cancel(Alarm& alarm) { size_t save = disableAndSaveInterrupts(); for (Alarm **p = &_alarm_list; *p; p = &(*p)->_next) { if (*p == &alarm) { *p = (*p)->_next; break; } } restoreInterrupts(save); } void AlarmClass::cancel(uint8_t num, void *arg) { if ((num < lengthof(Alarm::_params)) && arg) { size_t save = disableAndSaveInterrupts(); for (Alarm **p = &_alarm_list; *p; p = &(*p)->_next) { if ((*p)->_params[num] == arg) { *p = (*p)->_next; break; } } restoreInterrupts(save); } } bool AlarmClass::add(Alarm& alarm) { Alarm **p; for (p = &_alarm_list; *p && ((int32_t)((*p)->_alarm - alarm._alarm) <= 0); p = &(*p)->_next) continue; alarm._next = *p; *p = &alarm; return p == &_alarm_list; } bool AlarmClass::timeup(void) { Alarm *p = NULL; while (_alarm_list) { int32_t t = _alarm_list->_alarm - micros(); if (p || (t > 0)) { if (!_poll_mode) startAlarmTimer(t); return true; } _alarm_list = (p = _alarm_list)->_next; if (p->_handler(*p)) { p->_alarm += p->_interval; if (!add(*p)) p = NULL; } else p = NULL; } return false; } void AlarmClass::handle(void) { if (_poll_mode) { size_t save = disableAndSaveInterrupts(); timeup(); restoreInterrupts(save); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/* hardware.h - Hardware Library Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once #include <stddef.h> #include <stdint.h> #include <stdbool.h> class Hardware { public: Hardware(void); static uint32_t micros(void); static size_t disableAndSaveInterrupts(void); static void restoreInterrupts(size_t save); static void idle(void); protected: /* For Alarm Class */ static bool setupAlarmTimer(void); static void startAlarmTimer(int32_t interval); }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
/* hardware.cpp - Hardware Library for ATSAMD21 Copyright (c) 2022 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "hardware.h" /********************************************************** * ARDUINO **********************************************************/ #if defined(ARDUINO) #include "Arduino.h" /* * ESP32 */ #if defined(ESP32) Hardware::Hardware(void) { } uint32_t Hardware::micros(void) { return ::micros(); } size_t Hardware::disableAndSaveInterrupts(void) { return portSET_INTERRUPT_MASK_FROM_ISR(); } void Hardware::restoreInterrupts(size_t save) { portCLEAR_INTERRUPT_MASK_FROM_ISR(save); } void Hardware::idle(void) { portENABLE_INTERRUPTS(); } bool Hardware::setupAlarmTimer(void) { return false; } void Hardware::startAlarmTimer(int32_t interval) { } /* * Generic Arduino */ #else static unsigned char nest; Hardware::Hardware(void) { } uint32_t Hardware::micros(void) { return ::micros(); } size_t Hardware::disableAndSaveInterrupts(void) { noInterrupts(); return nest++; } void Hardware::restoreInterrupts(size_t save) { if ((nest = save) == 0) interrupts(); } void Hardware::idle(void) { interrupts(); } bool Hardware::setupAlarmTimer(void) { return false; } void Hardware::startAlarmTimer(int32_t interval) { } #endif /********************************************************** * LINUX **********************************************************/ #elif defined(__linux__) #include <time.h> #include <pthread.h> static pthread_mutex_t mut = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; Hardware::Hardware(void) { } uint32_t Hardware::micros(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC_RAW, &ts); return (size_t)ts.tv_sec * 1000000 + (ts.tv_nsec / 1000); } size_t Hardware::disableAndSaveInterrupts(void) { pthread_mutex_lock(&mut); return 0; } void Hardware::restoreInterrupts([[maybe_unused]] size_t save) { pthread_mutex_unlock(&mut); } void Hardware::idle(void) { } bool Hardware::setupAlarmTimer(void) { return false; } void Hardware::startAlarmTimer(int32_t interval) { } /********************************************************** * WINDOWS **********************************************************/ #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> static CRITICAL_SECTION crit; static LARGE_INTEGER freq; Hardware::Hardware(void) { InitializeCriticalSection(&crit); QueryPerformanceFrequency(&freq); } uint32_t Hardware::micros(void) { LARGE_INTEGER now; QueryPerformanceCounter(&now); return now.QuadPart * 1000000U / freq.QuadPart; } size_t Hardware::disableAndSaveInterrupts(void) { EnterCriticalSection(&crit); return 0; } void Hardware::restoreInterrupts([[maybe_unused]] size_t save) { LeaveCriticalSection(&crit); } void Hardware::idle(void) { } bool Hardware::setupAlarmTimer(void) { return false; } void Hardware::startAlarmTimer(int32_t interval) { } #endif |