Commits

Ginés Martínez Sánchez committed 4c320ab Draft

writing inter_event example

Comments (0)

Files changed (33)

ginsfsm/examples/inter_event/banco/banco.ini

 GObj.trace_mach = true
 GObj.trace_creation = false
 GObj.trace_traverse = true
+GObj.trace_subscription = false
 
 PyramidRoot.pyramid_router_url = __pyramid_router__
 GRouter.trace_router = true
 
-GRouter.static_routes = RobberA
-
-[RobberA]
-name = RobberA
-roles = financiera, bolsa, publicidad
-url = http://localhost:8002
-
+GRouter.static_routes =
+    RobberA, financiera+bolsa+publicidad, http://localhost:8002;
 
 [app:wsgi-application]
 use = egg:banco#pyramid_app

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

         'GObj.trace_mach': True,
         'GObj.trace_creation': False,
         'GObj.trace_traverse': True,
+        'GObj.trace_subscription': False,
 
         'GObj.logger': logging,
         'PyramidRoot.pyramid_router_url': '__pyramid_router__',
         'GRouter.trace_router': True,
+
+        'GRouter.static_routes':
+        'RobberA, financiera+bolsa+publicidad, http://localhost:8002;',
     }
 
     ga = main({}, **local_conf)

ginsfsm/examples/inter_event/financiera/CHANGES.txt

+0.0.0
+-----
+
+-  Initial version

ginsfsm/examples/inter_event/financiera/MANIFEST.in

+prune .hg
+exclude push.sh
+include *.txt *.ini *.cfg *.rst
+recursive-include financiera *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml

ginsfsm/examples/inter_event/financiera/README.rst

+financiera
+==========
+
+License
+-------
+
+Copyright (c) 2013
+
+financiera is released under terms of The MIT
+License MIT <http://www.opensource.org/licenses/mit-license>.
+
+Authors
+-------
+
+Your name

ginsfsm/examples/inter_event/financiera/__init__.py

Empty file removed.

ginsfsm/examples/inter_event/financiera/docs/DejaVuSans.ttf

Binary file added.

ginsfsm/examples/inter_event/financiera/docs/README.txt

+Create a sphinx project
+=======================
+
+To build the documentation you must create a sphinx project in this directory
+with the 'sphinx-quickstart' command, with 'autodoc' extension enabled.
+I like the 'viewcode' extension too.
+
+
+Include the sphinx extensions
+=============================
+
+In order to build the ginsfsm documentation with svg graphics of smachine
+you must too add the extension 'ginsfsm.sphinxext' to the created conf.py file.
+
+The final result can be:
+
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'ginsfsm.sphinxext']
+
+
+Include the generated rst file
+==============================
+
+You must include the generated api_xxx.rst in the Contents of index.rst:
+
+.. toctree::
+   :maxdepth: 2
+
+   api_xxx
+
+being xxx the name of the created project.
+
+
+Don't compile sphinx?
+=====================
+
+If make html fails with the message:
+
+   "Could not import extension ginsfsm.sphinxext"
+
+check if the next modules are installed:
+
+   * docutils
+   * svgwrite
+   * PIL
+     Better install `pillow`, with pip.
+     `pillow` will need libfreetype*dev and libjpeg*dev libs to compile.

ginsfsm/examples/inter_event/financiera/docs/api_financiera.rst

+financiera
+==========
+
+This is the main index page of your documentation. It should be written in
+`reStructuredText format <http://docutils.sourceforge.net/rst.html>`_.
+
+
+:mod:`financiera`
+-----------------
+
+.. automodule:: financiera

ginsfsm/examples/inter_event/financiera/financiera.ini

+[composite:main]
+use = call:ginsfsm.gaplic:gaplic_factory
+main = websocket-server
+
+[app:websocket-server]
+use = egg:financiera#main
+gaplic-name = financiera
+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
+
+
+# Begin logging configuration
+
+[loggers]
+keys = root, ginsfsm
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = DEBUG
+handlers = console
+
+[logger_ginsfsm]
+level = DEBUG
+handlers =
+qualname = ginsfsm
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(message)s
+
+# End logging configuration

ginsfsm/examples/inter_event/financiera/financiera/__init__.py

+# -*- encoding: utf-8 -*-
+
+__version__ = '0.0.0'

ginsfsm/examples/inter_event/financiera/financiera/c_financiera.py

+# -*- encoding: utf-8 -*-
+""" GFinanciera GObj
+
+.. autoclass:: GFinanciera
+    :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)
+
+
+GFINANCIERA_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),
+        ),
+    }
+}
+
+GFINANCIERA_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 GFinanciera(GObj):
+    """  GFinanciera GObj.
+    A Sample gobj.
+
+    .. ginsfsm::
+       :fsm: GFINANCIERA_FSM
+       :gconfig: GFINANCIERA_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, GFINANCIERA_FSM, GFINANCIERA_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)

ginsfsm/examples/inter_event/financiera/financiera/main.py

+# -*- encoding: utf-8 -*-
+"""
+financiera
+==========
+
+It uses :class:`ginsfsm.protocols.wsgi.server.c_wsgi_server.GWsgiServer`.
+
+.. autofunction:: main
+
+"""
+
+from ginsfsm.gaplic import GAplic
+from ginsfsm.globals import (
+    set_global_main_gaplic,
+)
+from financiera.c_financiera import GFinanciera
+
+
+#===============================================================
+#                   Main
+#       Paste app factory.
+#       To run with gserve financiera.ini
+#===============================================================
+def main(global_config, **local_conf):
+    """ Entry point to run with gserve (PasteDeploy)
+    """
+    if 'gaplic-name' in local_conf:
+        gaplic_name = local_conf.pop('gaplic-name')
+    else:
+        raise Exception('You must supply an gaplic name ("gaplic-name")')
+
+    ga = GAplic(
+        name=gaplic_name,
+        roles='financiera, bolsa, publicidad',
+        **local_conf)
+    set_global_main_gaplic(ga)
+
+    ga.create_gobj(
+        'sample',
+        GSample,
+        ga,
+        __unique_name__=True,
+    )
+    return ga
+
+
+if __name__ == "__main__":
+    """ You can run directly this file, without gserve.
+    """
+    import logging
+    logging.basicConfig(level=logging.DEBUG)
+
+    # simulate running from ini file
+    local_conf = {
+        'gaplic-name': 'financiera',
+        '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,
+    }
+    ga = main({}, **local_conf)
+
+    try:
+        ga.start()
+    except (KeyboardInterrupt, SystemExit):
+        print('Program stopped')

ginsfsm/examples/inter_event/financiera/financiera/tests/__init__.py

+#

ginsfsm/examples/inter_event/financiera/financiera/tests/test_financiera.py

+import unittest
+

ginsfsm/examples/inter_event/financiera/setup.cfg

+[nosetests]
+match = ^test
+nocapture = 1
+cover-package = financiera
+with-coverage = 1
+cover-erase = 1
+
+[egg_info]
+tag_build =
+tag_svn_revision = false
+tag_date = 0
+
+[easy_install]
+zip_ok = false

ginsfsm/examples/inter_event/financiera/setup.py

+# -*- encoding: utf-8 -*-
+
+import os
+import sys
+import financiera
+
+from setuptools import setup, find_packages
+
+if sys.version_info[:2] < (2, 6):
+    raise RuntimeError('Requires Python 2.6 or better')
+
+here = os.path.abspath(os.path.dirname(__file__))
+try:
+    README = open(os.path.join(here, 'README.rst')).read()
+    CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
+except IOError:
+    README = CHANGES = ''
+
+requires = ['ginsfsm']
+
+setup(name='financiera',
+    version=financiera.__version__,
+    description='financiera',
+    long_description=README + '\n\n' + CHANGES,
+    classifiers=[
+        "Programming Language :: Python",
+    ],
+    author='',
+    author_email='',
+    url='',
+    license='MIT License',
+    keywords='gobj ginsfsm finite state machine fsm wsgi',
+    packages=find_packages(),
+    include_package_data=True,
+    zip_safe=False,
+    install_requires=requires,
+    tests_require=requires,
+    test_suite="financiera.tests",
+    entry_points="""\
+    [paste.app_factory]
+    main = financiera.main:main
+    """,
+)

ginsfsm/scaffolds/__init__.py

         print(msg)
 
 
+class MultipleWsgiTemplate(GinsFSMTemplate):
+    _template_dir = 'multiple_wsgi'
+    summary = 'Create a multiple WSGI proyect.'
+
+
+class MultiplePyramidWsgiTemplate(GinsFSMTemplate):
+    _template_dir = 'multi_pyramid_wsgi'
+    summary = 'Create a multiple WSGI proyect' \
+        ' with a Pyramid wsgi application.'
+
+
 class SimpleGObjTemplate(GinsFSMTemplate):
     _template_dir = 'simple_gobj'
     summary = 'Create a simple GObj proyect.'
     summary = 'Create a simple Pyramid proyect, with sockjs server activated.'
 
 
-class MultipleWsgiTemplate(GinsFSMTemplate):
-    _template_dir = 'multiple_wsgi'
-    summary = 'Create a multiple WSGI proyect.'
+class SimpleWebsocketServerTemplate(GinsFSMTemplate):
+    _template_dir = 'simple_websocket_server'
+    summary = 'Create a simple Websocket Server proyect'
 
-
-class MultiplePyramidWsgiTemplate(GinsFSMTemplate):
-    _template_dir = 'multi_pyramid_wsgi'
-    summary = 'Create a multiple WSGI proyect' \
-        ' with a Pyramid wsgi application.'

ginsfsm/scaffolds/simple_websocket_server/+package+.ini_tmpl

+[composite:main]
+use = call:ginsfsm.gaplic:gaplic_factory
+main = websocket-server
+
+[app:websocket-server]
+use = egg:{{package}}#main
+gaplic-name = {{package}}
+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
+
+
+# Begin logging configuration
+
+[loggers]
+keys = root, ginsfsm
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = DEBUG
+handlers = console
+
+[logger_ginsfsm]
+level = DEBUG
+handlers =
+qualname = ginsfsm
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(message)s
+
+# End logging configuration

ginsfsm/scaffolds/simple_websocket_server/+package+/__init__.py_tmpl

+# -*- encoding: utf-8 -*-
+
+__version__ = '0.0.0'

ginsfsm/scaffolds/simple_websocket_server/+package+/c_sample.py_tmpl

+# -*- encoding: utf-8 -*-
+""" GSample GObj
+
+.. autoclass:: GSample
+    :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)
+
+
+GSAMPLE_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),
+        ),
+    }
+}
+
+GSAMPLE_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 GSample(GObj):
+    """  GSample GObj.
+    A Sample gobj.
+
+    .. ginsfsm::
+       :fsm: GSAMPLE_FSM
+       :gconfig: GSAMPLE_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, GSAMPLE_FSM, GSAMPLE_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)

ginsfsm/scaffolds/simple_websocket_server/+package+/main.py_tmpl

+# -*- encoding: utf-8 -*-
+"""
+{{package}}
+{{len(package)*'='}}
+
+It uses :class:`ginsfsm.protocols.wsgi.server.c_wsgi_server.GWsgiServer`.
+
+.. autofunction:: main
+
+"""
+
+from ginsfsm.gaplic import GAplic
+from ginsfsm.globals import (
+    set_global_main_gaplic,
+)
+from {{package}}.c_sample import GSample
+
+
+#===============================================================
+#                   Main
+#       Paste app factory.
+#       To run with gserve {{package}}.ini
+#===============================================================
+def main(global_config, **local_conf):
+    """ Entry point to run with gserve (PasteDeploy)
+    """
+    if 'gaplic-name' in local_conf:
+        gaplic_name = local_conf.pop('gaplic-name')
+    else:
+        raise Exception('You must supply an gaplic name ("gaplic-name")')
+
+    ga = GAplic(name=gaplic_name, roles='example_role', **local_conf)
+    set_global_main_gaplic(ga)
+
+    ga.create_gobj(
+        'sample',
+        GSample,
+        ga,
+        __unique_name__=True,
+    )
+    return ga
+
+
+if __name__ == "__main__":
+    """ You can run directly this file, without gserve.
+    """
+    import logging
+    logging.basicConfig(level=logging.DEBUG)
+
+    # simulate running from ini file
+    local_conf = {
+        'gaplic-name': '{{package}}',
+        '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,
+    }
+    ga = main({}, **local_conf)
+
+    try:
+        ga.start()
+    except (KeyboardInterrupt, SystemExit):
+        print('Program stopped')

ginsfsm/scaffolds/simple_websocket_server/+package+/tests/__init__.py

+#

ginsfsm/scaffolds/simple_websocket_server/+package+/tests/test_+package+.py_tmpl

+import unittest
+

ginsfsm/scaffolds/simple_websocket_server/CHANGES.txt_tmpl

+0.0.0
+-----
+
+-  Initial version

ginsfsm/scaffolds/simple_websocket_server/MANIFEST.in_tmpl

+prune .hg
+exclude push.sh
+include *.txt *.ini *.cfg *.rst
+recursive-include {{package}} *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml

ginsfsm/scaffolds/simple_websocket_server/README.rst_tmpl

+{{project}}
+{{len(project)*'='}}
+
+License
+-------
+
+Copyright (c) 2013
+
+{{project}} is released under terms of The MIT
+License MIT <http://www.opensource.org/licenses/mit-license>.
+
+Authors
+-------
+
+Your name

ginsfsm/scaffolds/simple_websocket_server/docs/DejaVuSans.ttf

Binary file added.

ginsfsm/scaffolds/simple_websocket_server/docs/README.txt

+Create a sphinx project
+=======================
+
+To build the documentation you must create a sphinx project in this directory
+with the 'sphinx-quickstart' command, with 'autodoc' extension enabled.
+I like the 'viewcode' extension too.
+
+
+Include the sphinx extensions
+=============================
+
+In order to build the ginsfsm documentation with svg graphics of smachine
+you must too add the extension 'ginsfsm.sphinxext' to the created conf.py file.
+
+The final result can be:
+
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'ginsfsm.sphinxext']
+
+
+Include the generated rst file
+==============================
+
+You must include the generated api_xxx.rst in the Contents of index.rst:
+
+.. toctree::
+   :maxdepth: 2
+
+   api_xxx
+
+being xxx the name of the created project.
+
+
+Don't compile sphinx?
+=====================
+
+If make html fails with the message:
+
+   "Could not import extension ginsfsm.sphinxext"
+
+check if the next modules are installed:
+
+   * docutils
+   * svgwrite
+   * PIL
+     Better install `pillow`, with pip.
+     `pillow` will need libfreetype*dev and libjpeg*dev libs to compile.

ginsfsm/scaffolds/simple_websocket_server/docs/api_+package+.rst_tmpl

+{{package}}
+{{len(package)*'='}}
+
+This is the main index page of your documentation. It should be written in
+`reStructuredText format <http://docutils.sourceforge.net/rst.html>`_.
+
+
+:mod:`{{package}}`
+{{(len(package) + 7) * '-'}}
+
+.. automodule:: {{package}}

ginsfsm/scaffolds/simple_websocket_server/setup.cfg_tmpl

+[nosetests]
+match = ^test
+nocapture = 1
+cover-package = {{package}}
+with-coverage = 1
+cover-erase = 1
+
+[egg_info]
+tag_build =
+tag_svn_revision = false
+tag_date = 0
+
+[easy_install]
+zip_ok = false

ginsfsm/scaffolds/simple_websocket_server/setup.py_tmpl

+# -*- encoding: utf-8 -*-
+
+import os
+import sys
+import {{package}}
+
+from setuptools import setup, find_packages
+
+if sys.version_info[:2] < (2, 6):
+    raise RuntimeError('Requires Python 2.6 or better')
+
+here = os.path.abspath(os.path.dirname(__file__))
+try:
+    README = open(os.path.join(here, 'README.rst')).read()
+    CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
+except IOError:
+    README = CHANGES = ''
+
+requires = ['ginsfsm']
+
+setup(name='{{package}}',
+    version={{package}}.__version__,
+    description='{{package}}',
+    long_description=README + '\n\n' + CHANGES,
+    classifiers=[
+        "Programming Language :: Python",
+    ],
+    author='',
+    author_email='',
+    url='',
+    license='MIT License',
+    keywords='gobj ginsfsm finite state machine fsm wsgi',
+    packages=find_packages(),
+    include_package_data=True,
+    zip_safe=False,
+    install_requires=requires,
+    tests_require=requires,
+    test_suite="{{package}}.tests",
+    entry_points="""\
+    [paste.app_factory]
+    main = {{package}}.main:main
+    """,
+)
     test_suite="ginsfsm.tests",
     entry_points="""
         [ginsfsm.scaffold]
+        multiple_wsgi=ginsfsm.scaffolds:MultipleWsgiTemplate
+        multi_pyramid_wsgi=ginsfsm.scaffolds:MultiplePyramidWsgiTemplate
         simple_gobj=ginsfsm.scaffolds:SimpleGObjTemplate
         simple_wsgi=ginsfsm.scaffolds:SimpleWsgiTemplate
         simple_pyramid=ginsfsm.scaffolds:SimplePyramidTemplate
-        multiple_wsgi=ginsfsm.scaffolds:MultipleWsgiTemplate
-        multi_pyramid_wsgi=ginsfsm.scaffolds:MultiplePyramidWsgiTemplate
+        simple_websocket_server=ginsfsm.scaffolds:SimpleWebsocketServerTemplate
 
         [console_scripts]
         gcreate = ginsfsm.scripts.gcreate:main