1b2732e9dSimarom# coding: utf-8
2b2732e9dSimarom"""miscellaneous zmq_utils wrapping"""
3b2732e9dSimarom
4b2732e9dSimarom# Copyright (C) PyZMQ Developers
5b2732e9dSimarom# Distributed under the terms of the Modified BSD License.
6b2732e9dSimarom
7b2732e9dSimaromfrom ._cffi import ffi, C
8b2732e9dSimarom
9b2732e9dSimaromfrom zmq.error import ZMQError, _check_rc, _check_version
10b2732e9dSimaromfrom zmq.utils.strtypes import unicode
11b2732e9dSimarom
12b2732e9dSimaromdef has(capability):
13b2732e9dSimarom    """Check for zmq capability by name (e.g. 'ipc', 'curve')
14b2732e9dSimarom
15b2732e9dSimarom    .. versionadded:: libzmq-4.1
16b2732e9dSimarom    .. versionadded:: 14.1
17b2732e9dSimarom    """
18b2732e9dSimarom    _check_version((4,1), 'zmq.has')
19b2732e9dSimarom    if isinstance(capability, unicode):
20b2732e9dSimarom        capability = capability.encode('utf8')
21b2732e9dSimarom    return bool(C.zmq_has(capability))
22b2732e9dSimarom
23b2732e9dSimaromdef curve_keypair():
24b2732e9dSimarom    """generate a Z85 keypair for use with zmq.CURVE security
25b2732e9dSimarom
26b2732e9dSimarom    Requires libzmq (≥ 4.0) to have been linked with libsodium.
27b2732e9dSimarom
28b2732e9dSimarom    Returns
29b2732e9dSimarom    -------
30b2732e9dSimarom    (public, secret) : two bytestrings
31b2732e9dSimarom        The public and private keypair as 40 byte z85-encoded bytestrings.
32b2732e9dSimarom    """
33b2732e9dSimarom    _check_version((3,2), "monitor")
34b2732e9dSimarom    public = ffi.new('char[64]')
35b2732e9dSimarom    private = ffi.new('char[64]')
36b2732e9dSimarom    rc = C.zmq_curve_keypair(public, private)
37b2732e9dSimarom    _check_rc(rc)
38b2732e9dSimarom    return ffi.buffer(public)[:40], ffi.buffer(private)[:40]
39b2732e9dSimarom
40b2732e9dSimarom
41b2732e9dSimaromclass Stopwatch(object):
42b2732e9dSimarom    def __init__(self):
43b2732e9dSimarom        self.watch = ffi.NULL
44b2732e9dSimarom
45b2732e9dSimarom    def start(self):
46b2732e9dSimarom        if self.watch == ffi.NULL:
47b2732e9dSimarom            self.watch = C.zmq_stopwatch_start()
48b2732e9dSimarom        else:
49b2732e9dSimarom            raise ZMQError('Stopwatch is already runing.')
50b2732e9dSimarom
51b2732e9dSimarom    def stop(self):
52b2732e9dSimarom        if self.watch == ffi.NULL:
53b2732e9dSimarom            raise ZMQError('Must start the Stopwatch before calling stop.')
54b2732e9dSimarom        else:
55b2732e9dSimarom            time = C.zmq_stopwatch_stop(self.watch)
56b2732e9dSimarom            self.watch = ffi.NULL
57b2732e9dSimarom            return time
58b2732e9dSimarom
59b2732e9dSimarom    def sleep(self, seconds):
60b2732e9dSimarom        C.zmq_sleep(seconds)
61b2732e9dSimarom
62b2732e9dSimarom__all__ = ['has', 'curve_keypair', 'Stopwatch']
63