Example #1
0
class EchoClient(object):
    """WebSocket echo client."""

    def __init__(self, options):
        self._options = options
        self._socket = None

        self._logger = util.get_class_logger(self)

    def run(self):
        """Run the client.

        Shake hands and then repeat sending message and receiving its echo.
        """

        self._socket = socket.socket()
        self._socket.settimeout(self._options.socket_timeout)
        try:
            self._socket.connect((self._options.server_host,
                                  self._options.server_port))
            if self._options.use_tls:
                self._socket = _TLSSocket(
                    self._socket,
                    self._options.tls_module,
                    self._options.tls_version,
                    self._options.disable_tls_compression)

            version = self._options.protocol_version

            if (version == _PROTOCOL_VERSION_HYBI08 or
                version == _PROTOCOL_VERSION_HYBI13):
                self._handshake = ClientHandshakeProcessor(
                    self._socket, self._options)
            elif version == _PROTOCOL_VERSION_HYBI00:
                self._handshake = ClientHandshakeProcessorHybi00(
                    self._socket, self._options)
            else:
                raise ValueError(
                    'Invalid --protocol-version flag: %r' % version)

            self._handshake.handshake()

            self._logger.info('Connection established')

            request = ClientRequest(self._socket)

            version_map = {
                _PROTOCOL_VERSION_HYBI08: common.VERSION_HYBI08,
                _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13,
                _PROTOCOL_VERSION_HYBI00: common.VERSION_HYBI00}
            request.ws_version = version_map[version]

            if (version == _PROTOCOL_VERSION_HYBI08 or
                version == _PROTOCOL_VERSION_HYBI13):
                stream_option = StreamOptions()
                stream_option.mask_send = True
                stream_option.unmask_receive = False

                if self._options.deflate_frame is not False:
                    processor = self._options.deflate_frame
                    processor.setup_stream_options(stream_option)

                if self._options.use_permessage_deflate is not False:
                    framer = self._options.use_permessage_deflate
                    framer.setup_stream_options(stream_option)

                self._stream = Stream(request, stream_option)
            elif version == _PROTOCOL_VERSION_HYBI00:
                self._stream = StreamHixie75(request, True)

            for line in self._options.message.split(','):
                self._stream.send_message(line)
                if self._options.verbose:
                    print('Send: %s' % line)
                try:
                    received = self._stream.receive_message()

                    if self._options.verbose:
                        print('Recv: %s' % received)
                except Exception, e:
                    if self._options.verbose:
                        print('Error: %s' % e)
                    raise

            self._do_closing_handshake()
        finally:
Example #2
0
class KiwiSDRStreamBase(object):
    """KiwiSDR WebSocket stream client."""
    def __init__(self):
        self._socket = None
        self._decoder = None
        self._sample_rate = None
        self._isIQ = False
        self._version_major = None
        self._version_minor = None
        self._modulation = None

    def connect(self, host, port):
        self._prepare_stream(host, port, 'SND')
        pass

    def _process_message(self, tag, body):
        print 'Unknown message tag: %s' % tag
        print repr(body)

    def _prepare_stream(self, host, port, which):
        import mod_pywebsocket.common
        from mod_pywebsocket.stream import Stream
        from mod_pywebsocket.stream import StreamOptions
        self._socket = socket.socket()
        self._socket.settimeout(10)
        # self._socket.settimeout(float(self._options[13]))
        self._socket.connect((host, port))
        uri = '/%d/%s' % (int(time.time()), which)
        handshake = wsclient.ClientHandshakeProcessor(self._socket, host, port)
        handshake.handshake(uri)

        request = wsclient.ClientRequest(self._socket)
        request.ws_version = mod_pywebsocket.common.VERSION_HYBI13

        stream_option = StreamOptions()
        stream_option.mask_send = True
        stream_option.unmask_receive = False

        self._stream = Stream(request, stream_option)

    def _send_message(self, msg):
        self._stream.send_message(msg)

    def _set_auth(self, client_type, password=''):
        self._send_message('SET auth t=%s p=%s' % (client_type, password))

    def set_name(self, name):
        self._send_message('SET ident_user=%s' % name)

    def set_geo(self, geo):
        self._send_message('SET geo=%s' % geo)

    def set_inactivity_timeout(self, timeout):
        self._send_message('SET OVERRIDE inactivity_timeout=%d' % timeout)

    def _set_keepalive(self):
        self._send_message('SET keepalive')

    def _process_ws_message(self, message):
        tag = message[0:3]
        body = message[4:]
        self._process_message(tag, body)
Example #3
0
class KiwiSDRStreamBase(object):
    """KiwiSDR WebSocket stream base client."""
    def __init__(self):
        self._socket = None
        self._decoder = None
        self._sample_rate = None
        self._isIQ = False
        self._version_major = None
        self._version_minor = None
        self._modulation = None
        self._lowcut = 0
        self._highcut = 0
        self._frequency = 0
        self._stream = None

    def get_mod(self):
        return self._modulation

    def get_lowcut(self):
        return self._lowcut

    def get_highcut(self):
        return self._highcut

    def get_frequency(self):
        return self._frequency

    def connect(self, host, port):
        # self._prepare_stream(host, port, 'SND')
        pass

    def _process_message(self, tag, body):
        logging.warn('Unknown message tag: %s' % tag)
        logging.warn(repr(body))

    def _prepare_stream(self, host, port, which):
        self._stream_name = which
        self._socket = socket.create_connection(
            address=(host, port), timeout=self._options.socket_timeout)
        uri = '/%d/%s' % (self._options.timestamp, which)
        handshake = ClientHandshakeProcessor(self._socket, host, port)
        handshake.handshake(uri)

        request = ClientRequest(self._socket)
        request.ws_version = mod_pywebsocket.common.VERSION_HYBI13

        stream_option = StreamOptions()
        stream_option.mask_send = True
        stream_option.unmask_receive = False

        self._stream = Stream(request, stream_option)

    def _send_message(self, msg):
        if msg != 'SET keepalive':
            logging.debug("send SET (%s) %s", self._stream_name, msg)
        self._stream.send_message(msg)

    def _set_auth(self, client_type, password='', tlimit_password=''):
        if tlimit_password != '':
            if password == '':
                ## when the password is empty set it to '#' in order to correctly parse tlimit_password
                ## note that '#' as a password is being ignored by the kiwi server
                password = '******'
            self._send_message('SET auth t=%s p=%s ipl=%s' %
                               (client_type, password, tlimit_password))
        else:
            self._send_message('SET auth t=%s p=%s' % (client_type, password))

    def set_name(self, name):
        self._send_message('SET ident_user=%s' % (name))

    def set_geo(self, geo):
        self._send_message('SET geo=%s' % (geo))

    def _set_keepalive(self):
        self._send_message('SET keepalive')

    def _process_ws_message(self, message):
        tag = bytearray2str(message[0:3])
        body = message[3:]
        self._process_message(tag, body)
Example #4
0
class KiwiSDRStreamBase(object):
    """KiwiSDR WebSocket stream base client."""
    def __init__(self):
        self._socket = None
        self._decoder = None
        self._sample_rate = None
        self._isIQ = False
        self._version_major = None
        self._version_minor = None
        self._modulation = None
        self._stream = None

    def connect(self, host, port):
        # self._prepare_stream(host, port, 'SND')
        pass

    def _process_message(self, tag, body):
        logging.warn('Unknown message tag: %s' % tag)
        logging.warn(repr(body))

    def _prepare_stream(self, host, port, which):
        self._stream_name = which
        self._socket = socket.create_connection(
            address=(host, port), timeout=self._options.socket_timeout)
        uri = '/%d/%s' % (self._options.tstamp, which)
        handshake = ClientHandshakeProcessor(self._socket, host, port)
        handshake.handshake(uri)

        request = ClientRequest(self._socket)
        request.ws_version = mod_pywebsocket.common.VERSION_HYBI13

        stream_option = StreamOptions()
        stream_option.mask_send = True
        stream_option.unmask_receive = False

        self._stream = Stream(request, stream_option)

    def _send_message(self, msg):
        if msg != 'SET keepalive':
            logging.debug("send SET (%s) %s", self._stream_name, msg)
        self._stream.send_message(msg)

    def _set_auth(self, client_type, password=''):
        self._send_message('SET auth t=%s p=%s' % (client_type, password))

    def set_name(self, name):
        self._send_message('SET ident_user=%s' % (name))

    def set_geo(self, geo):
        self._send_message('SET geo=%s' % (geo))

    def set_inactivity_timeout(self, timeout):
        self._send_message('SET OVERRIDE inactivity_timeout=%d' % (timeout))

    def _set_keepalive(self):
        self._send_message('SET keepalive')

    def _process_ws_message(self, message):
        tag = bytearray2str(message[0:3])
        body = message[3:]
        self._process_message(tag, body)
Example #5
0
request = wsclient.ClientRequest(mysocket)
request.ws_version = mod_pywebsocket.common.VERSION_HYBI13

stream_option = StreamOptions()
stream_option.mask_send = True
stream_option.unmask_receive = False

mystream = Stream(request, stream_option)
print "Data stream active..."


# send a sequence of messages to the server, hardcoded for now
msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(zoom,offset),\
'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0']
for msg in msg_list:
    mystream.send_message(msg)
print "Starting to retrieve waterfall data..."
# number of samples to draw from server
length = options['length']
# create a numpy array to contain the waterfall data
wf_data = np.zeros((length, bins))
binary_wf_list = []
time = 0
while time<length:
    # receive one msg from server
    tmp = mystream.receive_message()
    if "W/F" in tmp: # this is one waterfall line
        tmp = tmp[16:] # remove some header from each msg
        if options['verbosity']:
            print time,
        spectrum = np.array(struct.unpack('%dB'%len(tmp), tmp) ) # convert from binary data to uint8
Example #6
0
class EchoClient(object):
    """WebSocket echo client."""
    def __init__(self, options):
        self._options = options
        self._socket = None

        self._logger = util.get_class_logger(self)

    def run(self):
        """Run the client.

        Shake hands and then repeat sending message and receiving its echo.
        """

        self._socket = socket.socket()
        self._socket.settimeout(self._options.socket_timeout)
        try:
            self._socket.connect(
                (self._options.server_host, self._options.server_port))
            if self._options.use_tls:
                self._socket = _TLSSocket(self._socket)

            self._handshake = ClientHandshakeProcessor(self._socket,
                                                       self._options)

            self._handshake.handshake()

            self._logger.info('Connection established')

            request = ClientRequest(self._socket)

            stream_option = StreamOptions()
            stream_option.mask_send = True
            stream_option.unmask_receive = False

            if self._options.use_permessage_deflate is not False:
                framer = self._options.use_permessage_deflate
                framer.setup_stream_options(stream_option)

            self._stream = Stream(request, stream_option)

            for line in self._options.message.split(','):
                self._stream.send_message(line)
                if self._options.verbose:
                    print('Send: %s' % line)
                try:
                    received = self._stream.receive_message()

                    if self._options.verbose:
                        print('Recv: %s' % received)
                except Exception as e:
                    if self._options.verbose:
                        print('Error: %s' % e)
                    raise

            self._do_closing_handshake()
        finally:
            self._socket.close()

    def _do_closing_handshake(self):
        """Perform closing handshake using the specified closing frame."""

        if self._options.message.split(',')[-1] == _GOODBYE_MESSAGE:
            # requested server initiated closing handshake, so
            # expecting closing handshake message from server.
            self._logger.info('Wait for server-initiated closing handshake')
            message = self._stream.receive_message()
            if message is None:
                print('Recv close')
                print('Send ack')
                self._logger.info('Received closing handshake and sent ack')
                return
        print('Send close')
        self._stream.close_connection()
        self._logger.info('Sent closing handshake')
        print('Recv ack')
        self._logger.info('Received ack')
Example #7
0
stream_option = StreamOptions()
stream_option.mask_send = True
stream_option.unmask_receive = False

mystream = Stream(request, stream_option)
print "Data stream active..."

comp_2 = options['compression-2']
if comp_2: print "Using compression-2"

# send a sequence of messages to the server, hardcoded for now
# max wf speed, no compression
msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(0,0),\
'SET maxdb=0 mindb=-100', 'SET wf_speed=%d'%(options["speed"]), 'SET wf_comp=%d'%(2 if comp_2 else 0)]
for msg in msg_list:
    mystream.send_message(msg)
print "Starting to retrieve waterfall data..."
# number of samples to draw from server
# create a numpy array to contain the waterfall data
wf_data = np.zeros(bins)
if plt:
    plt.figure()
    plt.grid(True)
    plt.ion()
    plt.show()

last_keepalive = 0

tk_root = Tk()
tk_root.title("kiwi_rss.py")
rss_offset = DoubleVar(value=options["rss_offset"])
Example #8
0
handshake_wf.handshake(uri)
request_wf = wsclient.ClientRequest(kiwisocket)
request_wf.ws_version = mod_pywebsocket.common.VERSION_HYBI13
stream_option_wf = StreamOptions()
stream_option_wf.mask_send = True
stream_option_wf.unmask_receive = False

wf_stream = Stream(request_wf, stream_option_wf)
print ("Waterfall data stream active...")

# send a sequence of messages to the server, hardcoded for now
# max wf speed, no compression
msg_list = ['SET auth t=kiwi p=%s'%kiwi_password, 'SET zoom=%d start=%d'%(zoom,cnt),\
'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0', 'SET maxdb=-10 mindb=-110']
for msg in msg_list:
    wf_stream.send_message(msg)
print ("Starting to retrieve waterfall data...")

########################### SND connection
# connect to kiwi server
kiwisocket_snd = None
snd_stream = None
kiwi_audio = options["audio_on"]
print(kiwi_audio)
if kiwi_audio:
    print ("Trying to contact server...")
    try:
        kiwisocket_snd = socket.socket()
        kiwisocket_snd.connect((kiwihost, kiwiport))

        uri = '/%d/%s' % (int(time.time()), 'SND')
Example #9
0
request = wsclient.ClientRequest(mysocket)
request.ws_version = mod_pywebsocket.common.VERSION_HYBI13

stream_option = StreamOptions()
stream_option.mask_send = True
stream_option.unmask_receive = False

mystream = Stream(request, stream_option)
print("Data stream active...")

# send a sequence of messages to the server, hardcoded for now
# max wf speed, no compression
msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(zoom,cnt),\
'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0', 'SET maxdb=-10 mindb=-110']
for msg in msg_list:
    mystream.send_message(msg)
print("Starting to retrieve waterfall data...")
length = DISPLAY_HEIGHT
# create a numpy array to contain the waterfall data
wf_data = np.zeros((length, int(WF_BINS)))
binary_wf_list = []

while True:
    tmp = mystream.receive_message()
    if "W/F" in tmp:  # this is one waterfall line
        tmp = tmp[16:]  # remove some header from each msg
        spectrum = np.ndarray(len(tmp), dtype='B',
                              buffer=tmp)  # convert from binary data to uint8
        wf = spectrum
        wf = -(255 - wf)  # dBm
        wf = wf - 13  # typical Kiwi wf cal when zoomed out at max