1 # events.nas - Generic objects for managing events
3 # Copyright (C) 2014 Anton Gomez Alvedro
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License as
7 # published by the Free Software Foundation; either version 2 of the
8 # License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 # The EventDispatcher is a simple helper object that keeps a list of listeners
22 # and allows a calling entity to send an "event" object to all subscribers.
24 # It is intended to be used internally by modules that want to offer a
25 # subscription interface so other modules can receive notifications.
26 # For an example of how to use it this way, check Nasal/FailureMgr
28 var EventDispatcher = (func {
31 var getid = func { global_id += 1 };
35 var m = { parents: [EventDispatcher] };
41 foreach(var id; keys(me._subscribers))
42 me._subscribers[id](event);
45 subscribe: func(callback) {
46 assert(typeof(callback) == "func");
49 me._subscribers[id] = callback;
53 unsubscribe: func(id) {
54 delete(me._subscribers, id);
61 # Stores messages in a circular buffer that then can be retrieved at any point.
62 # Messages are time stamped when pushed into the buffer, and the time stamp is
63 # kept by the message.
67 new: func (max_messages = 128, echo = 0) {
68 assert(max_messages > 1, "come on, lets be serious..");
70 var m = { parents: [LogBuffer] };
72 m.max_messages = max_messages;
73 m.buffer = setsize([], max_messages);
80 var stamp = getprop("/sim/time/gmt-string");
81 if (me.echo) print(stamp, " ", message);
83 me.buffer[me.wp] = { time: stamp, message: message };
85 if (me.wp == me.max_messages) {
96 # Returns a vector with all messages, starting with the oldest one.
97 # Each vector entry is a hash with the format:
98 # { time: <timestamp_str>, message: <the message> }
102 !me.wp ? me.buffer : me.buffer[me.wp:-1] ~ me.buffer[0:me.wp-1];
106 me.buffer[0:me.wp-1];