1
0

InterfaceWaiter.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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_throw(eh, "InterfaceWaiter Timed out waiting for data.");
  62. }
  63. Assert_true(ctx.message);
  64. return ctx.message;
  65. }