Commits

Ginés Martínez Sánchez  committed b268784 Draft

new example

  • Participants
  • Parent commits 81faa7c

Comments (0)

Files changed (9)

 prune .hg
-recursive-include ginsfsm/examples/inter_event *
-
 global-exclude *.pyc
-recursive-include ginsfsm/scaffolds/multiple_wsgi *
-recursive-include ginsfsm/scaffolds/multi_pyramid_wsgi *
-recursive-include ginsfsm/scaffolds/simple_gobj *
-recursive-include ginsfsm/scaffolds/simple_pyramid *
-recursive-include ginsfsm/scaffolds/simple_websocket_server *
-recursive-include ginsfsm/scaffolds/simple_wsgi *
+recursive-include ginsfsm/examples *
+recursive-include ginsfsm/scaffolds *

File ginsfsm/c_connex.py

     ],
     'host': [
         str, '', GConfig.FLAG_DIRECT_ATTR, None,
-        "server or client host (ip or name)"
+        "ONLY READ!! server or client host (ip or name)"
     ],
     'port': [
         int, 0, GConfig.FLAG_DIRECT_ATTR, None,
-        "server or client port"
+        "ONLY READ!! server or client port"
     ],
 
     # If some name is None then parent don't want receive it.

File ginsfsm/examples/router/test_router.py

     self.counter += 1
     if self.counter > 4:
         # delete subscription
-        ret = self.gaplic.unsubscribe_event_from_external_gaplic(
+        ret = self.gaplic.unsubscribe_event_outside(
             'TOTO',         # gaplic_name
+            '',             # role
             'sample2',      # gobj_name
             'EV_MESSAGE',   # event_name
             self,           # subscriber_gobj
             print("Eiiiiiiiiiiiiiiiiiiiiii something wrong!")
 
     # causes broadcast EV_MESSAGE again
-    self.gaplic.send_event_to_external_gaplic(
+    self.gaplic.send_event_outside(
         'TOTO',             # gaplic_name
+        '',                 # role
         'sample2',          # gobj_name
         'EV_SET_TIMEOUT',   # event_name
         self,               # subscriber_gobj
     def start_up(self):
         """
         """
-        ret = self.gaplic.subscribe_event_from_external_gaplic(
+        ret = self.gaplic.subscribe_event_outside(
             'TOTO',         # gaplic_name
+            '',             # role
             'sample2',      # gobj_name
             'EV_MESSAGE',   # event_name
             self,           # subscriber_gobj
         if not ret:
             print("Eiiiiiiiiiiiiiiiiiiiiii something wrong!")
 
-        self.gaplic.send_event_to_external_gaplic(
+        self.gaplic.send_event_outside(
             'TOTO',             # gaplic_name
+            '',                 # role
             'sample2',          # gobj_name
             'EV_SET_TIMEOUT',   # event_name
             self,               # subscriber_gobj

File ginsfsm/examples/websocket_mixin/__init__.py

Empty file added.

File ginsfsm/examples/websocket_mixin/index.html

+<!DOCTYPE html>
+<html class="no-js">
+    <head>
+        <meta charset="utf-8">
+        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
+        <title></title>
+        <meta name="description" content="">
+        <meta name="viewport" content="width=device-width">
+        <script src="sockjs.js"></script>
+        <script src="jsfsm.js"></script>
+
+    </head>
+    <body>
+        <p>Hello world! .</p>
+    </body>
+</html>

File ginsfsm/examples/websocket_mixin/main.py

+import logging
+logging.basicConfig(level=logging.DEBUG)
+
+from ginsfsm.gobj import GObj
+from ginsfsm.c_connex import GConnex
+from ginsfsm.gaplic import GAplic, setup_gaplic_thread
+from ginsfsm.c_timer import GTimer
+from ginsfsm.c_srv_sock import GServerSock
+
+
+#===============================================================
+#   Server: emit a message to clients each 5 seconds
+#===============================================================
+def ac_clisrv_timeout(self, event):
+    self.set_timeout(5)
+    for child in self.clients:
+        self.send_event(child, 'EV_SEND_DATA', data='xxxxxx')
+
+
+def ac_clisrv_connected(self, event):
+    self.clients.add(event.gsock)
+
+
+def ac_clisrv_disconnected(self, event):
+    self.clients.remove(event.gsock)
+    self.destroy_gobj(event.source[-1])
+
+
+def ac_clisrv_rx_data(self, event):
+    # Do echo
+    self.send_event(event.source[-1], 'EV_SEND_DATA', data=event.data)
+
+
+SERVER_FSM = {
+    'event_list': (
+        'EV_SET_TIMER: bottom output',
+        'EV_TIMEOUT: bottom input',
+        'EV_CONNECTED: bottom input',
+        'EV_DISCONNECTED: bottom input',
+        'EV_RX_DATA:bottom input',
+    ),
+    'state_list': ('ST_IDLE',),
+    'machine': {
+        'ST_IDLE':
+        (
+            ('EV_TIMEOUT',          ac_clisrv_timeout,         'ST_IDLE'),
+            ('EV_CONNECTED',        ac_clisrv_connected,       'ST_IDLE'),
+            ('EV_DISCONNECTED',     ac_clisrv_disconnected,    'ST_IDLE'),
+            ('EV_RX_DATA',          ac_clisrv_rx_data,         'ST_IDLE'),
+        ),
+    }
+}
+
+
+SERVER_GCONFIG = {  # type, default_value, flag, validate_function, desc
+    'verbose': [int, 1, 0, None, "Increase output verbosity. Values [0,1,2]"],
+}
+
+
+class OnServer(GObj):
+    """  Server GObj.
+
+    .. ginsfsm::
+       :fsm: SERVER_FSM
+       :gconfig: SERVER_GCONFIG
+
+    *Input-Events:*
+
+        * :attr:`'EV_TIMEOUT'`: Timer over.
+            Start the machine.
+
+        * :attr:`'EV_CONNECTED'`: New client.
+
+        * :attr:`'EV_DISCONNECTED'`: Client disconnected.
+
+        * :attr:`'EV_RX_DATA'`: Receiving data.
+
+    *Output-Events:*
+
+    """
+    def __init__(self):
+        GObj.__init__(self, SERVER_FSM, SERVER_GCONFIG)
+        self.clients = set()
+
+    def start_up(self):
+        self.timer = self.create_gobj(
+            None,
+            GTimer,
+            self)
+        self.set_timeout(5)
+
+        self.server = self.create_gobj(
+            None,
+            GServerSock,
+            self,
+            host='0.0.0.0',
+            port=10000,
+            transmit_ready_event_name=None,
+        )
+
+    def set_timeout(self, seconds):
+        self.send_event(self.timer, 'EV_SET_TIMER', seconds=seconds)
+
+    def clear_timeout(self):
+        self.send_event(self.timer, 'EV_SET_TIMER', seconds=-1)
+
+
+#===============================================================
+#                   Driver
+#===============================================================
+def ac_rx_data(self, event):
+    data = event.kw['data']
+    print("RECIBO======> %s" % data)
+    self.broadcast_event('EV_UPDATE_DRIVER', data=data)
+
+
+DRIVER1_FSM = {
+    'event_list': (
+        'EV_UPDATE_DRIVER:top output',
+        'EV_RX_DATA:bottom input',
+    ),
+    'state_list': ('ST_IDLE',),
+    'machine': {
+        'ST_IDLE':
+        (
+            ('EV_RX_DATA',      ac_rx_data,     'ST_IDLE'),
+        ),
+    }
+}
+
+
+DRIVER1_GCONFIG = {  # type, default_value, flag, validate_function, desc
+    'host': [str, 'localhost', 0, None, ""],
+    'port': [int, 10000, 0, None, ""],
+}
+
+
+class Driver1(GObj):
+    """  Driver1 GObj.
+
+    .. ginsfsm::
+       :fsm: DRIVER1_FSM
+       :gconfig: DRIVER1_GCONFIG
+
+    *Input-Events:*
+
+        * :attr:`'EV_RX_DATA'`: Receiving data.
+            Receiving data from urls.
+
+    *Output-Events:*
+
+    """
+    def __init__(self):
+        GObj.__init__(self, DRIVER1_FSM, DRIVER1_GCONFIG)
+
+    def start_up(self):
+        """ Initialization zone."""
+        self.timer = self.create_gobj(
+            None,
+            GTimer,
+            self,
+        )
+        self.connex = self.create_gobj(
+            'connex',
+            GConnex,
+            self,
+            destinations=[
+                (self.config.host, self.config.port),
+            ],
+            #host=self.config.host,
+            #port=self.config.port,
+            # only want receive EV_RX_DATA event
+            connected_event_name=None,
+            disconnected_event_name=None,
+            transmit_ready_event_name=None,
+        )
+
+
+#===============================================================
+#                   Main
+#===============================================================
+def mycallback(event):
+    print("CALLBACK recibiendo %s" % event.data)
+
+if __name__ == "__main__":
+    local_conf = {
+        'GObj.trace_mach': True,
+        'GObj.logger': logging,
+    }
+
+    #---------------------------------------------#
+    #
+    #---------------------------------------------#
+    ga_srv = GAplic(name='server', roles='', **local_conf)
+    ga_srv.create_gobj(
+        'server',
+        OnServer,
+        ga_srv,
+    )
+    thread_server = setup_gaplic_thread(ga_srv)
+    thread_server.start()
+
+    #---------------------------------------------#
+    #
+    #---------------------------------------------#
+    local_conf = {
+        'router_enabled':  True,
+        'GRouter.server':  True,
+        'GRouter.localhost_route_ports':  8002,
+        'GRouter.trace_router':  True,
+        'GObj.trace_mach':  True,
+        'GObj.trace_creation':  False,
+        'GObj.trace_traverse':  True,
+        'GObj.trace_subscription':  False,
+        'GSock.trace_dump':  True,
+        'GObj.logger': logging,
+    }
+    ga_driver = GAplic(name='driver', roles='', **local_conf)
+    ga_driver.create_gobj(
+        'driverXXX',
+        Driver1,
+        ga_driver,
+        __unique_name__=True,
+    )
+    thread_driver = setup_gaplic_thread(ga_driver)
+    thread_driver.start()
+
+    #---------------------------------------------#
+    #   Code to insert in a non-gobj code.
+    #       Subscribe as callback
+    #---------------------------------------------#
+    from ginsfsm.globals import global_get_gobj
+    from ginsfsm.deferred import Deferred
+
+    defer = Deferred(0, mycallback)
+    gobj = global_get_gobj('driverXXX')
+    if gobj:
+        gobj.subscribe_event('EV_UPDATE_DRIVER', defer)
+
+    #---------------------------------------------#
+    #       Loop
+    #---------------------------------------------#
+    try:
+        while True:
+            pass
+    except (KeyboardInterrupt, SystemExit):
+        print('Program stopped')
+
+    thread_server.stop()
+    thread_driver.stop()
+    thread_server.join()
+    thread_driver.join()

File ginsfsm/globals.py

     TODO: with subprocesses send_event() will work??
     """
     global_main_gaplic = get_global_main_gaplic()
-    gobj = global_main_gaplic.find_unique_gobj(gobj_name)
-    if gobj:
-        return gobj
+    if global_main_gaplic:
+        gobj = global_main_gaplic.find_unique_gobj(gobj_name)
+        if gobj:
+            return gobj
 
     global_threads = get_global_threads()
     for wkr in global_threads:

File ginsfsm/scaffolds/simple_gobj/+package+/__init__.py_tmpl

 # -*- encoding: utf-8 -*-
-""" {{package.capitalize()}} GObj
-
-.. autoclass:: {{package.capitalize()}}
-    :members: start_up
-
-"""
-
-from ginsfsm.gobj import GObj
-
-
-def ac_sample(self, event):
-    """ Event attributes:
-        * :attr:`data`: example.
-
-    """
-    if self.output_event_name is not None:
-        self.broadcast_event(self.output_event_name, data=event.data)
-
-
-{{package.upper()}}_FSM = {
-    'event_list': (
-        'EV_INPUT_EVENT:top input',
-        'EV_OUTPUT_EVENT:top output',
-    ),
-    'state_list': (
-        'ST_IDLE',
-    ),
-    'machine': {
-        'ST_IDLE':
-        (
-            ('EV_INPUT_EVENT',      ac_sample,      None),
-        ),
-    }
-}
-
-{{package.upper()}}_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"
-    ],
-}
-
-
-class {{package.capitalize()}}(GObj):
-    """  {{package.capitalize()}} GObj.
-    A Sample gobj.
-
-    .. ginsfsm::
-       :fsm: {{package.upper()}}_FSM
-       :gconfig: {{package.upper()}}_GCONFIG
-
-    *Input-Events:*
-        * :attr:`'EV_INPUT_EVENT'`: sample input event.
-
-          Event attributes:
-
-              * ``data``: sample event attribute.
-
-    *Output-Events:*
-        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.
-
-          Event attributes:
-
-              * ``data``: sample event attribute.
-
-    """
-    def __init__(self):
-        GObj.__init__(self, {{package.upper()}}_FSM, {{package.upper()}}_GCONFIG)
-
-    def start_up(self):
-        """ Initialization zone.
-        """
-        if self.config.subscriber is None:
-            self.config.subscriber = self.parent
-        self.subscribe_event(None, self.config.subscriber)

File ginsfsm/scaffolds/simple_gobj/+package+/c_+package+.py_tmpl

+# -*- encoding: utf-8 -*-
+""" {{package.capitalize()}} GObj
+
+.. autoclass:: {{package.capitalize()}}
+    :members: start_up
+
+"""
+
+from ginsfsm.gobj import GObj
+
+
+def ac_sample(self, event):
+    """ Event attributes:
+        * :attr:`data`: example.
+
+    """
+    if self.output_event_name is not None:
+        self.broadcast_event(self.output_event_name, data=event.data)
+
+
+{{package.upper()}}_FSM = {
+    'event_list': (
+        'EV_INPUT_EVENT:top input',
+        'EV_OUTPUT_EVENT:top output',
+    ),
+    'state_list': (
+        'ST_IDLE',
+    ),
+    'machine': {
+        'ST_IDLE':
+        (
+            ('EV_INPUT_EVENT',      ac_sample,      None),
+        ),
+    }
+}
+
+{{package.upper()}}_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"
+    ],
+}
+
+
+class {{package.capitalize()}}(GObj):
+    """  {{package.capitalize()}} GObj.
+    A Sample gobj.
+
+    .. ginsfsm::
+       :fsm: {{package.upper()}}_FSM
+       :gconfig: {{package.upper()}}_GCONFIG
+
+    *Input-Events:*
+        * :attr:`'EV_INPUT_EVENT'`: sample input event.
+
+          Event attributes:
+
+              * ``data``: sample event attribute.
+
+    *Output-Events:*
+        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.
+
+          Event attributes:
+
+              * ``data``: sample event attribute.
+
+    """
+    def __init__(self):
+        GObj.__init__(self, {{package.upper()}}_FSM, {{package.upper()}}_GCONFIG)
+
+    def start_up(self):
+        """ Initialization zone.
+        """
+        if self.config.subscriber is None:
+            self.config.subscriber = self.parent
+        self.subscribe_event(None, self.config.subscriber)