Plotting from MacroServer

The main challenge in the example below is to find a good value for the DISPLAY environment variable.

#!/bin/env python

from sardana.macroserver.macro import *
from sardana.macroserver.macro import macro, Type
import os
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
#import pyqtgraph.functions as fn

win = None
app = None

class pg_minimal( Macro):
    """
    this macro simulates a scan. 
    """
    param_def = [["command", Type.String, None, "plot, close"],]
    result_def = []

    def plot( self): 
        global win
        global app
        xMin = 0
        xMax = 50
        xDelta = 0.5
        x = np.arange( xMin, xMax, xDelta)
        t = np.tan(2*np.pi*x)

        app = QtGui.QApplication([])
        mw = QtGui.QMainWindow()
        win = pg.GraphicsWindow( title="Scan the Tango Function")
        win.clear()

        win.addLabel( "A figure containing tan()", row = 1, col = 1)
        tan = win.addPlot( row=2, col=1)
        tan.showGrid( x = True, y = True)
        tan.setTitle( title = "The tan() Function")
        tan.setLabel( 'left', 'tan')
        tan.setLabel( 'bottom', 'phase')
        tan.enableAutoRange( x = False, y = True)
        tan.setXRange( xMin - 0.25, xMax + 0.25)

        for i in range( len(x)):
            tan.clear()
            tan.plot( x[0:i], t[0:i], pen=( 0, 0, 255))
            app.processEvents()

        #app.closeAllWindows()
        #app.exit()
        #app = None
        #win = None

    def run( self, command):
        os.environ[ 'DISPLAY'] = ':1'
        if command == "plot":
            self.plot()
        elif command == "close":
            app.closeAllWindows()
            app.exit()