Commits

Szymon Wróblewski committed 3eb6f0d

updated documentation, changed register parameters

  • Participants
  • Parent commits 5ae0116

Comments (0)

Files changed (8)

doc/source/event.rst

    :synopsis: Module defining Pygame events.
 
 
+.. data:: NETWORK
+
+.. data:: NET_CONNECTED
+
+.. data:: NET_DISCONNECTED
+
+.. data:: NET_RECEIVED
+
+.. note::
+   
+   If you plan to change value of :const:`NETWORK` with :func:`init`, then use:: 
+      
+      import pygame_network.event as event
+      # rather than
+      # from pygame_network.event import NETWORK # wrong
+   
+    
+
+Event attributes
+----------------
+
 Connected event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_CONNECTED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
+   | ``type`` = :const:`event.NETWORK`
+   | ``net_type`` = :const:`event.NET_CONNECTED`
+   | ``connection`` -- connection
 
 Disconnected event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_DISCONNECTED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
+   | ``type`` = :const:`event.NETWORK`
+   | ``net_type`` = :const:`event.NET_DISCONNECTED`
+   | ``connection`` -- connection
 
 Received event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_RECEIVED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-   | ``event.channel`` -- channel of connection
-   | ``event.packet`` -- received packet
-   | ``event.p_id`` -- packet identifier
-   | ``event.p_type`` -- packet type
+   | ``type`` = :const:`event.NETWORK`
+   | ``net_type`` = :const:`event.NET_RECEIVED`
+   | ``connection`` -- connection
+   | ``channel`` -- channel of connection
+   | ``message`` -- received message
+   | ``msg_id`` -- message identifier
+   | ``msg_type`` -- message type
 
-Response event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_RESPONSE`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-   | ``event.channel`` -- channel of connection
-   | ``event.packet`` -- received packet
-   | ``event.p_id`` -- packet identifier
-   | ``event.p_type`` -- packet type
 
-Example::
+Example
+-------
+::
 
    for e in pygame.event.get():
        if e.type == NETWORK:
            elif e.net_type == NET_DISCONNECTED:
                print 'disconnected'
            elif e.net_type == NET_RECEIVED:
-               if e.p_type == packet.chat_msg:
-                   print '%s: %s' % (e.packet.player, e.packet.msg)
+               if e.msg_type == message.chat_msg:
+                   print '%s: %s' % (e.message.player, e.message.msg)
                else:
-                   print 'received:', e.packet
-           elif e.net_type == NET_RESPONSE:
-               print 'response @%d: %s' % (e.p_id, e.packet)
+                   print 'received:', e.message
+                   
+   

doc/source/message.rst

+:mod:`message` Module
+=====================
+
+.. module:: message
+   :synopsis: Message factory and predefined messages.
+   
+
+.. class:: MessageFactory
+
+   Class allowing to register new message types and pack/unpack them.
+   
+   Example::
+   
+      chat_msg = MessageFactory.register('chat_msg', ('player', 'msg'))
+      data = MessageFactory.pack(chat_msg('Tom', 'Test message'))
+      received_msg = MessageFactory.unpack(data)
+      player = received_msg.player
+      msg = received_msg.msg
+
+   .. note::
+      
+      You can create instances of :class:`MessageFactory`, when you want to
+      separate messages for different connections in Client.
+      
+   
+   .. classmethod:: register(name, field_names[, kwargs])
+   
+      Register new message type
+      
+      :param name: name of message class
+      :param field_names: list of names of message fields
+      :param kwargs: keyword arguments for send method
+      :return: packet (namedtuple)
+      
+
+Predefined messages
+-------------------
+
+.. class:: chat_msg(player, msg)
+
+   :param player: player name
+   :param msg: message
+
+
+.. class:: update_remoteobject(type_id, obj_id, variables)
+
+   Message used by :class:`syncobject.SyncObjectManager` to update state of
+   :class:`syncobject.RemoteObject`.
+
+   :param type_id: identifier of object type
+   :param obj_id: identifier of object instance
+   :param variables: list of changed object variables
+
+
+Small FAQ
+---------
+
+Why I have to register message? Can't I just use dictionary to send it?
+   :meth:`register` creates a compact data structure -
+   :func:`namedtuple <collections.namedtuple>`, which contains only essential
+   data, reducing overall amount of data to send. Take a look at example below
+   and compare sizes of packed dictionary and structure created by
+   :class:`MessageFactory`.
+
+      >>> import msgpack
+      >>> m1 = msgpack.packb({'action':'chat_msg', 'player':'Tom', 'msg':'Test message'})
+      >>> m1, len(m1)
+      ('\x83\xa6action\xa8chat_msg\xa6player\xa3Tom\xa3msg\xacTest message', 45)
+      >>> import pygame_network as net
+      >>> net.init()
+      12:33:14:INFO:Using enet network module
+      12:33:14:INFO:Using msgpack serialization module
+      >>> chat_msg = net.register('chat_msg', ('player', 'msg'))
+      >>> m2 = net.message.MessageFactory.pack(0, chat_msg('Tom', 'Test message'))
+      >>> m2, len(m2)
+      ('\x94\x03\x00\xa3Tom\xacTest message', 20)
+
+   The only drawback of this method is the need to register the same messages
+   in the same order in client and server.
+
+Why order of creating messages is important?
+   As You may noticed in previous example, there is no string with type of
+   message in packed data. That's because type is encoded as integer,
+   depending on order of creation.

doc/source/packet.rst

-:mod:`packet` Module
-====================
-
-.. module:: packet
-   :synopsis: Packet manager and predefined packets.
-
-
-.. class:: PacketManager
-
-   Class allowing to register new packet types and send them.
-   
-   It is used by :class:`Client` and :class:`Server`.
-   
-   Example::
-   
-       chat_msg = PacketManager.register('chat_msg', ('player', 'msg'), enet.PACKET_FLAG_RELIABLE)
-       PacketManager.send(peer, 0, chat_msg('Tom', 'Test message'))
-   
-   
-   .. classmethod:: PacketManager.get_packet(name)
-   
-      Returns packet class with given name
-   
-      :param name: name of packet
-      :return: packet (namedtuple)
-      
-   
-   .. classmethod:: PacketManager.register(name, field_names[, flags])
-   
-      Register new packet type and return class
-      
-      :param name: name of packet class
-      :param field_names: list of names of packet fields
-      :param flags: 
-         enet flags used when sending packet
-         (default :const:`enet.PACKET_FLAG_RELIABLE`)
-      :return: packet (namedtuple)
-      
-
-Predefined packets
-------------------
-
-.. class:: chat_msg(player, msg)
-
-   :param player: player name
-   :param msg: message
-
-
-.. class:: update_remoteobject(type_id, obj_id, variables)
-
-   Packet used by :class:`syncobject.SyncObjectManager` to update state of
-   :class:`syncobject.RemoteObject`.
-
-   :param type_id: identifier of object type
-   :param obj_id: identifier of object instance
-   :param variables: list of changed object variables
-

doc/source/pygame_network.rst

    
    connection
    event
-   packet
+   message
    syncobject
 
 
 Functions
 ---------
 
+.. function:: init([events, event_val, logging_lvl, network, serialization])
+
+   Initialize network library.
+   
+   :param events: allow sending Pygame events (default False)
+   :param event_val:
+      set :const:`event.NETWORK` as :const:`pygame.USEREVENT` + :attr:`event_val` (default 1)
+   :param logging_lvl:
+      level of logging messages (default :const:`logging.INFO`
+      (see: :ref:`logging-basic-tutorial`), None to skip initializing
+      logging module)
+   :param network:
+      name(s) of network library adapters, first available will be used
+      (default ['enet'])
+   :type network: string or list of strings
+   :param serialization:
+      name(s) of serialization library adapters, first available will be used
+      (default ['msgpack', 'json'])
+   :type serialization: string or list of strings
+   
+   .. note::
+   
+      Because of the dynamic loading of network library adapter, 
+      :class:`Client`, :class:`Server` and :class:`State` classes will only be
+      available after initialization.
+
+
 .. function:: register(name, field_names[, flags])
    
    Register new packet type and return class by calling 
-   :meth:`packet.PacketManager.register` 
+   :meth:`message.MessageFactory.register`
    
    :param name: name of packet class
    :param field_names: list of names of packet fields

pygame_network/__init__.py

 
 def init(events=False, event_val=1, logging_lvl=logging.INFO,
          network=('enet',), serialization=('msgpack', 'json')):
+    """Initialize network library.
+
+    events - allow sending Pygame events (default False)
+    event_val - set event ID as event_val + pygame.USEREVENT (default 1)
+    logging_lvl - level of logging messages (default logging.INFO, None to skip
+                  initializing logging module
+    network - string or list of strings with names of network library adapters,
+              first available will be used
+    serialization - string or list of strings with names of serialization
+                    library adapters, first available will be used
+
+    Note: Because of the dynamic loading of network library adapter, Client,
+        Server and State classes will only be available after initialization.
+    """
     global Client, Server, State
     _logger = logging.getLogger(__name__)
     if logging_lvl is not None:
         return
     message.s_lib = smod
     _logger.info("Using %s serialization module", name)
-    print nmod
     if events:
         _logger.info("Enabling pygame events")
         import event

pygame_network/event.py

            'NET_DISCONNECTED',
            'NET_RECEIVED')
 
-NETWORK = -1
+NETWORK = 30
 NET_CONNECTED = 0
 NET_DISCONNECTED = 1
 NET_RECEIVED = 2

pygame_network/message.py

     """Class allowing to register new message types and pack/unpack them.
 
     example:
-        chat_msg = MessageFactory.register('chat_msg', ('player', 'msg'),
-                                          enet.PACKET_FLAG_RELIABLE)
-        MessageFactory.pack(chat_msg('Tom', 'Test message'))
+        chat_msg = MessageFactory.register('chat_msg', ('player', 'msg'))
+        data = MessageFactory.pack(chat_msg('Tom', 'Test message'))
+        received_msg = MessageFactory.unpack(data)
+        player = received_msg.player
+        msg = received_msg.msg
     """
     _message_names = {}  # mapping name -> message
     _message_types = WeakValueDictionary()  # mapping type_id -> message
         self._hash = None
 
     @classmethod
-    def register(cls, name, field_names=tuple(), channel=0, flags=enet.PACKET_FLAG_RELIABLE):
+    def register(cls, name, field_names=tuple(), **kwargs):
         """Register new message type
 
-        MessageFactory.register(name, field_names, channel, flags): return class
+        MessageFactory.register(name, field_names[, **kwargs]): return class
 
         name - name of message class
         field_names - names of message fields
+        args - additional arguments for sending message
 
         Warning: All packets must be registered in THE SAME ORDER in client and
         server, BEFORE creating any connection.
         packet = namedtuple(name, field_names)
         cls._message_names[name] = packet
         cls._message_types[type_id] = packet
-        cls._message_params[packet] = (type_id, channel, flags)
+        cls._message_params[packet] = (type_id, kwargs)
         return packet
 
     @classmethod
 
     @classmethod
     def get_params(cls, message):
-        """Return tuple containing type_id, channel and sending flags
+        """Return tuple containing type_id, and sending keyword args
 
-        MessageFactory.get_params(message): return (int, int, int)
+        MessageFactory.get_params(message): return (int, dict)
 
         message - message class created by register
         """
     'type_id',
     'obj_id',
     'variables'
-), 1, 0)
+), channel=1, flags=0)
 chat_msg = MessageFactory.register('chat_msg', (
     'player',
     'msg'

pygame_network/network/enet_adapter/connection.py

         self._send(message, *args, **kwargs)
 
     def _send(self, message, *args, **kwargs):
-        _, channel, flags = self._message_factory.get_params(message)
-        flags = kwargs.get('flags', flags)
-        channel = kwargs.get('channel', channel)
+        params = self._message_factory.get_params(message)[1]
+        flags = kwargs.get('flags', params.get('flags', enet.PACKET_FLAG_RELIABLE))
+        channel = kwargs.get('channel', params.get('channel', 0))
         message_id = self._message_cnt = self._message_cnt + 1
         name = message.__name__
         message = message(*args, **kwargs)