3
3kU^µ  ã               @   sV   d dl Z d dlmZ ddlmZmZ ddlmZ dd„ ZdZ	d
d„ Z
G dd„ dƒZdS )é    N)ÚZMQErroré   )Úsocket_namesÚneeds_codec)ÚMessagec             C   sF   y| j |ƒ W n2 tk
r@ } ztd|› �ƒ ‚ W Y dd}~X nX |S )zÂBind socket to address

    Any error is printed and reraised.

    :param sock: ZeroMQ socket object
    :param addr: address in ZeroMQ format
    :returns: the address
    :rtype: string

    zfailed to bind N)Úbindr   Úprint)ÚsockÚaddrÚe© r   ú%/home/yuhw/zmq/zio/python/zio/port.pyÚbind_address   s    r   é À  éÿÿ  c             C   s‚   t |ƒtkr&|dkr&t| d||f ƒS d| }y| j|ftžŽ }W n2 tk
rt } ztd|› �ƒ ‚ W Y dd}~X nX d||f S )zÖBind socket TCP host and port

    :param sock: ZeroMQ socket object
    :param host: name or IP address of host to bind
    :param port: TCP port number
    :returns: ZeroMQ address string
    :rtype: string

    r   ztcp://%s:%dztcp://%szfailed to bind N)ÚtypeÚintr   Úbind_to_random_portÚephemeral_port_ranger   r   )r	   ÚhostÚportr
   r   r   r   r   Úbind_hostport   s    
r   c               @   sl   e Zd Zddd„Zdd„ Zdd„ Zdd	„ Zddd„Zdd„ Zdd„ Z	ddd„Z
dd„ Zdd„ Zddd„ZdS )ÚPortú	127.0.0.1c             C   sŒ   || _ || _t|ƒtkr2tjƒ | _| jj|ƒ| _n|| _d| _	t
ƒ | _t
ƒ | _tƒ | _d| _t
ƒ | _t
ƒ | _tjƒ | _| jj| jtjƒ dS )zË
        Create a Port with a name and a ZeroMQ socket type.

        Ports are typically not meant to be constructed directly by
        application code but instead through a managing zio.Node
        NF)ÚnameÚ	_hostnamer   r   ÚzmqÚContextÚctxÚsocketr	   ÚoriginÚlistÚto_bindÚto_connÚdictÚheadersÚ	is_onlineÚ	connectedÚboundÚPollerÚpollerÚregisterÚPOLLIN)Úselfr   r	   Zhostnamer   r   r   Ú__init__5   s    

zPort.__init__c             C   s6   d| j t| jj t| jƒt| jƒt| jƒt| jƒf S )Nz6[port %s]: type:%s binds:%d(todo:%d) conns:%d(todo:%d))	r   r   r	   r   Úlenr(   r"   r'   r#   )r-   r   r   r   Ú__str__M   s    zPort.__str__c             G   s>   |s| j j| jdfƒ dS t|ƒdkr.tdƒ‚| j j|ƒ dS )zÜ
        Request a bind.

        If spec is None, do a default/ephemeral bind.
        If spec is a string, it is assumed to be a ZeroMQ adddress.
        If spec is a tuple ithen it is a (hostname,portnumber).
        r   Né   zunsupported bind specification)r"   Úappendr   r/   Ú
ValueError)r-   Úspecr   r   r   r   S   s    z	Port.bindc             G   s*   | st |ƒdkrtdƒ‚| jj|ƒ dS )z¡
        Request a connect.

        If a single string is given it is a ZeroMQ address.
        If two strings are given they are (nodename, portname).
        r1   z!unsupported connect specificationN)r/   r3   r#   r2   )r-   r4   r   r   r   Úconnectd   s    zPort.connectÚ c             C   s&   | j jtjk	rdS | j jtj|ƒ dS )zº
        Subscribe to a PUB/SUB topic.

        This method is only meaningful if our socket is a SUB and then
        it MUST be called if messages are expected to be received.
        N)r	   r   r   ÚSUBÚsetsockopt_stringÚ	SUBSCRIBE)r-   Úprefixr   r   r   Ú	subscribeo   s    zPort.subscribec             O   sJ   xDt |ƒ|g D ]2}x,|jƒ D ] \}}d| j|f }|| j|< qW qW dS )a  
        Add one or more headers or dictionaries of headers.

        Every key will be wrapped into ZIO port header convention.
        The headers will appear to the network as

        zio.port.<portname>.<key> = <value>

        The self.headers collects these.
        zzio.port.%s.%sN)r!   Úitemsr   r%   )r-   ÚargsÚkwargsÚdÚkÚvÚkeyr   r   r   Úadd_headers{   s
    zPort.add_headersc             C   sx   xT| j D ]J}t|ƒdkr*t| jf|žŽ }nt| j|d ƒ}| jj|ƒ | j|d� qW tƒ | _ | jt	| jj
 d� | jS )a  
        Actually perform binds.

        Return dictionary suitable for use as peer headers the give
        information about the binds.

        This must be called prior to any call of .online() and is
        intended to be used by a zio.Node which holds this zio.Port.
        r1   r   )Úaddress)r   )r"   r/   r   r	   r   r(   r2   rC   r!   r   r   r%   )r-   r4   r
   r   r   r   Údo_bindsŒ   s    
zPort.do_bindsNc             C   sú   | j r
dS d| _ xÜ| jD ]Ò}t|ƒdkrZt|d ƒtkrZ|d }| jj|ƒ | jj|ƒ q|std| j	|f }t
|ƒ‚|\}}|j|ƒ}|s–td| ƒ‚xP|D ]H}|j| }d|› d�}	|jj|	d	ƒ}
|
sÊqœ| jj|
ƒ | jj|
ƒ qœqœW qqW tƒ | _dS )
zÂ
        Bring this port online.

        If no peer is given then indirect connects will fail.

        This method is intended for use by a zio.Node which holds this
        zio.Port.
        NTr   r   z,[port %s]: no peer given, can not connect %szfailed to wait for "%s"z	zio.port.z.addressF)r&   r#   r/   r   Ústrr	   r5   r'   r2   r   r3   ZwaitforÚRuntimeErrorÚpeersr%   Úgetr!   )r-   ÚpeerZconnÚerrÚnodenameZportnameZuuidsZuuidÚpirB   r
   r   r   r   Úonline¤   s:    	 


zPort.onlinec             C   sX   | j s
dS d| _ x| jD ]}| jj|ƒ qW x| jD ]}| jj|ƒ q4W tƒ }tƒ }dS )zl
        Bring this port offline.

        This unbinds and disconnects and forgets their addresses
        NF)r&   r'   r	   Ú
disconnectr(   Úunbindr!   )r-   r
   Zm_boundZm_connectedr   r   r   ÚofflineÌ   s     zPort.offlinec             C   sp   | j dk	r| j |j_ t| jjƒrX|jƒ }| jjtjkrJ| jj||j	d� ql| jj|ƒ n|j
ƒ }| jj|ƒ dS )zˆ
        Send a zio.Message

        This modifies the message prior to sending to set the origin
        if this port has one.
        N)Ú
routing_id)r    Úcoordr   r	   r   Úencoder   ÚSERVERÚsendrR   ÚtopartsÚsend_multipart)r-   ÚmsgÚdataÚpartsr   r   r   rV   Û   s    

z	Port.sendc             C   sŒ   t | jj|ƒƒ}| j|krdS t| jjƒrp| jjtjkrX| jjdd�}|sNdS t	|d�S | jjdd�}t	|d�S | jj
ƒ }|s‚dS t	|d�S )z�
        Receive and return a zio.Message waiting up to a timeout 

        If timeout is reached then None is returned.
        NF)Úcopy)ÚframeT)Úencoded)r[   )r$   r*   Úpollr	   r   r   r   rU   Úrecvr   Úrecv_multipart)r-   ÚtimeoutÚwhichr]   rZ   r[   r   r   r   r`   ï   s    



z	Port.recv)r   )r6   )N)N)Ú__name__Ú
__module__Ú__qualname__r.   r0   r   r5   r;   rC   rE   rN   rQ   rV   r`   r   r   r   r   r   4   s   


(r   )r   r   )r   Ú	zmq.errorr   Úutilr   r   Úmessager   r   r   r   r   r   r   r   r   Ú<module>   s   