Commits

Ginés Martínez Sánchez committed 500be0a Draft

writting inter event example

Comments (0)

Files changed (10)

ginsfsm/c_sock.py

 GObj for manage socket events.
 
 .. autoclass:: GSock
-    :members: start_up, get_next_dst
+    :members: start_up, get_next_dst, get_peername, get_sockname
 
 """
 
         self.rxed_bytes = 0
         self.__trace_dump = False
 
+        self.socket = None
         self.connected = False
-        self.addr = None
-        self.socket = None
-        self.sockname = None
+        self.addr = None  # remote address to which the socket is connected
+        self.sockname = None  # the socket’s own address
 
         self._socket_map = {}   # socket_map set by gaplic. Dict {fd:Gobj}
         self._impl_poll = None  # _poll(),epoll() implementation
     def is_disconnected(self):
         return not self.connected
 
+    def get_peername(self):
+        """ Remote address to which the socket is connected
+        """
+        return self.addr
+
+    def get_sockname(self):
+        """ the socket’s own address
+        """
+        return self.sockname
+
     def remove_socket(self):
         fd = self._fileno
         self._socket_map.pop(fd, None)

ginsfsm/examples/inter_event/ap1_banco/banco/ac_cuentas.py

+# -*- encoding: utf-8 -*-
+""" Cuentas GObj
+
+.. autoclass:: Cuentas
+    :members: start_up
+
+"""
+
+from ginsfsm.gobj import GObj
+
+
+def ac_cuenta(self, event):
+    """ Event attributes:
+        * :attr:`user_name`: user name.
+
+    """
+    user_name = event.user_name
+    if not user_name in self.cuentas:
+        self.cuentas[user_name] = 0
+
+    if event.__intra_event__:
+        origin_gaplic = event.__intra_event__.origin_gaplic
+        origin_role = event.__intra_event__.origin_role
+        origin_gobj = event.__intra_event__.origin_gobj
+
+        self.gaplic.send_event_outside(
+            origin_gaplic,  # gaplic_name
+            origin_role,  # role
+            origin_gobj,  # gobj_name
+            'EV_CUENTA_ACK',  # event_name
+            self,  # subscriber_gobj
+        )
+
+
+CUENTAS_FSM = {
+    'event_list': (
+        'EV_CUENTA:top input',
+        'EV_CUENTA_ACK:top output',
+    ),
+    'state_list': (
+        'ST_IDLE',
+    ),
+    'machine': {
+        'ST_IDLE':
+        (
+            ('EV_CUENTA',      ac_cuenta,      None),
+        ),
+    }
+}
+
+CUENTAS_GCONFIG = {
+    'subscriber': [
+        None, None, 0, None,
+        "subcriber of all output-events."
+        "Default is ``None``, i.e., the parent"
+    ],
+}
+
+
+class Cuentas(GObj):
+    """  Cuentas GObj.
+    A Sample gobj.
+
+    .. ginsfsm::
+       :fsm: CUENTAS_FSM
+       :gconfig: CUENTAS_GCONFIG
+
+    *Input-Events:*
+        * :attr:`'EV_CUENTA'`: sample input event.
+
+          Event attributes:
+
+              * ``data``: sample event attribute.
+
+    *Output-Events:*
+        * :attr:`'EV_CUENTA_ACK'`: sample output event.
+
+          Event attributes:
+
+              * ``data``: sample event attribute.
+
+    """
+    def __init__(self):
+        GObj.__init__(self, CUENTAS_FSM, CUENTAS_GCONFIG)
+        self.cuentas = {}
+
+    def start_up(self):
+        """ Initialization zone.
+        """
+        if self.config.subscriber:
+            self.subscribe_event(None, self.config.subscriber)

ginsfsm/examples/inter_event/ap1_banco/banco/main.py

 )
 from ginsfsm.protocols.wsgi.server.c_wsgi_server import GWsgiServer
 from banco.pyramid_app import pyramid_wsgi_app
+from banco.ac_cuentas import Cuentas
 
 
 #===============================================================
         ga,
         application=application,
     )
+    ga.create_gobj(
+        'cuentas',
+        Cuentas,
+        ga,
+        __unique_name__=True,
+    )
     print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
     print("<<<     To test the application, go to http://localhost:8001   >>>")
     print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")

ginsfsm/examples/inter_event/ap1_banco/banco/pyramid_app/static/cliente.js

     /********************************************
      *      Auxiliary
      ********************************************/
-    function escriba_algo(self, texto, $element) {
+    function IsNumeric(num) {
+        return (num >=0 || num < 0);
+    }
+
+    function pon_texto(self, texto, $element) {
         $element.val(texto).select();
     }
 
+    function init_controles(self) {
+        pon_texto(self, "Regístrese!", self.$registro_button);
+        self.$registro_nombre.prop('disabled', false);
+        self.$registro_button.prop('disabled', false);
+        self.$prestamo_button.prop('disabled', true);
+        self.$acciones_button.prop('disabled', true);
+        self.$prestamo_cantidad.prop('disabled', true);
+        self.$acciones_cantidad.prop('disabled', true);
+
+        pon_texto(self, "", self.$registro_resultado);
+        pon_texto(self, "", self.$prestamo_cantidad);
+        pon_texto(self, "", self.$acciones_cantidad);
+        pon_texto(self, "", self.$prestamo_total);
+        pon_texto(self, "", self.$acciones_total);
+        pon_texto(self, "", self.$saldo_total);
+
+        pon_texto(self, "Escriba su nombre", self.$registro_nombre);
+    }
+
     /********************************************
      *      Configure events
      ********************************************/
             self.send_event(self, 'EV_REGISTER_USER', kw);
         });
 
+        self.$prestamo_button.on("click", self, function(event){
+            event.stopPropagation();
+            var self = event.data;
+            var kw = {
+                euros: self.$prestamo_cantidad.val()
+            };
+            self.send_event(self, 'EV_PEDIR_PRESTAMO', kw);
+        });
+
+        self.$acciones_button.on("click", self, function(event){
+            event.stopPropagation();
+            var self = event.data;
+            var kw = {
+                acciones: self.$acciones_cantidad.val()
+            };
+            self.send_event(self, 'EV_COMPRAR_ACCIONES', kw);
+        });
+
         return 1;
     }
 
          *  user_name =
          */
         var user_name = event.kw.user_name;
-        if (!user_name) {
-            escriba_algo(self, "Escriba su nombre", self.$registro_nombre);
+        if (!user_name || user_name == "Escriba su nombre") {
+            pon_texto(self, "Escriba su nombre", self.$registro_nombre);
             return 1;
         }
-        escriba_algo(self, "Espere por favor...", self.$registro_resultado);
+        pon_texto(self, "Espere por favor...", self.$registro_resultado);
+        self.user_name = user_name;
+
+        self.gaplic.send_event_outside(
+            '',                 // gaplic
+            'banco',            // role
+            'cuentas',          // gobj_name
+            'EV_CUENTA',        // event_name
+            self,               // subscriber_gobj
+            null,               // origin_role
+            {                   // kw
+                user_name: user_name
+            }
+        );
+
         return 1;
     }
 
     function ac_unregister_user(self, event) {
+        init_controles(self);
         return 1;
     }
 
+    function ac_cuenta_ack(self, event) {
+        pon_texto(self, "Deregistrarse", self.$registro_button);
+        pon_texto(self, "Registrado!", self.$registro_resultado);
+
+        self.$registro_nombre.prop('disabled', true);
+        self.$prestamo_button.prop('disabled', false);
+        self.$acciones_button.prop('disabled', false);
+        self.$prestamo_cantidad.prop('disabled', false);
+        self.$acciones_cantidad.prop('disabled', false);
+
+        pon_texto(self, "", self.$prestamo_cantidad);
+
+        return 1;
+    }
+
+    function ac_pedir_prestamo(self, event) {
+        var euros = event.kw.euros;
+
+        if (!IsNumeric(euros) || euros <= 0) {
+            pon_texto(self, "Escriba una cantidad", self.$prestamo_cantidad);
+            return 1;
+        }
+
+        pon_texto(self, "Espere por favor...", self.$prestamo_total);
+
+        self.gaplic.send_event_outside(
+            '',                 // gaplic
+            'financiera',       // role
+            'prestamos',        // gobj_name
+            'EV_PRESTAMO',      // event_name
+            self,               // subscriber_gobj
+            null,               // origin_role
+            {                   // kw
+                euros: euros,
+                user_name: self.user_name
+            }
+        );
+
+        return 1;
+    }
+
+    function ac_prestamo_ack(self, event) {
+        var euros = event.kw.euros;
+
+        pon_texto(self, euros, self.$prestamo_total);
+
+        return 1;
+    }
+
+    function ac_comprar_acciones(self, event) {
+        var acciones = event.kw.acciones;
+
+        if (!IsNumeric(acciones)) {
+            pon_texto(self, "Escriba una cantidad", self.$acciones_cantidad);
+            return 1;
+        }
+
+        pon_texto(self, "Espere por favor...", self.$acciones_total);
+
+        self.gaplic.send_event_outside(
+            '',                 // gaplic
+            'bolsa',            // role
+            'acciones',         // gobj_name
+            'EV_ACCIONES',      // event_name
+            self,               // subscriber_gobj
+            null,               // origin_role
+            {                   // kw
+                acciones: acciones,
+                user_name: self.user_name
+            }
+        );
+
+        return 1;
+    }
+
+    function ac_acciones_ack(self, event) {
+        var acciones = event.kw.acciones;
+
+        pon_texto(self, acciones, self.$acciones_total);
+
+        return 1;
+    }
 
     /********************************************
      *      Automata
      ********************************************/
     var CLIENTE_FSM = {
         'event_list': [
-            'EV_COMMAND: output',
-            'EV_UNREGISTER_USER',
+            'EV_CUENTA_ACK',
+            'EV_PRESTAMO_ACK',
+            'EV_ACCIONES_ACK',
+            'EV_PEDIR_PRESTAMO',
+            'EV_COMPRAR_ACCIONES',
             'EV_REGISTER_USER'
         ],
         'state_list': [
         'machine': {
             'ST_INIT':
             [
-                ['EV_REGISTER_USER',        ac_register_user,       undefined]
+                ['EV_CUENTA_ACK',       ac_cuenta_ack,       'ST_REGISTERED'],
+                ['EV_REGISTER_USER',    ac_register_user,    undefined]
             ],
             'ST_REGISTERED':
             [
-                ['EV_UNREGISTER_USER',      ac_unregister_user,     undefined]
+                ['EV_REGISTER_USER',    ac_unregister_user,  'ST_INIT'],
+                ['EV_PEDIR_PRESTAMO',   ac_pedir_prestamo,   undefined],
+                ['EV_COMPRAR_ACCIONES', ac_comprar_acciones, undefined],
+                ['EV_PRESTAMO_ACK',     ac_prestamo_ack,     undefined],
+                ['EV_ACCIONES_ACK',     ac_acciones_ack,     undefined]
             ]
         }
     }
          *      Build jquery link list.
          *---------------------------------*/
         self.build_jquery_link_list();
+
+        init_controles(self);
     }
 
     /*--------------------------------------*

ginsfsm/examples/inter_event/ap1_banco/setup.py

     'pyramid >= 1.4',
 ]
 
-setup(name='banco',
+setup(
+    name='banco',
     version=banco.__version__,
     description='banco',
     long_description=README + '\n\n' + CHANGES,

ginsfsm/examples/inter_event/ap2_financiera/financiera/c_prestamos.py

 from ginsfsm.gobj import GObj
 
 
-def ac_sample(self, event):
+def ac_prestamo(self, event):
     """ Event attributes:
-        * :attr:`data`: example.
+        * :attr:`euros`: .
 
     """
-    if self.output_event_name is not None:
-        self.broadcast_event(self.output_event_name, data=event.data)
+    euros = int(event.euros)
+    user_name = event.user_name
+    if not user_name in self.user_prestamos:
+        self.user_prestamos[user_name] = euros
+    else:
+        self.user_prestamos[user_name] += euros
 
+    if event.__intra_event__:
+        origin_gaplic = event.__intra_event__.origin_gaplic
+        origin_role = event.__intra_event__.origin_role
+        origin_gobj = event.__intra_event__.origin_gobj
 
-GPRESTAMOS_FSM = {
+        self.gaplic.send_event_outside(
+            origin_gaplic,  # gaplic_name
+            origin_role,  # role
+            origin_gobj,  # gobj_name
+            'EV_PRESTAMO_ACK',  # event_name
+            self,  # subscriber_gobj
+            euros=self.user_prestamos[user_name],
+        )
+
+
+PRESTAMOS_FSM = {
     'event_list': (
-        'EV_INPUT_EVENT:top input',
-        'EV_OUTPUT_EVENT:top output',
+        'EV_PRESTAMO:top input',
+        'EV_PRESTAMO_ACK:top output',
     ),
     'state_list': (
         'ST_IDLE',
     'machine': {
         'ST_IDLE':
         (
-            ('EV_INPUT_EVENT',      ac_sample,      None),
+            ('EV_PRESTAMO',      ac_prestamo,      None),
         ),
     }
 }
 
-GPRESTAMOS_GCONFIG = {
+PRESTAMOS_GCONFIG = {
     'subscriber': [
         None, None, 0, None,
         "subcriber of all output-events."
         "Default is ``None``, i.e., the parent"
     ],
-
-    # If some name is None then the parent don't want receive it.
-    'output_event_name': [
-        str, 'EV_OUTPUT_EVENT', 0, None,
-        "Name of the *sample output* event."
-        " ``None`` if you want ignore the event"
-    ],
 }
 
 
     A Sample gobj.
 
     .. ginsfsm::
-       :fsm: GPRESTAMOS_FSM
-       :gconfig: GPRESTAMOS_GCONFIG
+       :fsm: PRESTAMOS_FSM
+       :gconfig: PRESTAMOS_GCONFIG
 
     *Input-Events:*
-        * :attr:`'EV_INPUT_EVENT'`: sample input event.
+        * :attr:`'EV_PRESTAMO'`: sample input event.
 
           Event attributes:
 
               * ``data``: sample event attribute.
 
     *Output-Events:*
-        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.
+        * :attr:`'EV_PRESTAMO_ACK'`: sample output event.
 
           Event attributes:
 
 
     """
     def __init__(self):
-        GObj.__init__(self, GPRESTAMOS_FSM, GPRESTAMOS_GCONFIG)
+        GObj.__init__(self, PRESTAMOS_FSM, PRESTAMOS_GCONFIG)
+        self.user_prestamos = {}
 
     def start_up(self):
         """ Initialization zone.
         """
-        if self.config.subscriber is None:
-            self.config.subscriber = self.parent
-        self.subscribe_event(None, self.config.subscriber)
+        if self.config.subscriber:
+            self.subscribe_event(None, self.config.subscriber)

ginsfsm/examples/inter_event/ap3_bolsa/bolsa/c_acciones.py

 from ginsfsm.gobj import GObj
 
 
-def ac_sample(self, event):
+def ac_acciones(self, event):
     """ Event attributes:
-        * :attr:`data`: example.
+        * :attr:`acciones`: .
 
     """
-    if self.output_event_name is not None:
-        self.broadcast_event(self.output_event_name, data=event.data)
+    acciones = int(event.acciones)
+    user_name = event.user_name
+    if not user_name in self.user_acciones:
+        self.user_acciones[user_name] = acciones
+    else:
+        self.user_acciones[user_name] += acciones
 
+    if event.__intra_event__:
+        origin_gaplic = event.__intra_event__.origin_gaplic
+        origin_role = event.__intra_event__.origin_role
+        origin_gobj = event.__intra_event__.origin_gobj
 
-GACCIONES_FSM = {
+        self.gaplic.send_event_outside(
+            origin_gaplic,  # gaplic_name
+            origin_role,  # role
+            origin_gobj,  # gobj_name
+            'EV_ACCIONES_ACK',  # event_name
+            self,  # subscriber_gobj
+            acciones=self.user_acciones[user_name],
+        )
+
+
+ACCIONES_FSM = {
     'event_list': (
-        'EV_INPUT_EVENT:top input',
-        'EV_OUTPUT_EVENT:top output',
+        'EV_ACCIONES:top input',
+        'EV_ACCIONES_ACK:top output',
     ),
     'state_list': (
         'ST_IDLE',
     'machine': {
         'ST_IDLE':
         (
-            ('EV_INPUT_EVENT',      ac_sample,      None),
+            ('EV_ACCIONES',      ac_acciones,      None),
         ),
     }
 }
 
-GACCIONES_GCONFIG = {
+ACCIONES_GCONFIG = {
     'subscriber': [
         None, None, 0, None,
         "subcriber of all output-events."
         "Default is ``None``, i.e., the parent"
     ],
-
-    # If some name is None then the parent don't want receive it.
-    'output_event_name': [
-        str, 'EV_OUTPUT_EVENT', 0, None,
-        "Name of the *sample output* event."
-        " ``None`` if you want ignore the event"
-    ],
 }
 
 
     A Sample gobj.
 
     .. ginsfsm::
-       :fsm: GACCIONES_FSM
-       :gconfig: GACCIONES_GCONFIG
+       :fsm: ACCIONES_FSM
+       :gconfig: ACCIONES_GCONFIG
 
     *Input-Events:*
-        * :attr:`'EV_INPUT_EVENT'`: sample input event.
+        * :attr:`'EV_ACCIONES'`: sample input event.
 
           Event attributes:
 
               * ``data``: sample event attribute.
 
     *Output-Events:*
-        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.
+        * :attr:`'EV_ACCIONES_ACK'`: sample output event.
 
           Event attributes:
 
 
     """
     def __init__(self):
-        GObj.__init__(self, GACCIONES_FSM, GACCIONES_GCONFIG)
+        GObj.__init__(self, ACCIONES_FSM, ACCIONES_GCONFIG)
+        self.user_acciones = {}
 
     def start_up(self):
         """ Initialization zone.
         """
-        if self.config.subscriber is None:
-            self.config.subscriber = self.parent
-        self.subscribe_event(None, self.config.subscriber)
+        if self.config.subscriber:
+            self.subscribe_event(None, self.config.subscriber)
Add a comment to this file

ginsfsm/examples/inter_event/schema.svg

Old
Old image
New
New image
      inkscape:pageopacity="0.0"
      inkscape:pageshadow="2"
      inkscape:zoom="0.8830081"
-     inkscape:cx="272.74448"
-     inkscape:cy="361.4463"
+     inkscape:cx="-130.93686"
+     inkscape:cy="225.54721"
      inkscape:current-layer="layer1"
      inkscape:document-units="px"
      showgrid="false"
          sodipodi:role="line"
          x="768.40326"
          y="554.82635"
-         id="tspan2999">Role: banco, *financiera, **bolsa, **publicidad ↓</tspan><tspan
+         id="tspan2999">Role: banco, *financiera, *bolsa, *publicidad ↓</tspan><tspan
          sodipodi:role="line"
          x="768.40326"
          y="569.82635"
            id="tspan3260"
            y="371.57397"
            x="-195.6662"
-           sodipodi:role="line">    my_roles: ('financiera',)</tspan><tspan
+           sodipodi:role="line">    my_roles: ('financiera','^banco', '^^cliente')</tspan><tspan
            style="font-size:10px"
            id="tspan3262"
            y="384.07397"
     </g>
     <g
        id="g5414"
-       transform="translate(-20,40)">
+       transform="translate(-28,40)">
       <text
          sodipodi:linespacing="125%"
          id="text4702"
            id="tspan4710"
            y="513.07947"
            x="-167.92932"
-           sodipodi:role="line">    my_roles: ('banco',)</tspan><tspan
+           sodipodi:role="line">    my_roles: ('banco', '^cliente')</tspan><tspan
            style="font-size:10px"
            id="tspan4712"
            y="525.57947"
            id="tspan5108"
            y="402.30463"
            x="-31.942787"
-           sodipodi:role="line">    my_roles: ('financiera','bolsa','publicidad')</tspan><tspan
+           sodipodi:role="line">    my_roles: ('financiera','*bolsa','*publicidad')</tspan><tspan
            style="font-size:10px"
            id="tspan5110"
            y="414.80463"
     </g>
     <g
        id="g5324"
-       transform="translate(-67.92432,-9.0599395)">
+       transform="translate(-75.92432,-9.0599395)">
       <text
          sodipodi:linespacing="125%"
          id="text4702-7"
            id="tspan5108-7"
            y="611.55585"
            x="35.054585"
-           sodipodi:role="line">    my_roles: ('banco','financiera',bolsa, publicidad)</tspan><tspan
+           sodipodi:role="line">    my_roles: ('banco','*financiera',*bolsa, *publicidad)</tspan><tspan
            style="font-size:10px"
            id="tspan5110-4"
            y="624.05585"
     </g>
     <g
        id="g5450-0"
-       transform="translate(-312.41242,23.504286)">
+       transform="translate(-362.41242,25.504286)">
       <text
          sodipodi:linespacing="125%"
          id="text3252-3"
            id="tspan3260-7"
            y="371.57397"
            x="-195.6662"
-           sodipodi:role="line">    my_roles: ('financiera',)</tspan><tspan
+           sodipodi:role="line">    my_roles: ('financiera','^banco', '^^cliente')</tspan><tspan
            style="font-size:10px"
            id="tspan3262-4"
            y="384.07397"

ginsfsm/gaplic.py

 * :meth:`GAplic.create_gobj`
 * :meth:`GAplic.destroy_gobj`
 * :meth:`GAplic.find_unique_gobj`
-* :meth:`GAplic.send_event_to_external_gaplic`
+* :meth:`GAplic.send_event_outside`
 * :meth:`GAplic.send_event_to_external_role`
 * :meth:`GAplic.subscribe_event_from_external_gaplic`
 * :meth:`GAplic.subscribe_event_from_external_role`
 .. autoclass:: GAplic
     :members: create_gobj, destroy_gobj,
         find_unique_gobj,
-        send_event_to_external_gaplic,
+        send_event_outside,
         send_event_to_external_role,
         subscribe_event_from_external_gaplic,
         subscribe_event_from_external_role,
         named_gobj = self._unique_named_gobjs.get(gobj_name, None)
         return named_gobj
 
-    def send_event_to_external_gaplic(
-            self, gaplic_name, role, gobj_name, event_name, subscriber_gobj, **kw):
+    def send_event_outside(
+            self,
+            gaplic_name,
+            role,
+            gobj_name,
+            event_name,
+            subscriber_gobj,
+            origin_role=None,
+            **kw):
         """ Send an event to an external gaplic.
 
         :param role: name of external role.
                 % (subscriber_gobj)
             )
 
-        if role in self.roles:
+        if role in self.roles or gaplic_name == self.name:
             raise TypeError(
-                "Please don't use external methods to self gaplic."
-                % (role)
+                "Please don't use external methods to send self."
+            )
+
+        if origin_role and not origin_role in self.roles:
+            raise TypeError(
+                "Unknown origin role: %s" % origin_role
             )
 
         if isinstance(subscriber_gobj, (GObj)):
                 % (subscriber_gobj)
             )
 
-        return self.router.mt_send_event_to_external_gaplic(
-            gaplic_name,
-            role,
-            gobj_name,
-            event_name,
-            subscriber_gobj,
-            kw
+        return self.send_event(
+            self.router,
+            'EV_SEND_EVENT_OUTSIDE',
+            gaplic_name=gaplic_name,
+            role=role,
+            gobj_name=gobj_name,
+            event_name_=event_name,
+            subscriber_gobj=subscriber_gobj,
+            origin_role=origin_role,
+            kw=kw
         )
 
+        #return self.router.mt_send_event_to_external_gaplic(
+        #    gaplic_name,
+        #    role,
+        #    gobj_name,
+        #    event_name,
+        #    subscriber_gobj,
+        #    kw
+        #)
+
     def subscribe_event_from_external_gaplic(
             self, gaplic_name, role, gobj_name, event_name, subscriber_gobj, **kw):
         """ Subscribe an event of an external gaplic by name.
         """
         kw.update({'__subscribe_event__': True})
-        return self.send_event_to_external_gaplic(
+        return self.send_event_outside(
             gaplic_name,
             role,
             gobj_name,
         """ Subscribe an event of an external gaplic by name.
         """
         kw.update({'__unsubscribe_event__': True})
-        return self.send_event_to_external_gaplic(
+        return self.send_event_outside(
             gaplic_name,
             role,
             gobj_name,

ginsfsm/router.py

         return r
 
     def add_dynamic_route(self, name, role, write, gsock):
+        if not name:
+            # anonymous gaplic name
+            name = "^%s%s" % (gsock.get_peername(), gsock.get_sockname())
         r = DynamicRoute(name, role, write, gsock)
         self.dynamic_routes[r.route_ref] = r
         return r
             roles = route.roles
             # TODO: busca el rol conectado si hay varios
             for ro in roles:
+                ro = ro.lstrip('^')
                 if ro == role:
                     return route
 
                 return False
             if trace_router:
                 prefix = '%s ==> %s' % (
-                    self.my_gaplic_name, route.route_ref)
+                    self.my_gaplic_name, route)
                 self.router.trace_intra_event(prefix, route.cur_pending_event)
             write(msg)
             return True
                 return False
             if trace_router:
                 prefix = '%s ==> %s' % (
-                    self.my_gaplic_name, route.route_ref)
+                    self.my_gaplic_name, route)
                 self.router.trace_intra_event(prefix, route.cur_pending_event)
             write(msg)
             return True
             pass  # TODO: delete gsock or channel
 
 
+def get_first_name(name):
+    if '^' in name:
+        name = name.split()[0]
+    return name
+
+
 def ac_connected(self, event):
     """ Someone is connected.
     By here we receive the connection of both client and server routers
         )
         if trace_router:
             prefix = '%s ==> %s' % (
-                registry.my_gaplic_name, this_route.route_ref)
+                registry.my_gaplic_name, this_route)
             self.trace_intra_event(prefix, ack)
         write(ack.toJSON())
 
         return
 
     elif message_type == '__event__':
-        #-------------------------------------------#
-        #           search in self
-        #-------------------------------------------#
+        #--------------------------------------------------#
+        #   It's an event. Search if for us or to resend
+        #--------------------------------------------------#
         own = False
 
+        if isinstance(this_route, DynamicRoute):
+            if not intra_event.origin_gaplic:
+                #  Set our extended gaplic name
+                intra_event.origin_gaplic = this_route.gaplic_name
+
         # search by gaplic
         if intra_event.destination_gaplic and registry.my_gaplic_name:
-            if intra_event.destination_gaplic == registry.my_gaplic_name:
+            first_gaplic_name = get_first_name(intra_event.destination_gaplic)
+            if first_gaplic_name == registry.my_gaplic_name:
                 own = True
 
         # search by role
                 own = True
 
         if own:
-            # The event is for own gaplic.
+            #------------------------------------#
+            #   The event is for own gaplic.
+            #------------------------------------#
             dst_gobj = intra_event.destination_gobj
             try:
                 named_gobj = self.gaplic.find_unique_gobj(dst_gobj)
                 ack.error_message = e
                 if trace_router:
                     prefix = '%s ==> %s' % (
-                        registry.my_gaplic_name, this_route.route_ref)
+                        registry.my_gaplic_name, this_route)
                     self.trace_intra_event(prefix, ack)
                 write(ack.toJSON())
                 return
                 ack.error_message = "GObj %r UNKNOWN" % dst_gobj
                 if trace_router:
                     prefix = '%s ==> %s' % (
-                        registry.my_gaplic_name, this_route.route_ref)
+                        registry.my_gaplic_name, this_route)
                     self.trace_intra_event(prefix, ack)
                 write(ack.toJSON())
                 return
                     ack.error_message = "Cannot make external subscription"
                     if trace_router:
                         prefix = '%s ==> %s' % (
-                            registry.my_gaplic_name, this_route.route_ref)
+                            registry.my_gaplic_name, this_route)
                         self.trace_intra_event(prefix, ack)
                     write(ack.toJSON())
                     return
                     ack.error_message = "Cannot subscribe event: " + e
                     if trace_router:
                         prefix = '%s ==> %s' % (
-                            registry.my_gaplic_name, this_route.route_ref)
+                            registry.my_gaplic_name, this_route)
                         self.trace_intra_event(prefix, ack)
                     write(ack.toJSON())
                     return
                 ack.reference = external_subscriptor_ref
                 if trace_router:
                     prefix = '%s ==> %s' % (
-                        registry.my_gaplic_name, this_route.route_ref)
+                        registry.my_gaplic_name, this_route)
                     self.trace_intra_event(prefix, ack)
                 write(ack.toJSON())
                 return
                 ack = intra_event.copy('__event_ack__')
                 if trace_router:
                     prefix = '%s ==> %s' % (
-                        registry.my_gaplic_name, this_route.route_ref)
+                        registry.my_gaplic_name, this_route)
                     self.trace_intra_event(prefix, ack)
                 write(ack.toJSON())
                 return
             ack = intra_event.copy('__event_ack__')
             if trace_router:
                 prefix = '%s ==> %s' % (
-                    registry.my_gaplic_name, this_route.route_ref)
+                    registry.my_gaplic_name, this_route)
                 self.trace_intra_event(prefix, ack)
             write(ack.toJSON())
 
             return
 
         #-------------------------------------------#
-        #           search in routes
+        #       The event is for resend.
+        #       Search in routes.
         #-------------------------------------------#
         route_dst = registry.search_route(
             intra_event.destination_gaplic,
                 )
             if trace_router:
                 prefix = '%s ==> %s' % (
-                    registry.my_gaplic_name, this_route.route_ref)
+                    registry.my_gaplic_name, this_route)
                 self.trace_intra_event(prefix, ack)
             write(ack.toJSON())
             return
             ack.error_message = "Route found but DISCONNECTED"
             if trace_router:
                 prefix = '%s ==> %s' % (
-                    registry.my_gaplic_name, this_route.route_ref)
+                    registry.my_gaplic_name, this_route)
                 self.trace_intra_event(prefix, ack)
             write(ack.toJSON())
             return
             ack.error_message = "route_dst event queue FULL"
         if trace_router:
             prefix = '%s ==> %s' % (
-                registry.my_gaplic_name, this_route.route_ref)
+                registry.my_gaplic_name, this_route)
             self.trace_intra_event(prefix, ack)
         write(ack.toJSON())
 
     subscription = self.external_subscriptions.get(
         subscription_reference, None)
     if subscription:
-        self.mt_send_event_to_external_route(
+        self._send_event_to_external_route(
             subscription.route_ref,
             subscription.origin_gobj,
             subscription.event_name,
             event.kw)
 
 
+def ac_send_event_outside(self, event):
+    gaplic_name = event.gaplic_name
+    role = event.role
+    gobj_name = event.gobj_name
+    event_name_ = event.event_name_
+    subscriber_gobj = event.subscriber_gobj
+    origin_role = event.origin_role
+    kw = event.kw
+
+    registry = self.registry
+    route = registry.search_route(gaplic_name, role)
+    if not route:
+        self.logger.error(
+            "ERROR ac_send_event_outside() "
+            "route NOT FOUND: %r %r" % (gaplic_name, role))
+        return False
+
+    intra_event = IntraEvent(
+        message_type='__event__',
+        serial=route.incr_serial(),
+        event_name=event_name_,
+        destination_gaplic=gaplic_name,
+        destination_role=role,
+        destination_gobj=gobj_name,
+        origin_gaplic=registry.my_gaplic_name,
+        origin_role=origin_role if origin_role else registry.my_roles[0],
+        origin_gobj=subscriber_gobj,
+        kw=kw)
+
+    registry.enqueue_pending_event(route, intra_event)
+    if not route.cur_pending_event:
+        registry.fire_pending_events(route)
+    return True
+
+
 GROUTER_FSM = {
     'event_list': (
         'EV_ADD_STATIC_ROUTE: top input',
         'EV_INPUT_MESSAGE: bottom input',
         'EV_TIMEOUT: bottom input',
         'EV_SUBSCRIPTION: bottom input',
+        'EV_SEND_EVENT_OUTSIDE: top output',
     ),
     'state_list': ('ST_IDLE',),
     'machine': {
             ('EV_INPUT_MESSAGE',        ac_input_message,       None),
             ('EV_TIMEOUT',              ac_timeout,             None),
             ('EV_SUBSCRIPTION',         ac_subscription,        None),
+            ('EV_SEND_EVENT_OUTSIDE',   ac_send_event_outside,  None),
         ),
     }
 }
             transmit_ready_event_name=None,
         )
 
-    def mt_send_event_to_external_gaplic(
-            self,
-            gaplic_name,
-            role,
-            gobj_name,
-            event_name,
-            subscriber_gobj,
-            kw):
-        registry = self.registry
-        route = registry.search_route(gaplic_name, role)
-        if not route:
-            self.logger.error(
-                "ERROR mt_send_event_to_external_gaplic() "
-                "gaplic NOT FOUND: %r" % gaplic_name)
-            return False
-
-        intra_event = IntraEvent(
-            message_type='__event__',
-            serial=route.incr_serial(),
-            event_name=event_name,
-            destination_gaplic=gaplic_name,
-            destination_gobj=gobj_name,
-            origin_gaplic=registry.my_gaplic_name,
-            origin_gobj=subscriber_gobj,
-            kw=kw)
-
-        registry.enqueue_pending_event(route, intra_event)
-        if not route.cur_pending_event:
-            registry.fire_pending_events(route)
-        return True
-
-    def mt_send_event_to_external_route(
+    def _send_event_to_external_route(
             self,
             route_ref,
             gobj_name,
             destination_role=route.roles[0] if route.roles else '',
             destination_gobj=gobj_name,
             origin_gaplic=registry.my_gaplic_name,
+            origin_role=registry.my_roles,
             origin_gobj=subscriber_gobj,
             kw=kw)
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.