1
0

InterfaceWaiter.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "admin/angel/InterfaceWaiter.h"
  16. #include "exception/Except.h"
  17. #include "memory/Allocator.h"
  18. #include "util/events/EventBase.h"
  19. #include "util/log/Log.h"
  20. #include "io/FileWriter.h"
  21. #include "util/events/Timeout.h"
  22. struct Context
  23. {
  24. struct EventBase* eventBase;
  25. struct Message* message;
  26. struct Allocator* alloc;
  27. struct Timeout* timeout;
  28. int timedOut;
  29. };
  30. static void timeout(void* vcontext)
  31. {
  32. struct Context* ctx = vcontext;
  33. ctx->timedOut = 1;
  34. EventBase_endLoop(ctx->eventBase);
  35. }
  36. static uint8_t receiveMessage(struct Message* message, struct Interface* iface)
  37. {
  38. struct Context* ctx = iface->receiverContext;
  39. ctx->message = Message_clone(message, ctx->alloc);
  40. Timeout_clearTimeout(ctx->timeout);
  41. EventBase_endLoop(ctx->eventBase);
  42. return 0;
  43. }
  44. struct Message* InterfaceWaiter_waitForData(struct Interface* iface,
  45. struct EventBase* eventBase,
  46. struct Allocator* alloc,
  47. struct Except* eh)
  48. {
  49. struct Context ctx = {
  50. .eventBase = eventBase,
  51. .alloc = alloc
  52. };
  53. struct Allocator* tempAlloc = Allocator_child(alloc);
  54. iface->receiverContext = &ctx;
  55. iface->receiveMessage = receiveMessage;
  56. ctx.timeout = Timeout_setTimeout(timeout, &ctx, 2000, eventBase, tempAlloc);
  57. EventBase_beginLoop(eventBase);
  58. iface->receiveMessage = NULL;
  59. Allocator_free(tempAlloc);
  60. if (ctx.timedOut) {
  61. Except_raise(eh, InterfaceWaiter_waitForData_TIMEOUT,
  62. "InterfaceWaiter Timed out waiting for data.");
  63. }
  64. Assert_true(ctx.message);
  65. return ctx.message;
  66. }