Debian Codegraph @

Nasal/emesary_mp_bridge.nas

raw
1 #---------------------------------------------------------------------------
2 #
3 # Title : EMESARY multiplayer bridge
4 #
5 # File Type : Implementation File
6 #
7 # Description : Bridges selected emesary notifications over MP
8 # : To send a message use a Transmitter with an object. That's all there is to it.
9 #
10 # References : http://chateau-logic.com/content/emesary-nasal-implementation-flightgear
11 #
12 # Author : Richard Harrison ([email protected])
13 #
14 # Creation Date : 04 April 2016
15 #
16 # Version : 4.8
17 #
18 # Copyright © 2016 Richard Harrison Released under GPL V2
19 #
20 #---------------------------------------------------------------------------*/
21
22 # Example of connecting an incoming and outgoing bridge (should reside inside an aircraft nasal file)
23 #
24 # var routedNotifications = [notifications.TacticalNotification.new()];
25 # var incomingBridge = emesary_mp_bridge.IncomingMPBridge.startMPBridge(routedNotifications);
26 # var outgoingBridge = emesary_mp_bridge.OutgoingMPBridge.new("F-15mp",routedNotifications);
27 #------------------------------------------------------------------
28 #
29 # NOTES:
30 # * Aircraft do not need to have both an incoming and outgoing bridge, but it is usual.
31 #
32 # * Only the notifications specified will be routed via the bridge.
33 #
34 # * Once routed a message will by default not be re-rerouted again by the outgoing bridge.
35 #
36 # * Transmit frequency and message lifetime may need to be tuned.
37 #
38 # * IsDistinct messages must be absolute and self contained as a later message will
39 # supercede any earlier ones in the outgoing queue (possibly prior to receipt)
40 #
41 # * Use the message type and ident to identify distinct messages
42 #
43 # * The outgoing 'port' is a multiplay/emesary/bridge index, however any available string property
44 # can be used by specifying it in the construction of the incoming or outgoing bridge.
45 # NOTE: This should not often be changed as it different versions of FG or model will
46 # have to use the same properties to be able to communicate
47 #
48 # * multiplay/emesary/bridge-type is used to identify the bridge that is in use. This is to
49 # protect against bridges being used for different purposes by different models.
50 #
51 # * The bridge-type property should contain an ID that identifies the purpose
52 # and thereore the message set that the bridge will be using.
53 #
54 # - ! is used as a seperator between the elements that are used to send the
55 # notification (typeid, sequence, notification)
56 # - There is an extra ! at the start of the message that is used to indicate protocol version.
57 # - ; is used to seperate serialzied elemnts of the notification
58
59 # General Notes
60 #----------------------------------------------------------------------
61 # Outgoing messages are sent in a scheduled manner, usually once per
62 # second, and each message has a lifetime (to allow for propogation to
63 # all clients over UDP). Clients will ignore messages that they have
64 # already received (based on the sequence id).
65
66 # The incoming bridge will usually be created part of the aircraft
67 # model file; it is important to understand that each AI/MP model will
68 # have an incoming bridge as each element in /ai/models needs its own
69 # bridge to keep up with the incoming sequence id. This scheme may not
70 # work properly as it relies on the model being loaded which may only
71 # happen when visible so it may be necessary to track AI models in a
72 # seperate instantiatable incoming bridge manager.
73 #
74 # The outgoing bridge would usually be created within the aircraft loading Nasal.
75 var EmesaryMPBridgeDefaultPropertyIndex=19;
76
77 var OutgoingMPBridge =
78 {
79 SeperatorChar : "!",
80 MessageEndChar : "~",
81 StartMessageIndex : 11,
82 DefaultMessageLifetimeSeconds : 10,
83 MPStringMaxLen: 128,
84
85 new: func(_ident, _notifications_to_bridge=nil, _mpidx=19, _root="", _transmitter=nil, _propertybase="emesary/bridge")
86 {
87 if (_transmitter == nil)
88 _transmitter = emesary.GlobalTransmitter;
89
90 print("OutgoingMPBridge created for "~_ident," mp=",_mpidx);
91 var new_class = emesary.Recipient.new("OutgoingMPBridge "~_ident);
92
93
94 if (_notifications_to_bridge == nil)
95 new_class.NotificationsToBridge = [];
96 else
97 new_class.NotificationsToBridge = _notifications_to_bridge;
98
99 new_class.NotificationsToBridge_Lookup = {};
100
101 foreach (var n ; new_class.NotificationsToBridge) {
102 print(" ",_ident," outwards bridge[",n,"] notifications of type --> ",n.NotificationType, " Id ",n.TypeId);
103 n.MessageIndex = OutgoingMPBridge.StartMessageIndex;
104 new_class.NotificationsToBridge_Lookup[n.TypeId] = n;
105 }
106 new_class.MPout = "";
107 new_class.MPidx = _mpidx;
108 new_class.MessageLifeTime = 10; # seconds
109 new_class.OutgoingList = [];
110 new_class.Transmitter = _transmitter;
111 new_class.TransmitRequired=0;
112 new_class.MpVariable = _root~"sim/multiplay/"~_propertybase~"["~new_class.MPidx~"]";
113 new_class.TransmitterActive = 0;
114 new_class.TransmitFrequencySeconds = 1;
115 new_class.trace = 0;
116 new_class.MPStringMaxLen = OutgoingMPBridge.MPStringMaxLen;
117
118 new_class.TransmitTimer =
119 maketimer(6, func
120 {
121 if (new_class.TransmitterActive)
122 new_class.Transmit();
123 else
124 new_class.TransmitEnd();
125
126 new_class.TransmitTimer.restart(new_class.TransmitFrequencySeconds);
127 });
128
129 new_class.Delete = func
130 {
131 if (me.Transmitter != nil) {
132 me.Transmitter.DeRegister(me);
133 me.Transmitter = nil;
134 }
135 };
136 new_class.AddMessage = func(m)
137 {
138 append(me.NotificationsToBridge, m);
139 };
140
141 #-------------------------------------------
142 # Receive override:
143 new_class.Receive = func(notification)
144 {
145 if (notification.FromIncomingBridge)
146 return emesary.Transmitter.ReceiptStatus_NotProcessed;
147
148 #print("Receive ",notification.NotificationType," ",notification.Ident);
149 for (var idx = 0; idx < size(me.NotificationsToBridge); idx += 1) {
150 if (me.NotificationsToBridge[idx].NotificationType == notification.NotificationType) {
151 me.NotificationsToBridge[idx].MessageIndex += 1;
152 notification.MessageExpiryTime = systime()+me.MessageLifeTime;
153 notification.Expired = 0;
154 notification.BridgeMessageId = me.NotificationsToBridge[idx].MessageIndex;
155 notification.BridgeMessageNotificationTypeId = me.NotificationsToBridge[idx].TypeId;
156 #
157 # The message key is a composite of the type and ident to allow for multiple senders
158 # of the same message type.
159 #print("Received ",notification.BridgeMessageNotificationTypeKey," expire=",notification.MessageExpiryTime);
160 me.AddToOutgoing(notification);
161 return emesary.Transmitter.ReceiptStatus_Pending;
162 }
163 }
164 return emesary.Transmitter.ReceiptStatus_NotProcessed;
165 };
166
167 new_class.AddToOutgoing = func(notification)
168 {
169 if (notification.IsDistinct) {
170 for (var idx = 0; idx < size(me.OutgoingList); idx += 1) {
171 if (me.trace)
172 print("Compare [",idx,"] qId=",me.OutgoingList[idx].GetBridgeMessageNotificationTypeKey() ," noti --> ",notification.GetBridgeMessageNotificationTypeKey());
173 if (me.OutgoingList[idx].GetBridgeMessageNotificationTypeKey() == notification.GetBridgeMessageNotificationTypeKey()) {
174 if (me.trace)
175 print(" --> Update ",me.OutgoingList[idx].GetBridgeMessageNotificationTypeKey() ," noti --> ",notification.GetBridgeMessageNotificationTypeKey());
176 me.OutgoingList[idx]= notification;
177 me.TransmitterActive = size(me.OutgoingList);
178 return;
179 }
180 }
181 } else
182 if (me.trace)
183 print("Not distinct, adding always");
184
185 if (me.trace)
186 print(" --> Added ",notification.GetBridgeMessageNotificationTypeKey());
187 append(me.OutgoingList, notification);
188 me.TransmitterActive = size(me.OutgoingList);
189 };
190 new_class.Transmit = func
191 {
192 var outgoing = "";
193 var cur_time=systime();
194 var first_time = 1;
195 me.OutgoingListNew = [];
196 for (var idx = 0; idx < size(me.OutgoingList); idx += 1) {
197 var sect = "";
198 var notification = me.OutgoingList[idx];
199
200 if (!notification.Expired and notification.MessageExpiryTime > cur_time) {
201 if (notification["sect"] == nil) {
202 # This is first time attempting to transmit this notification
203 var encval="";
204
205 var eidx = 0;
206 notification.Expired = 0;
207
208 foreach(var p ; notification.bridgeProperties()) {
209 var nv = p.getValue();
210 encval = encval ~ nv;
211 eidx += 1;
212 }
213 # !idx!typ!encv~
214 sect = sprintf("%s%s%s%s%s%s%s",
215 OutgoingMPBridge.SeperatorChar, emesary.BinaryAsciiTransfer.encodeInt(notification.BridgeMessageId,4),
216 OutgoingMPBridge.SeperatorChar, emesary.BinaryAsciiTransfer.encodeInt(notification.BridgeMessageNotificationTypeId,1),
217 OutgoingMPBridge.SeperatorChar, encval, OutgoingMPBridge.MessageEndChar);
218 } else {
219 # This notification has already been coded, but was previously not sent due to too little space.
220 sect = notification.sect;
221 }
222 if (size(outgoing) + size(sect) < me.MPStringMaxLen) {
223 outgoing = outgoing~sect;
224 } else {
225 if (first_time) {
226 print("Emesary: ERROR [",me.Ident,"] out of space for ",notification.NotificationType, " transmitted count=",idx, " queue size ",size(me.OutgoingList));
227 first_time = 0;
228 }
229 #notification.MessageExpiryTime = systime()+me.MessageLifeTime;
230 #break;
231 notification.sect = sect;
232 append(me.OutgoingListNew, notification);
233 }
234 } else {
235 notification.Expired = 1;
236 }
237 }
238 me.OutgoingList = me.OutgoingListNew;
239 me.TransmitterActive = size(me.OutgoingList);
240 setprop(me.MpVariable,outgoing);
241 };
242 new_class.TransmitEnd = func
243 {
244 if (getprop(me.MpVariable) != "") {
245 setprop(me.MpVariable,"");
246 }
247 };
248 new_class.Transmitter.Register(new_class);
249 new_class.TransmitTimer.restart(new_class.TransmitFrequencySeconds);
250 return new_class;
251 },
252
253 };
254
255
256 #
257 #
258 # one of these for each model instantiated in the model XML - it will
259 # route messages to
260 var IncomingMPBridge =
261 {
262 trace : 0,
263 new: func(_ident, _notifications_to_bridge=nil, _mpidx=19, _transmitter=nil, _propertybase="emesary/bridge")
264 {
265 if (_transmitter == nil)
266 _transmitter = emesary.GlobalTransmitter;
267
268 print("IncomingMPBridge created for "~_ident," mp=",_mpidx, " using Transmitter ",_transmitter.Ident, " with property base sim/multiplayer/"~_propertybase);
269
270 var new_class = emesary.Transmitter.new("IncominggMPBridge "~_ident);
271
272 if (_notifications_to_bridge == nil)
273 new_class.NotificationsToBridge = [];
274 else
275 new_class.NotificationsToBridge = _notifications_to_bridge;
276
277 new_class.NotificationsToBridge_Lookup = {};
278
279 foreach (var n ; new_class.NotificationsToBridge) {
280 print(" Incoming bridge notification type --> ",n.NotificationType);
281 var new_n = {parents: [n]};
282 new_n.IncomingMessageIndex = OutgoingMPBridge.StartMessageIndex;
283 new_class.NotificationsToBridge_Lookup[n.TypeId] = new_n;
284 }
285
286 new_class.MPout = "";
287 new_class.MPidx = _mpidx;
288 new_class.MPpropertyBase = _propertybase;
289 new_class.MessageLifeTime = OutgoingMPBridge.DefaultMessageLifetimeSeconds; # seconds
290 new_class.OutgoingList = [];
291 new_class.Transmitter = _transmitter;
292 new_class.MpVariable = "";
293
294 new_class.Connect = func(_root)
295 {
296 me.MpVariable = _root~"sim/multiplay/"~new_class.MPpropertyBase~"["~new_class.MPidx~"]";
297 me.CallsignPath = _root~"callsign";
298 me.PropertyRoot = _root;
299 me.mp_listener = setlistener(me.MpVariable, func(v)
300 {
301 #print("incoming ",getprop(me.CallsignPath)," -->",me.PropertyRoot," v=",v.getValue());
302 me.ProcessIncoming(v.getValue());
303 },0,0);
304 };
305 new_class.setprop = func(property, value){
306 if (IncomingMPBridge.trace == 2)
307 print("setprop ",new_class.PropertyRoot~property," = ",value);
308 setprop(new_class.PropertyRoot~property,value);
309 };
310 new_class.GetCallsign = func
311 {
312 return getprop(me.CallsignPath);
313 };
314 new_class.AddMessage = func(m)
315 {
316 append(me.NotificationsToBridge, m);
317 };
318
319 new_class.Remove = func
320 {
321 print("Emesary IncomingMPBridge Remove() ",me.Ident," Property: ",me.MpVariable);
322 me.Transmitter.DeRegister(me);
323 if (me["mp_listener"] != nil)
324 removelistener(me.mp_listener);
325 me.mp_listener = nil;
326 };
327
328 #-------------------------------------------
329 # Receive override:
330 new_class.ProcessIncoming = func(encoded_val)
331 {
332 if (encoded_val == "")
333 return;
334
335 if(right(encoded_val,1) != OutgoingMPBridge.MessageEndChar)
336 printf("Error: emesary.IncomingBridge.ProcessIncoming Missing endChar. From %s. Message=%s",me.GetCallsign(),encoded_val);
337
338 var encoded_notifications = split(OutgoingMPBridge.MessageEndChar, encoded_val);
339 for (var idx = 0; idx < size(encoded_notifications); idx += 1) {
340 if (encoded_notifications[idx] == "")
341 continue ;
342 # get the message parts
343 var encoded_notification = split(OutgoingMPBridge.SeperatorChar, encoded_notifications[idx]);
344 if (size(encoded_notification) < 4)
345 print("Error: emesary.IncomingBridge.ProcessIncoming bad msg ",encoded_notifications[idx]);
346 else {
347 var msg_idx = emesary.BinaryAsciiTransfer.decodeInt(encoded_notification[1],4,0).value;
348 var msg_type_id = emesary.BinaryAsciiTransfer.decodeInt(encoded_notification[2],1,0).value;
349 var bridged_notification = new_class.NotificationsToBridge_Lookup[msg_type_id];
350 if (bridged_notification == nil) {
351 print("Error: emesary.IncomingBridge.ProcessIncoming invalid type_id ",msg_type_id);
352 } else {
353 bridged_notification.FromIncomingBridge = 1;
354 bridged_notification.Callsign = me.GetCallsign();
355 if(IncomingMPBridge.trace>1)
356 print("ProcessIncoming callsign=",bridged_notification.Callsign," ",me.PropertyRoot, " msg_type=",msg_type_id," idx=",msg_idx, " bridge_idx=",bridged_notification.IncomingMessageIndex);
357 if (msg_idx > bridged_notification.IncomingMessageIndex) {
358 if(IncomingMPBridge.trace==1)
359 print("ProcessIncoming callsign=",bridged_notification.Callsign," ",me.PropertyRoot, " msg_type=",msg_type_id," idx=",msg_idx, " bridge_idx=",bridged_notification.IncomingMessageIndex);
360 var msg_body = encoded_notification[3];
361 if (IncomingMPBridge.trace > 2)
362 print("received idx=",msg_idx," ",msg_type_id,":",bridged_notification.NotificationType);
363
364 # populate fields
365 var bridgedProperties = bridged_notification.bridgeProperties();
366 var msglen = size(msg_body);
367 if (IncomingMPBridge.trace > 2)
368 print("Process ",msg_body," len=",msglen, " BPsize = ",size(bridgedProperties));
369 var pos = 0;
370 for (var bpi = 0; bpi < size(bridgedProperties); bpi += 1) {
371 if (pos < msglen) {
372 if (IncomingMPBridge.trace > 2)
373 print("dec: pos ",pos);
374 var bp = bridgedProperties[bpi];
375 dv = bp.setValue(msg_body, me, pos);
376 if (IncomingMPBridge.trace > 2)
377 print(" --> next pos ", dv.pos);
378
379 if (dv.pos == pos or dv.pos > msglen)
380 break;
381 pos = dv.pos;
382 } else {
383 print("Error: emesary.IncomingBridge.ProcessIncoming: [",bridged_notification.NotificationType,"] supplementary encoded value at position ",bpi);
384 break;
385 }
386 }
387 # maybe extend the bridge to allow certain notifications to only be routed to a specific player;
388 # i.e.
389 # (notification.Callsign == nil or notification.Callsign == getprop("/sim/multiplay/callsign"))
390
391 if (bridged_notification.Ident == "none")
392 bridged_notification.Ident = "mp-bridge";
393
394 bridged_notification.IncomingMessageIndex = msg_idx;
395 me.Transmitter.NotifyAll(bridged_notification);
396 }
397 }
398 }
399 }
400 }
401 foreach (var n; new_class.NotificationsToBridge) {
402 print("IncomingBridge: ",n.NotificationType);
403 }
404 return new_class;
405 },
406 connectIncomingBridge : func(path, notification_list, mpidx, transmitter, _propertybase){
407 var incomingBridge = emesary_mp_bridge.IncomingMPBridge.new(path, notification_list, mpidx, transmitter, _propertybase);
408
409 incomingBridge.Connect(path~"/");
410 if (me.incomingBridgeList[path] == nil) {
411 me.incomingBridgeList[path] = [incomingBridge];
412 } else {
413 append(me.incomingBridgeList[path],incomingBridge);
414 }
415 return incomingBridge;
416 },
417
418 #
419 # Each multiplayer object will have its own incoming bridge. This is necessary to allow message ID
420 # tracking (as the bridge knows which messages have been already processed)
421 # Whenever a client connects over MP a new bridge is instantiated
422 startMPBridge : func(notification_list, mpidx=19, transmitter=nil, _propertybase="emesary/bridge")
423 {
424 me.incomingBridgeList = {};
425
426 #
427 # Create bridge whenever a client connects
428 #
429 setlistener("/ai/models/model-added", func(v)
430 {
431 # Model added will be eg: /ai[0]/models[0]/multiplayer[0]
432 var path = v.getValue();
433
434 # Ensure we only handle multiplayer elements
435 if (find("/multiplayer",path) > 0) {
436 var callsign = getprop(path~"/callsign");
437 print("Creating Emesary MPBridge for ",path);
438 if (callsign == "" or callsign == nil)
439 callsign = path;
440
441 me.connectIncomingBridge(path, notification_list, mpidx, transmitter, _propertybase);
442 }
443 });
444
445 #
446 # when a client disconnects remove the associated bridge.
447 #
448 setlistener("/ai/models/model-removed", func(v){
449 var path = v.getValue();
450 var bridges = me.incomingBridgeList[path];
451 if (bridges != nil) {
452 foreach(bridge;bridges) {
453 bridge.Remove();
454 # print("Bridge removed for ",v.getValue());
455 }
456 me.incomingBridgeList[path] = nil;
457 }
458 });
459 },
460 };