''' Present an interactive function explorer with slider widgets.

Scrub the sliders to change the properties of the ``sin`` curve, or
type into the title text box to update the title of the plot.

Use the ``bokeh serve`` command to run the example by executing:

    bokeh serve sliders.py

at your command prompt. Then navigate to the URL

    http://localhost:5006/sliders

in your browser.

'''

import numpy as np

from bokeh.plotting import Figure
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import HBox, Slider, TextInput, VBoxForm
from bokeh.io import curdoc

import zmq


N = 200
x = np.linspace(0,200,N)
y = np.linspace(0,200,N)    # dummy data
source = ColumnDataSource(data=dict(x=x, y=y))

# Set up plot
plot = Figure(plot_height=400, plot_width=400, title="my sine wave",
              tools="crosshair,pan,reset,resize,save,wheel_zoom",
              x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

# Set up widgets
text = TextInput(title="title", value='my sine wave')
offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0)
phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1)

# Set up callbacks
def update_title(attrname, old, new):
    plot.title = text.value

text.on_change('value', update_title)

# Set up layouts and add to document
inputs = VBoxForm(children=[text, offset, amplitude, phase, freq])

curdoc().add_root(HBox(children=[inputs, plot], width=800))

context = zmq.Context()
zmq_socket = context.socket(zmq.PULL)
zmq_socket.connect("tcp://10.16.32.180:9999")

poller = zmq.Poller()
poller.register(zmq_socket, zmq.POLLIN)

def recv_callback():
    socks = dict(poller.poll(1))
    if zmq_socket in socks and socks[zmq_socket] == zmq.POLLIN:
        raw_data = np.frombuffer(zmq_socket.recv(),dtype=np.complex64)
        signal = raw_data / 1.0   # convert to proper type
        
        if(signal.size >199):
            y = signal.real[0:200]
            source.data = dict(x=x,y=y)

curdoc().add_periodic_callback(recv_callback, 50) #callback.interval)
