Query.pm.svn-base
上传用户:market2
上传日期:2018-11-18
资源大小:18786k
文件大小:2k
源码类别:

外挂编程

开发平台:

Windows_Unix

  1. ##########################################################
  2. #  OpenKore - Bus System
  3. #  Bus query object
  4. #
  5. #  This software is open source, licensed under the GNU General Public
  6. #  License, version 2.
  7. #  Basically, this means that you're allowed to modify and distribute
  8. #  this software. However, if you distribute modified versions, you MUST
  9. #  also distribute the source code.
  10. #  See http://www.gnu.org/licenses/gpl.html for the full license.
  11. #
  12. #  $Revision$
  13. #  $Id$
  14. #
  15. #########################################################################
  16. package Bus::Query;
  17. use strict;
  18. use Time::HiRes qw(time);
  19. use Modules 'register';
  20. # Query state constants.
  21. use constant {
  22. WAITING => 1,
  23. DONE    => 2,
  24. TIMEOUT => 3
  25. };
  26. # See $BusClient->query() for options allowed for the constructor.
  27. sub new {
  28. my ($class, $args) = @_;
  29. my $self = bless $args, $class;
  30. # Invariant: if $state == WAITING: defined($receivedEvent)
  31. $self->{receivedEvent} = $self->{bus}->onMessageReceived->add($self, &messageReceived);
  32. $self->{replies} = [];
  33. $self->{state} = WAITING;
  34. $self->{start_time} = time;
  35. $self->{timeout} ||= 5;
  36. return $self;
  37. }
  38. sub DESTROY {
  39. my ($self) = @_;
  40. if ($self->{receivedEvent}) {
  41. $self->{bus}->onMessageReceived->remove($self->{receivedEvent});
  42. }
  43. }
  44. sub getState {
  45. my ($self) = @_;
  46. if ($self->{state} == WAITING) {
  47. if (time - $self->{start_time} > $self->{timeout}) {
  48. # Timeout for query reached.
  49. $self->{bus}->onMessageReceived->remove($self->{receivedEvent});
  50. delete $self->{receivedEvent};
  51. if (@{$self->{replies}} > 0) {
  52. $self->{state} = DONE;
  53. return DONE;
  54. } else {
  55. $self->{state} = TIMEOUT;
  56. return TIMEOUT;
  57. }
  58. } else {
  59. return WAITING;
  60. }
  61. } else {
  62. return $self->{state};
  63. }
  64. }
  65. sub getReply {
  66. my ($self) = @_;
  67. if (@{$self->{replies}}) {
  68. my $message = shift @{$self->{replies}};
  69. return @{$message};
  70. } else {
  71. return undef;
  72. }
  73. }
  74. sub messageReceived {
  75. my ($self, undef, $message) = @_;
  76. if ($self->{state} == WAITING && $message->{args}{SEQ} == $self->{seq} && $message->{args}{IRY}) {
  77. # A reply has been received.
  78. push @{$self->{replies}}, [$message->{messageID}, $message->{args}];
  79. if (!$self->{collectAll}) {
  80. # This query needs only one reply, so stop immediately.
  81. $self->{bus}->onMessageReceived->remove($self->{receivedEvent});
  82. delete $self->{receivedEvent};
  83. $self->{state} = DONE;
  84. }
  85. }
  86. }
  87. 1;