class CanvasPanel3(wx.Panel):
    w = 0
    draw_map = False

    def __init__(self,
                 parent,
                 sf,
                 shapes2,
                 size,
                 use_grid,
                 permission=False,
                 sites_bouger=[]):
        wx.Panel.__init__(self, parent, size=size)
        self.SetBackgroundColour(wxc.NamedColour("BLACK"))
        self.permission = permission

        self.figure = Figure(dpi=65)  #figsize=(16,9))
        self.figure.set_size_inches(1, 1, forward=True)

        #self.axes.xaxis.set_ticks_position('bottom')
        #self.axes.yaxis.set_ticks_position('left')
        self.axes = self.figure.add_subplot(
            111, frameon=False)  #plt.subplot(111, projection="lambert")

        user_grid = False
        if use_grid:

            d = (0, 0.01, 0.99, 0.99)
            self.axes.grid(use_grid)

        else:
            #self.axes = self.figure.add_subplot(111, frameon=False)
            d = (0, 0, 0.999, 0.999)
            self.axes.get_xaxis().set_visible(False)
            self.axes.get_yaxis().set_visible(False)

        self.w, self.h = self.figure.get_size_inches() * self.figure.dpi
        CanvasPanel3.w = size[0]
        self.axes.set_position(
            d
        )  # x-top-left-corner, y-top-left-corner, x-width, y-width (in pixels)

        self.canvas = FigureCanvas(self, -1, self.figure)

        if permission:
            self.axes.clear()
            self.canvas.Update()
            recs = sf.records()

            shapes = sf.shapes
            Nshp = len(shapes)
            """
			for nshp in xrange(Nshp):
				ptchs = []
				pts = array(shapes[nshp].points)
				if shapes[nshp].shapeType == 5:
					prt = shapes[nshp].parts
					par = list(prt) + [pts.shape[0]]
					for pij in xrange(len(prt)):
						ptchs.append(Polygon(pts[par[pij]:par[pij+1]]))
			
				self.axes.add_collection(PatchCollection(ptchs,facecolor='none',edgecolor='b', linewidths=2))
			"""
            """
			data = [(50, 50), (70, 70)]
			pp = []
			for x, y in data :
				c = Circle((x,y), 0.5)
				pp.append(c)
			
			p = PatchCollection(pp, cmap=mpl.cm.jet, alpha=0.4)
			self.axes.add_collection(PatchCollection(p,facecolor='none',edgecolor='r', linewidths=2))
			"""
            #self.axes.scatter(50, 50, s=10, c='g', marker='^', label='Two Fires')
            #print "Len shapes :", len(shapes)
            """
			for obj in range(0, len(shapes)):
						for pt in range(0, len(shapes[obj].points)):
							if shapes[obj].points[pt] != shapes2[obj].points[pt]:
								print "------------------------------------"
								print "Not equal !"
								print "Original :",shapes[obj].points[pt], obj, pt
								print "Modifie :",shapes2[obj].points[pt], obj, pt
			"""

            #t = [ [147.83058185027457, -42.27884684129017] ,[146.66141197230283, -41.096120875508596] ]

            self.axes.triplot(Triangulation.points[:, 0],
                              Triangulation.points[:, 1], Triangulation.triang)
            self.axes.plot(Triangulation.points[:, 0],
                           Triangulation.points[:, 1], 'r.')

            shapes = shapes2
            Nshp = len(shapes)
            import random
            color = random.choice(["g", "r", "y"])
            for nshp in xrange(Nshp):
                ptchs = []
                pts = array(shapes[nshp].points)
                if shapes[nshp].shapeType == 5:
                    prt = shapes[nshp].parts
                    par = list(prt) + [pts.shape[0]]
                    for pij in xrange(len(prt)):
                        ptchs.append(Polygon(pts[par[pij]:par[pij + 1]]))
                self.axes.add_collection(
                    PatchCollection(ptchs,
                                    facecolor='none',
                                    edgecolor="black",
                                    linewidths=1.5))
            """
			pp = [
			      [146.661411968, -41.09612087949996] , [146.66141197230283, -41.096120875508596]

					#(142.89579288266205, -43.922664989702909), 
					#(142.89579288266205, -43.922664989702909)
				]
			"""
            #ptchs.append(Circle(pp[0], 0.001))

            #self.axes.add_collection(PatchCollection(ptchs,facecolor='r',edgecolor="r", linewidths= 5))
            #ptchs.append(Circle(pp[1], 0.001))
            #self.axes.add_collection(PatchCollection(ptchs,facecolor='g',edgecolor="g", linewidths= 0.1, alpha=0.9))
            original = {
                'family': 'Courier New',
                'color': 'green',
                'weight': 'bold',
                'size': 12,
            }
            modified = {
                'family': 'Courier New',
                'color': 'red',
                'weight': 'bold',
                'size': 12,
            }

            usb = self.GetTopLevelParent(
            ).rightpanel.get_original_per_sites_bouger()

            for pp in sites_bouger:
                self.axes.plot(pp[0][0][0], pp[0][0][1], 'r+')  # modifie
                self.axes.plot(pp[1][0][0], pp[1][0][1], 'g+')  # original
                #self.axes.text(pp[0][0][0], pp[0][0][1], "Modifie" , fontdict = modified, ha='left')
                #self.axes.text(pp[1][0][0], pp[1][0][1], "Original" , fontdict = original, ha='left')
                for tt in usb:
                    if tt == complex(pp[0][0][0], pp[0][0][1]):
                        v = usb[tt]
                        self.axes.text(pp[0][0][0],
                                       pp[0][0][1],
                                       u"Modifié ( " + str(v[2]) + " )",
                                       fontdict=modified,
                                       ha='left')
                        self.axes.text(pp[1][0][0],
                                       pp[1][0][1],
                                       "Original ( " + str(v[3]) + " )",
                                       fontdict=original,
                                       ha='left')

        self.figure.canvas.mpl_connect('motion_notify_event',
                                       self.StatusBarUpdate)

        self.canvas.draw()
        CanvasPanel.draw_map = True

        self.axes.axis(
            'scaled'
        )  # si cet instruction n'est pas activé , il n'y aura pas d'affichage

        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.toolbar = CustomNavToolbar(self.canvas)
        self.toolbar.DeleteToolByPos(6)

        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

    def StatusBarUpdate(self, e):
        if e.inaxes:
            if self.permission:
                a, b = e.xdata, e.ydata
                self.GetTopLevelParent().StatusBarUpdater("x = " + str(a) +
                                                          ",  y = " + str(b))

        else:
            self.GetTopLevelParent().StatusBarUpdater("")
Пример #2
0
class CanvasPanel(wx.Panel):
    """ plot frame based on the Generic Frame class"""
    def __init__(self, parent, figure, *args, **kargs):
        wx.Panel.__init__(self, parent)
        # initialize the external data source

        figure.set_dpi(150)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)

        self.figurecavas = FigureCanvas(self, -1, figure)
        sizer.Add(self.figurecavas, 0,
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)

        self.figurecavas.mpl_connect('pick_event', self.OnPick)
        self.figurecavas.mpl_connect('button_press_event', self.OnButtonPress)
        self.figurecavas.mpl_connect('motion_notify_event',
                                     self.UpdateStatusBar)
        self.figurecavas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor)
        self.figurecavas.mpl_connect('key_press_event', self.OnKeyPressed)

        # add interactive curve pick function

        # setup the tool bar
        self.toolbar = MyNavigationToolbar(self.figurecavas, True)
        self.toolbar.Realize()

        sizer.Add(self.toolbar, 0,
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)

        self.text_x = wx.TextCtrl(self, wx.NewId(), "Value X:", size=(100, -1))
        self.text_y = wx.TextCtrl(self, wx.NewId(), "Value Y:", size=(100, -1))

        sizer.Add(
            self.text_x, 0,
            wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
        sizer.Add(
            self.text_y, 0,
            wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)

        self.sizerinuse = sizer
        # bind resize event
        wx.EVT_SIZE(self, self.OnSize)

        # show the frame

        self.Show()

    def OnPick(self, event):
        print 'picked'

    def OnButtonPress(self, event):
        ''' button press event'''
        pass

    def OnKeyPressed(self, event):
        #print 'keypressed'
        pass

    def ResizeCanvas(self):

        pass
        '''
        size = self.Parent.GetClientSize()
        
        self.figurecavas.resize(size[0],size[1])
        
        self.figurecavas.draw()
        
        print self.figurecavas.Size
        print self.Size
        print self.Parent.Size
        '''

    def OnSize(self, event):

        event.Skip()
        #wx.CallAfter(self.ResizeCanvas)

    def FigureUpdate(self, newfigure=None):

        if newfigure != None:
            newfigure.set_dpi(150)
            #self.figurecavas.figure.clear()
            self.figurecavas.figure = newfigure  #FigureCanvas(self, -1, newfigure)

        self.figurecavas.draw()

        self.figurecavas.Update()

        self.Update()
        self.Refresh()

    def ChangeCursor(self, event):
        """ change the cursor within the canvas"""
        self.figurecavas.SetCursor(wx.StockCursor(wx.CURSOR_BULLSEYE))

    def UpdateStatusBar(self, event):
        """ update the statue bar for point position"""
        if event.inaxes:
            x, y = event.xdata, event.ydata
            self.text_x.SetValue(str(x))
            self.text_y.SetValue(str(y))
            #self.statusBar.SetStatusText(( "x= " + str(x) +
            #                               "  y=" +str(y) ),
            #                               0)
    def set_limits(self, limits):
        """
        Set limits for the x and y axes,
        Operation based on current ax
        """
        ax1 = self.figurecavas.figure.axes[0]
        if limits != None:
            if limits[0] != None and limits[0] != 'None':
                ax1.set_xlim(xmin=float(limits[0]))
            if limits[1] != None and limits[1] != 'None':
                ax1.set_xlim(xmax=float(limits[1]))
            if limits[2] != None and limits[2] != 'None':
                ax1.set_ylim(ymin=float(limits[2]))
            if limits[3] != None and limits[3] != 'None':
                ax1.set_ylim(ymax=float(limits[3]))
        return ax1

    def set_labels(self, label):
        """
        Set labels for the x and y axes
        """
        ax = self.figurecavas.figure.axes[0]
        ax.set_xlabel(label[0])
        ax.set_ylabel(label[1])
Пример #3
0
class ClientGUI(wx.Frame):
    def __init__(self):
        self.create_GUI()

    def create_GUI(self):
        #This function creates buttons with defined position and connects(binds) them with events that
        #This function creates buttons with defined position and connects(binds) them with events that

        #####Global start variable####
        self.local_time = time()
        self.AirT_cjc = -2.
        self.OasisT_cjc = -2.
        self.smooth_factor = 1
        self.calib = [1, 0, 1, 0, 0]

        self.time_list = [
            10 * 50, 30 * 50, 60 * 50, 60 * 2 * 50, 60 * 5 * 50, 60 * 10 * 50,
            60 * 30 * 50, 3600 * 1 * 50, 3600 * 2 * 50, 3600 * 6 * 50,
            3600 * 12 * 50,
            len(buffer.buffer[0, :])
        ]

        self.time_range = 10 * 50

        self.txt_font_size = 10
        self.arg2 = 10

        self.environment = 0  #APS is 0, NIH is 1; localhost is 2
        self.DicObjects = {
        }  #this is a dictionary with all different objects in GUI

        ##Create Frame ans assign panel
        frame = wx.Frame.__init__(self,
                                  None,
                                  wx.ID_ANY,
                                  "Monitor (DI-245)",
                                  pos=(0, 0))

        self.panel = wx.Panel(self,
                              wx.ID_ANY,
                              style=wx.BORDER_THEME,
                              size=(400, 70),
                              pos=(0, 0))

        ###########################################################################
        ##MENU STARTS: for the GUI
        ###########################################################################
        file_item = {}
        about_item = {}
        self.calib_item = {}
        self.opt_item = {}
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        file_item[2] = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
        self.Bind(wx.EVT_MENU, self.OnQuit, file_item[2])

        calibMenu = wx.Menu()
        self.calib_item[0] = calibMenu.Append(wx.NewId(), "Calibrate", "")
        self.Bind(wx.EVT_MENU, self._on_server_comm, self.calib_item[0])

        optMenu = wx.Menu()
        self.opt_item[0] = optMenu.Append(wx.NewId(), '(0) Echo Server')
        self.opt_item[1] = optMenu.Append(wx.NewId(), '(1) Close Server')
        self.opt_item[2] = optMenu.Append(wx.NewId(), '(2) CA Broadcast')
        self.opt_item[6] = optMenu.Append(wx.NewId(),
                                          '(6) Perform calibration')
        self.opt_item[7] = optMenu.Append(wx.NewId(), '(7) Get calibration')
        self.Bind(wx.EVT_MENU, self._on_server_comm, self.opt_item[0])
        self.Bind(wx.EVT_MENU, self._on_server_comm, self.opt_item[1])

        aboutMenu = wx.Menu()
        about_item[0] = aboutMenu.Append(wx.ID_ANY, 'Client About')
        about_item[1] = aboutMenu.Append(wx.ID_ANY, 'Server About')
        self.Bind(wx.EVT_MENU, self._on_client_about, about_item[0])
        self.Bind(wx.EVT_MENU, self._on_server_about, about_item[1])

        menubar.Append(fileMenu, '&File')
        menubar.Append(calibMenu, '&Calibration')

        menubar.Append(optMenu, '&Options')
        menubar.Append(aboutMenu, '&About')

        self.SetMenuBar(menubar)

        self.Centre()
        self.Show(True)
        ###########################################################################
        ###MENU ENDS###
        ###########################################################################

        sizer = wx.GridBagSizer(5, 2)

        text4 = wx.StaticText(self.panel, label="Server IP")
        sizer.Add(text4, pos=(0, 0), flag=wx.TOP | wx.LEFT, border=5)

        self.ip_dropdown_list = [[
            '164.54.161.34', '128.231.5.78', '127.0.0.1'
        ], ['APS', 'NIH', 'localhost']]
        self.IP_choice = wx.Choice(self.panel,
                                   choices=self.ip_dropdown_list[1][:])
        self.IP_choice.SetSelection(self.environment)
        self.IP_choice.Bind(wx.EVT_CHOICE, self._on_change_ip_press)
        sizer.Add(self.IP_choice,
                  pos=(0, 1),
                  span=(1, 1),
                  flag=wx.TOP | wx.EXPAND,
                  border=5)

        self.flashingText = wx.StaticText(self.panel)
        self.flashingText.SetLabel('Ready')
        sizer.Add(self.flashingText,
                  pos=(0, 3),
                  flag=wx.TOP | wx.LEFT,
                  border=5)

        self.DicObjects[4] = wx.Button(self.panel, label="Start")
        sizer.Add(self.DicObjects[4],
                  pos=(0, 4),
                  flag=wx.TOP | wx.RIGHT,
                  border=5)
        self.DicObjects[4].Bind(wx.EVT_BUTTON, self.mthd_buttons)

        self.live_checkbox = wx.CheckBox(self.panel,
                                         id=wx.ID_ANY,
                                         label="Live",
                                         style=0,
                                         validator=wx.DefaultValidator,
                                         name='LiveCheckBoxNameStr')
        sizer.Add(self.live_checkbox,
                  pos=(1, 0),
                  flag=wx.TOP | wx.LEFT,
                  border=5)
        self.live_checkbox.SetValue(False)
        self.live_checkbox.Disable()

        self.DicObjects['server time'] = wx.StaticText(self.panel)
        self.DicObjects['server time'].SetLabel('')
        sizer.Add(self.DicObjects['server time'],
                  pos=(1, 1),
                  flag=wx.TOP | wx.LEFT,
                  border=5)
        self.DicObjects['server time'].SetLabel('Press Start Button')
        text5 = wx.StaticText(self.panel, label="time")
        sizer.Add(text5, pos=(1, 3), flag=wx.TOP | wx.LEFT, border=5)
        self.time_dropdown_list = [
            '10 s', '30 s', '1 min', '2 min', '5 min', '10 min', '30 min',
            '1 h', '2 h', '6 h', '12 h', 'max'
        ]  #, 'max']
        self.time_choice = wx.Choice(self.panel,
                                     choices=self.time_dropdown_list)
        sizer.Add(self.time_choice,
                  pos=(1, 4),
                  span=(4, 5),
                  flag=wx.LEFT | wx.TOP,
                  border=5)
        self.time_choice.Bind(wx.EVT_CHOICE, self._on_change_time_press)
        self.time_choice.SetSelection(1)
        self.live_checkbox.SetValue(False)
        sizer.AddGrowableCol(2)

        self.panel.SetSizer(sizer)

        self.dpi = 100
        self.figure = Figure((4, 6), dpi=self.dpi)
        self.axes0 = self.figure.add_subplot(411)
        self.axes1 = self.figure.add_subplot(412)
        self.axes2 = self.figure.add_subplot(413)
        self.axes3 = self.figure.add_subplot(414)
        self.canvas = FCW(self, -1, self.figure)
        gsizer = wx.BoxSizer(wx.VERTICAL)
        gsizer.Add(self.panel, 0)
        gsizer.Add(self.canvas, 1, wx.EXPAND)
        self.SetSizer(gsizer)
        self.Fit()

        self.redraw_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
        self.redraw_timer.Start(1000)
        self.draw(None)

    def _on_client_about(self, event):
        "Called from the Help/About"
        from os.path import basename
        from inspect import getfile
        filename = getfile(lambda x: None)
        info = basename(filename) + " version: " + __version__ + "\n" + __doc__
        dlg = wx.MessageDialog(self, info, "About",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.CenterOnParent()
        dlg.ShowModal()
        dlg.Destroy()

    def _on_server_about(self, event):
        wx.MessageBox('This is information about the server', 'Server Info',
                      wx.OK | wx.ICON_INFORMATION)

    def OnQuit(self, event):
        self.Close()

    def _on_change_ip_press(self, event):
        info("Dropdown IP menu: selected %s , New IP address : %r" %
             (self.ip_dropdown_list[1][self.IP_choice.GetSelection()],
              self.ip_dropdown_list[0][self.IP_choice.GetSelection()]))
        client.ip_address_server = self.ip_dropdown_list[0][
            self.IP_choice.GetSelection()]
        self.live_checkbox.SetValue(False)
        self.live_checkbox.Disable()

    def _on_change_time_press(self, event):
        self.time_list = [
            10 * 50, 30 * 50, 60 * 50, 60 * 2 * 50, 60 * 5 * 50, 60 * 10 * 50,
            60 * 30 * 50, 3600 * 1 * 50, 3600 * 2 * 50, 3600 * 6 * 50,
            3600 * 12 * 50,
            len(buffer.buffer[0, :])
        ]
        self.time_range = self.time_list[self.time_choice.GetSelection()]
        if self.time_range >= len(buffer.buffer[0, :]):
            self.time_range = self.time_list[len(self.time_list) - 1]
            self.time_choice.SetSelection(len(self.time_list) - 1)
        info('self time_range selected %r' % (self.time_range))

        if self.time_range == 10 * 50:
            self.smooth_factor = 1
            self.redraw_timer.Start(1000)
        elif self.time_range == 30 * 50:
            self.smooth_factor = 1
            self.redraw_timer.Start(1000)
        elif self.time_range == 1 * 60 * 50:
            self.smooth_factor = 20
            self.redraw_timer.Start(1000)
        elif self.time_range == 2 * 60 * 50:
            self.smooth_factor = 30
            self.redraw_timer.Start(1000)
        elif self.time_range == 5 * 60 * 50:
            self.smooth_factor = 50
            self.redraw_timer.Start(1000)
        elif self.time_range == 10 * 60 * 50:
            self.smooth_factor = 60
            self.redraw_timer.Start(1000)
        elif self.time_range == 0.5 * 3600 * 50:
            self.smooth_factor = 50
            self.redraw_timer.Start(1000)
        elif self.time_range == 3600 * 50:
            self.smooth_factor = 250
            self.redraw_timer.Start(3000)
        elif self.time_range == 2 * 3600 * 50:
            self.smooth_factor = 500
            self.redraw_timer.Start(4000)
        elif self.time_range == 6 * 3600 * 50:
            self.smooth_factor = 2000
            self.redraw_timer.Start(5000)
        elif self.time_range == 12 * 3600 * 50:
            self.smooth_factor = 6000
            self.redraw_timer.Start(5000)
        elif self.time_range > 12 * 3600 * 50:
            self.smooth_factor = 12000
            self.redraw_timer.Start(10000)
        else:
            self.smooth_factor = 1
        self.draw(None)

    def _on_command_list_select(self, event):

        info('commands from the list selected')
        # self._create_button(0,'Echo (0)',(step_h*0+step_h_zero,step_v*0+step_v_zero),'mthd_buttons')
        # self._create_button(1,'Close Server (1)',(step_h*0+step_h_zero,step_v*1+step_v_zero),'mthd_buttons')
        # self._create_button(2,'Broadcast burst (2)',(step_h*0+step_h_zero,step_v*2+step_v_zero),'mthd_buttons')
        # self._create_button(3,'Get mean(N) (3)',(step_h*0+step_h_zero,step_v*3+step_v_zero),'mthd_buttons')
        # self._create_button(4,'All buffer (4)',(step_h*0+step_h_zero,step_v*4+step_v_zero),'mthd_buttons')
        # self._create_button(5,'Update buffer (5)',(step_h*0+step_h_zero,step_v*5+step_v_zero),'mthd_buttons')
        # self._create_button(6,'Plot (6)',(step_h*0+step_h_zero,step_v*6+step_v_zero),'_on_button_plot')
        # self._create_button(7,'Save to file (7)',(step_h*0+step_h_zero,step_v*7+step_v_zero),'_on_save_file_press')

    def _set_response(self, response_arg):
        self.local_time = response_arg[1]
        self.DicObjects['server time'].SetLabel(
            strftime("%Y-%m-%d %H:%M:%S", localtime(self.local_time)))

    def method_result(self, method='window'):
        if method == 'window':
            self.DicObjects['result'].SetLabel(str(self.result))

    def help_button(self, event):
        info('Help button was pressed')

    def _on_button_plot(self, event):
        info('plot button pressed')
        self.draw(event)

    def _on_server_comm(self, event):
        # self.calib_item[0]= calibMenu.Append(wx.NewId(),  "Calibrate" ,"")
        # self.opt_item[0]= optMenu.Append(wx.NewId(),  'Echo Server')
        # self.opt_item[1]= optMenu.Append(wx.NewId(),  'Close Server')

        try:
            if event.GetId() == self.calib_item[0].GetId():
                command = 6
            elif event.GetId() == self.opt_item[0].GetId():
                command = 0
            elif event.GetId() == self.opt_item[1].GetId():
                command = 1
            flag = True
        except:
            flag = False
        if event == 7:
            command = 7
            flag = True
        info('sending command = %r' % (command))
        if flag:
            client._connect()
            client._send(str(command))
            sleep(0.005)
            client._receive()
            client.server.close()
            info('Command processed: %r' % client.response_arg[0])
            info('server time: %r' % client.response_arg[1])
            info('arg1: %r' % client.response_arg[2])
            info('arg2: %r' % client.response_arg[3])
            if command == 6:
                self.calib = client.response_arg[2]
            if command == 7:
                self.calib = client.response_arg[2]
            self._set_response(client.response_arg)

    def _on_save_file_press(self, event):
        #msgpack_packb([time(),], default=m.encode)
        np.savetxt('DI_245_circular_buffer' + str(time()) + '.csv',
                   np.transpose(buffer.buffer),
                   delimiter=',',
                   fmt='%1.4e')

    def mthd_buttons(self, event):
        """
        This method is an event handler. It cross refences the event Id and an Id stored in a dictionary to determine what to do. 
        """
        if event == 'change_ip':
            pass
        else:
            self.flashingText.SetLabel('Pulling')
            info('Event ID %r' % event.GetId())
            raw_commands = '0'
            for i in self.DicObjects.keys():
                if event.GetId() == self.DicObjects[i].GetId():
                    raw_commands = str(i)
                if i == 3:
                    raw_commands = raw_commands + ',' + str(self.arg2)

            print('raw_commands %r' % raw_commands)

            client._connect()
            client._send(raw_commands)

            sleep(0.005)
            client._receive()
            client.server.close()

            if client.response_arg[0] == 0:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self._set_response(client.response_arg)

            elif client.response_arg[0] == 1:
                print("Server has been shut down")
                self._set_response(client.response_arg)

            elif client.response_arg[0] == 2:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self._set_response(client.response_arg)

            elif client.response_arg[0] == 3:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self._set_response(client.response_arg)
                self._update_readings(client.response_arg)
            elif client.response_arg[0] == 4:
                print('test')
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                buffer.get_all(int(client.response_arg[2]),
                               client.response_arg[3])
                self._set_response(client.response_arg)
                self._on_server_comm(7)
                self.live_checkbox.SetValue(True)
                self.live_checkbox.Enable()

            elif client.response_arg[0] == 5:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                print('client.response_arg[2]', client.response_arg[2])
                buffer.get_update(int(client.response_arg[2]),
                                  client.response_arg[3])
                self._set_response(client.response_arg)

            elif client.response_arg[0] == 6:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self.calib = client.response_arg[2]
                self._set_response(client.response_arg)

            elif client.response_arg[0] == 7:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self.calib = client.response_arg[2]
                self._set_response(client.response_arg)

            else:
                print('Command processed:', client.response_arg[0])
                print('server time:', client.response_arg[1])
                print('arg1:', client.response_arg[2])
                print('arg2:', client.response_arg[3])
                self._set_response(client.response_arg)

        self.flashingText.SetLabel('Ready')

#################################################################################
########### Plotting
#################################################################################

    def on_redraw_timer(self, event):
        if self.live_checkbox.IsChecked(
        ):  #plot only if the live checkbox is checked
            self.flashingText.SetLabel('Pulling')
            client._connect()
            client._send('5')
            sleep(0.005)
            client._receive()
            client._server_close()
            buffer.get_update(client.response_arg[2], client.response_arg[3])
            self._set_response(client.response_arg)
            self.draw(event)
            self.flashingText.SetLabel('Ready')

    def smooth(self,
               y,
               step=1
               ):  #this is a smoothing function that helps speed up plotting
        if step == 1:
            y_out = y
        else:
            y_out = np.zeros(len(y) / step)
            for i in range(len(y_out)):
                if i == 0:
                    y_out[i] = np.mean(y[0:int((1) * step)])
                elif i == len(y_out) - 1:
                    y_out[i] = np.mean(y[int((i) * step):])
                else:
                    y_out[i] = np.mean(y[int((i) * step):int((i + 1) * step)])
        return y_out

    def draw(self, event):

        x = self.smooth(np.arange(-self.time_range * 0.02, 0, 0.02),
                        self.smooth_factor)

        self.axes0.cla()
        self.axes1.cla()
        self.axes2.cla()
        self.axes3.cla()

        plot_from = buffer.pointerC - self.time_range
        plot_to = buffer.pointerC

        if buffer.pointerC > self.time_range:
            y1 = self.smooth((
                (buffer.buffer[0, plot_from:plot_to] - 8192.) * 0.25 / 8192.) /
                             self.calib[0], self.smooth_factor)
            y2 = self.smooth((
                (buffer.buffer[2, plot_from:plot_to] - 8192.) * 0.25 / 8192.) /
                             self.calib[2], self.smooth_factor)
            y3 = self.smooth(
                (buffer.buffer[1, plot_from:plot_to] - 8192.) * 0.036621 +
                100. - self.calib[1], self.smooth_factor)
            y4 = self.smooth(
                (buffer.buffer[3, plot_from:plot_to] - 8192.) * 0.036621 +
                100. - self.calib[3], self.smooth_factor)

        else:
            y = np.concatenate(
                (buffer.buffer[0, plot_from:], buffer.buffer[0, 0:plot_to]))
            y1 = self.smooth(((y - 8192.) * 0.25 / 8192.) / self.calib[0],
                             self.smooth_factor)
            y = np.concatenate(
                (buffer.buffer[2, plot_from:], buffer.buffer[2, 0:plot_to]))
            y2 = self.smooth(((y - 8192.) * 0.25 / 8192.) / self.calib[2],
                             self.smooth_factor)
            y = np.concatenate(
                (buffer.buffer[1, plot_from:], buffer.buffer[1, 0:plot_to]))
            y3 = self.smooth((y - 8192.) * 0.036621 + 100. - self.calib[1],
                             self.smooth_factor)
            y = np.concatenate(
                (buffer.buffer[3, plot_from:], buffer.buffer[3, 0:plot_to]))
            y4 = self.smooth((y - 8192.) * 0.036621 + 100. - self.calib[3],
                             self.smooth_factor)

        self.axes0.plot(x, y1, '-b', label='Upstream')
        self.axes1.plot(x, y2, '-g', label='Downstream')
        self.axes2.plot(x, y3, '-r')
        self.axes3.plot(x, y4, '-r')

        self.axes0.set_title('Pressure upstream')
        self.axes1.set_title('Pressure downstream')
        self.axes2.set_title('Air Temperature')
        self.axes3.set_title('Oasis Temperature')
        self.axes3.set_xlabel("time, seconds")

        self.axes0.set_xticklabels([])
        self.axes1.set_xticklabels([])
        self.axes2.set_xticklabels([])

        self.axes0.set_xlim([np.min(x), np.max(x)])
        self.axes1.set_xlim([np.min(x), np.max(x)])
        self.axes2.set_xlim([np.min(x), np.max(x)])
        self.axes3.set_xlim([np.min(x), np.max(x)])

        self.axes0.set_ylim([
            np.min(y1) - np.abs(np.min(y1)) * 0.02,
            np.max(y1) + np.abs(np.max(y1)) * 0.02
        ])
        self.axes1.set_ylim([
            np.min(y2) - np.abs(np.min(y2)) * 0.02,
            np.max(y2) + np.abs(np.max(y2)) * 0.02
        ])
        self.axes2.set_ylim([
            np.min(y3) - np.abs(np.min(y3)) * 0.02,
            np.max(y3) + np.abs(np.max(y3)) * 0.02
        ])
        self.axes3.set_ylim([
            np.min(y4) - np.abs(np.min(y4)) * 0.02,
            np.max(y4) + np.abs(np.max(y4)) * 0.02
        ])

        self.axes0.grid()
        self.axes1.grid()
        self.axes2.grid()
        self.axes3.grid()

        divider = 5  #this is a tick divider, meaning how many ticks we have in plots. 5 tick = 6 div is a good choice
        step = (np.max(x) - np.min(x)) / divider
        range_lst = []
        for i in range(divider + 1):
            range_lst.append(np.min(x) + step * i)
        label_lst = []

        if self.time_choice.GetSelection(
        ) == 0 or self.time_choice.GetSelection(
        ) == 1 or self.time_choice.GetSelection(
        ) == 2 or self.time_choice.GetSelection() == 3:
            time_format = '%M:%S'
        elif self.time_choice.GetSelection(
        ) == 4 or self.time_choice.GetSelection(
        ) == 5 or self.time_choice.GetSelection() == 6:
            time_format = '%H:%M'
        else:
            time_format = '%H:%M:%S'
        for i in range(len(range_lst) - 1):
            label_lst.append(
                strftime(time_format,
                         localtime(self.local_time + range_lst[i])))
        i = i + 1
        label_lst.append(
            strftime('%H:%M:%S', localtime(self.local_time + range_lst[i])))

        self.axes3.set_xticklabels(label_lst)
        self.axes0.set_xticks(range_lst)
        self.axes1.set_xticks(range_lst)
        self.axes2.set_xticks(range_lst)
        self.axes3.set_xticks(range_lst)
        self.axes3.set_xlabel("local time")

        self.canvas.Refresh()
        self.canvas.Update()
        self.canvas.draw()