Ejemplo n.º 1
0
class TestSite(object):
    def setup(self):

        self.manager = Manager(port=8000)

        #self.manager.addClass(Site, "lna", {"name": "LNA",
        #                                    "latitude": "-22 32 03",
        #                                    "longitude": "-45 34 57",
        #                                    "altitude": "1896"}

        self.manager.addClass(
            Site, "lna", {
                "name": "UFSC",
                "latitude": "-27 36 13 ",
                "longitude": "-48 31 20",
                "altitude": "20"
            })

    def teardown(self):
        self.manager.shutdown()

    def test_times(self):

        site = self.manager.getProxy(Site)

        try:
            print
            print "local:", site.localtime()
            print "UT   :", site.ut()
            print "JD   :", site.JD()
            print "MJD  :", site.MJD()
            print "LST  :", site.LST()
            print "GST  :", site.GST()
        except Exception, e:
            printException(e)
Ejemplo n.º 2
0
class TestFilterWheel(object):
    def setup(self):

        self.manager = Manager(port=8000)

        self.manager.addClass(FakeFilterWheel, "fake",
                              {"device": "/dev/ttyS0"})
        self.manager.addClass(FilterWheel, "filter", {
            "driver": "/FakeFilterWheel/0",
            "filters": "U B V R I"
        })

        #self.manager.addClass(SBIG, "sbig", {"device": Device.USB})
        #self.manager.addClass(FilterWheel, "filter", {"driver": "/SBIG/0",
        #                                              "filters": "R G B LUNAR CLEAR"})

    def teardown(self):
        self.manager.shutdown()

    def test_filters(self):

        f = self.manager.getProxy(FilterWheel)

        filters = f.getFilters()

        for filter in filters:
            f.setFilter(filter)
            assert f.getFilter() == filter

    def test_get_filters(self):

        f = self.manager.getProxy(FilterWheel)
        filters = f.getFilters()

        assert isinstance(filters, tuple) or isinstance(filters, list)
Ejemplo n.º 3
0
class TestAutofocus(object):
    def setup(self):

        self.manager = Manager(port=8000)

        # real
        self.manager.addClass(SBIG, "sbig", {"device": "USB"})
        self.manager.addClass(Camera, "cam", {"driver": "/SBIG/0"})

        self.manager.addClass(
            Site, "lna", {
                "name": "UFSC",
                "latitude": "-27 36 13 ",
                "longitude": "-48 31 20",
                "altitude": "20",
                "utc_offset": "-3"
            })

        self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        self.manager.addClass(Telescope, "meade", {"driver": "/Meade/meade"})

        self.manager.addClass(PointVerify, "Point")

    def teardown(self):
        self.manager.shutdown()
        del self.manager

    def test_point(self):

        point = self.manager.getProxy(PointVerify)
Ejemplo n.º 4
0
class TestPointVerify (object):

    def setup (self):

        self.manager = Manager(port=8000)

        # real
        self.manager.addClass(SBIG, "sbig", {"device": "USB"})
        self.manager.addClass(Camera, "cam", {"driver": "/SBIG/0"})

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        self.manager.addClass(Telescope, "meade", {"driver": "/Meade/meade"})

        self.manager.addClass(PointVerify, "Point")



    def teardown (self):
        self.manager.shutdown()
        del self.manager

    def test_point (self):

        point = self.manager.getProxy(PointVerify)
Ejemplo n.º 5
0
class TestSite (object):

    def setup (self):

        self.manager = Manager(port=8000)

        #self.manager.addClass(Site, "lna", {"name": "LNA",
        #                                    "latitude": "-22 32 03",
        #                                    "longitude": "-45 34 57",
        #                                    "altitude": "1896"}

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

    def teardown (self):
        self.manager.shutdown()

    def test_times (self):

        site = self.manager.getProxy(Site)

        try:
            print
            print "local:", site.localtime()
            print "UT   :", site.ut()
            print "JD   :", site.JD()
            print "MJD  :", site.MJD()
            print "LST  :", site.LST()
            print "GST  :", site.GST()
        except Exception, e:
            printException(e)
Ejemplo n.º 6
0
class TestRealDome(RealHardwareTest, DomeTest):
    
    def setup (self):

        self.manager = Manager()

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.domelna40cm import DomeLNA40cm
        from chimera.instruments.meade       import Meade
        self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        self.manager.addClass(DomeLNA40cm, "lna40", {"device": "/dev/ttyS9",
                                                     "telescope": "/Meade/0",
                                                     "mode": "Stand"})

        self.TELESCOPE = "/Meade/meade"
        self.DOME = "/DomeLNA40cm/0"
       
        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()

    def test_stress_dome_track (self):
        # just for manual and visual testing
        raise SkipTest()
Ejemplo n.º 7
0
class TestFakeCamera(FakeHardwareTest, CameraTest):
    def setup(self):
        self.manager = Manager(port=8000)
        from chimera.instruments.fakecamera import FakeCamera
        self.manager.addClass(FakeCamera, "fake")
        self.CAMERA = "/FakeCamera/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 8
0
class TestFakeCamera(FakeHardwareTest, CameraTest):

    def setup (self):
        self.manager = Manager(port=8000)
        from chimera.instruments.fakecamera import FakeCamera
        self.manager.addClass(FakeCamera, "fake")
        self.CAMERA = "/FakeCamera/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 9
0
class TestFocuser(object):
    def setup(self):

        self.manager = Manager(port=8000)

        self.manager.addClass(
            Site, "lna", {
                "name": "LNA",
                "latitude": "-22 32 03",
                "longitude": "-45 34 57",
                "altitude": "1896",
                "utc_offset": "-3"
            })

        self.manager.addClass(FakeFocuser, "fake", {"device": "/dev/ttyS0"})
        self.manager.addClass(Focuser, "focus", {"driver": "/FakeFocuser/0"})

        #self.manager.addClass(OptecTCFS, "optec", {"device": "/dev/ttyS0"})
        #self.manager.addClass(Focuser, "focus", {"driver": "/OptecTCFS/0"})

    def teardown(self):
        self.manager.shutdown()

    def test_get_position(self):

        focus = self.manager.getProxy(Focuser)

        assert focus.getPosition() >= 0

    def test_move(self):

        focus = self.manager.getProxy(Focuser)

        start = focus.getPosition()
        delta = int(random.Random().random() * 1000)

        # assumes IN moving to lower values
        focus.moveIn(delta)
        assert focus.getPosition() == start - delta

        # assumes OUT moving to larger values
        start = focus.getPosition()
        focus.moveOut(delta)
        assert focus.getPosition() == start + delta

        # TO
        focus.moveTo(1000)
        assert focus.getPosition() == 1000

        # TO where?
        assert_raises(InvalidFocusPositionException, focus.moveTo, 1e9)
Ejemplo n.º 10
0
class TestRealCamera(RealHardwareTest, CameraTest):
    def setup(self):

        self.manager = Manager(port=8000)

        from chimera.instruments.sbig import SBIG
        self.manager.addClass(SBIG, "sbig")
        self.CAMERA = "/SBIG/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 11
0
class TestRealFilterWheel(RealHardwareTest, FilterWheelTest):
    def setup(self):

        self.manager = Manager()

        from chimera.instruments.sbig import SBIG
        self.manager.addClass(SBIG, "sbig", {"filters": "R G B LUNAR CLEAR"})
        self.FILTER_WHEEL = "/SBIG/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 12
0
    def test_locate(self):

        manager = Manager(host='localhost', port=9999)

        proxy = ManagerLocator.locate()
        assert proxy.ping() == True

        assert proxy.URI.address == gethostbyname("localhost")
        assert proxy.URI.port == 9999

        manager.shutdown()

        # where are you
        assert_raises(ManagerNotFoundException, ManagerLocator.locate)
Ejemplo n.º 13
0
class TestRealFilterWheel(RealHardwareTest, FilterWheelTest):
    def setup(self):

        self.manager = Manager()

        from chimera.instruments.sbig import SBIG

        self.manager.addClass(SBIG, "sbig", {"filters": "R G B LUNAR CLEAR"})
        self.FILTER_WHEEL = "/SBIG/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 14
0
class TestFakeFilterWheel(FakeHardwareTest, FilterWheelTest):
    def setup(self):

        self.manager = Manager(port=8000)

        from chimera.instruments.fakefilterwheel import FakeFilterWheel

        self.manager.addClass(FakeFilterWheel, "fake", {"device": "/dev/ttyS0", "filters": "U B V R I"})
        self.FILTER_WHEEL = "/FakeFilterWheel/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 15
0
class TestRealFocuser(RealHardwareTest, FocuserTest):
    
    def setup (self):
        self.manager = Manager(port=8000)
        self.manager.addClass(Site, "lna", {"name": "LNA",
                                            "latitude": "-22 32 03",
                                            "longitude": "-45 34 57",
                                            "altitude": "1896"})

        from chimera.instruments.optectcfs import OptecTCFS
        self.manager.addClass(OptecTCFS, "optec", {"device": "/dev/ttyS4"})
        self.FOCUSER = "******"

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 16
0
class TestRealCamera(RealHardwareTest, CameraTest):
    
    def setup (self):

        self.manager = Manager(port=8000)

        from chimera.instruments.sbig import SBIG
        self.manager.addClass(SBIG, "sbig")
        self.CAMERA = "/SBIG/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 17
0
class TestFakeFocuser(FakeHardwareTest, FocuserTest):

    def setup(self):

        self.manager = Manager(port=8000)
        self.manager.addClass(Site, "lna", {"name": "LNA",
                                            "latitude": "-22 32 03",
                                            "longitude": "-45 34 57",
                                            "altitude": "1896"})

        from chimera.instruments.fakefocuser import FakeFocuser
        self.manager.addClass(FakeFocuser, "fake", {"device": "/dev/ttyS0"})
        self.FOCUSER = "******"

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 18
0
class TestFakeFilterWheel(FakeHardwareTest, FilterWheelTest):
    def setup(self):

        self.manager = Manager(port=8000)

        from chimera.instruments.fakefilterwheel import FakeFilterWheel
        self.manager.addClass(FakeFilterWheel, "fake", {
            "device": "/dev/ttyS0",
            "filters": "U B V R I"
        })
        self.FILTER_WHEEL = "/FakeFilterWheel/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 19
0
class TestRealFocuser(RealHardwareTest, FocuserTest):
    def setup(self):
        self.manager = Manager(port=8000)
        self.manager.addClass(
            Site, "lna", {
                "name": "LNA",
                "latitude": "-22 32 03",
                "longitude": "-45 34 57",
                "altitude": "1896"
            })

        from chimera.instruments.optectcfs import OptecTCFS
        self.manager.addClass(OptecTCFS, "optec", {"device": "/dev/ttyS4"})
        self.FOCUSER = "******"

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 20
0
class TestFakeFocuser(FakeHardwareTest, FocuserTest):
    def setup(self):

        self.manager = Manager(port=8000)
        self.manager.addClass(
            Site, "lna", {
                "name": "LNA",
                "latitude": "-22 32 03",
                "longitude": "-45 34 57",
                "altitude": "1896"
            })

        from chimera.instruments.fakefocuser import FakeFocuser
        self.manager.addClass(FakeFocuser, "fake", {"device": "/dev/ttyS0"})
        self.FOCUSER = "******"

    def teardown(self):
        self.manager.shutdown()
Ejemplo n.º 21
0
class TestFakeTelescope(FakeHardwareTest, TelescopeTest):

    def setup(self):

        self.manager = Manager(port=8000)

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.faketelescope import FakeTelescope
        self.manager.addClass(FakeTelescope, "fake")
        self.TELESCOPE = "/FakeTelescope/0"

        self.tel = self.manager.getProxy(self.TELESCOPE)

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 22
0
class TestRealTelescope(RealHardwareTest, TelescopeTest):
    
    def setup (self):

        self.manager = Manager(port=8000)

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.meade import Meade
        self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        self.TELESCOPE = "/Meade/0"
        #self.TELESCOPE = "150.162.110.3:7666/TheSkyTelescope/0"
        self.tel = self.manager.getProxy(self.TELESCOPE)

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 23
0
class TestRealTelescope(RealHardwareTest, TelescopeTest):
    
    def setup (self):

        self.manager = Manager(port=8000)

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.meade import Meade
        self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        self.TELESCOPE = "/Meade/0"
        #self.TELESCOPE = "150.162.110.3:7666/TheSkyTelescope/0"
        self.tel = self.manager.getProxy(self.TELESCOPE)

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 24
0
class TestFakeTelescope(FakeHardwareTest, TelescopeTest):

    def setup(self):

        self.manager = Manager(port=8000)

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.faketelescope import FakeTelescope
        self.manager.addClass(FakeTelescope, "fake")
        self.TELESCOPE = "/FakeTelescope/0"

        self.tel = self.manager.getProxy(self.TELESCOPE)

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 25
0
class TestFakeDome(FakeHardwareTest, DomeTest):

    def setup (self):

        self.manager = Manager()

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20"})

        from chimera.instruments.faketelescope import FakeTelescope
        from chimera.instruments.fakedome import FakeDome
        self.manager.addClass(FakeTelescope, "fake")
        self.manager.addClass(FakeDome, "dome", {"telescope": "/FakeTelescope/0",
                                                 "mode": "Track"})
        self.TELESCOPE = "/FakeTelescope/0"
        self.DOME = "/FakeDome/0"

        FiredEvents = {}
        self.setupEvents()

    def teardown (self):
        self.manager.shutdown()
Ejemplo n.º 26
0
    def test_log(self):
        class Simple(ChimeraObject):
            def __init__(self):
                ChimeraObject.__init__(self)

            def answer(self):
                try:
                    raise ChimeraException("I'm an Exception, sorry.")
                except ChimeraException:
                    self.log.exception("from except: wow, exception caught.")
                    raise ChimeraException("I'm a new Exception, sorry again")

        manager = Manager()
        manager.addClass(Simple, "simple")

        simple = manager.getProxy(Simple)

        try:
            simple.answer()
        except ChimeraException as e:
            assert e.cause != None
            log.exception("wow, something wrong")

        manager.shutdown()
Ejemplo n.º 27
0
class TestAutoMap(object):
    def setup(self):

        self.manager = Manager(port=8000)

        self.manager.addClass(
            Site, "lna", {
                "name": "LNA",
                "latitude": "-22 32 03",
                "longitude": "-45 34 57",
                "altitude": "1896",
                "utc_offset": "-3"
            })

        # fake
        self.manager.addClass(FakeTelescope, "fake", {"skip_init": False})
        self.manager.addClass(Telescope, "fake",
                              {"driver": "/FakeTelescope/0"})

        self.manager.addClass(FakeCamera, "fake")
        self.manager.addClass(Camera, "cam", {"driver": "/FakeCamera/0"})

        self.manager.addClass(FakeDome, "fake")
        self.manager.addClass(Dome, "dome", {
            "driver": "/FakeDome/0",
            "mode": "Track",
            "telescope": "/Telescope/0"
        })

        # real
        #self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6", "skip_init": False})
        #self.manager.addClass(Telescope, "meade", {"driver": "/Meade/meade"})

        #self.manager.addClass(SBIG, "sbig", {"device": "USB"})
        #self.manager.addClass(Camera, "cam", {"driver": "/SBIG/0"})

        #self.manager.addClass(DomeLNA40cm, "lna40", {"device": "/dev/ttyS0"})
        #self.manager.addClass(Dome, "dome", {"driver": "/DomeLNA40cm/0",
        #                                     "mode": "Track",
        #                                     "telescope": "/Telescope/0"})

        @callback(self.manager)
        def exposeBeginClbk(exp_time):
            print time.time(), "[cam] Expose begin for %.3f s." % exp_time

        @callback(self.manager)
        def exposeCompleteClbk():
            print time.time(), "[cam] Expose complete."

        @callback(self.manager)
        def readoutBeginClbk(frame):
            print time.time(), "[cam] Readout begin for %s." % frame

        @callback(self.manager)
        def readoutCompleteClbk(frame):
            print time.time(), "[cam] Readout complete for %s." % frame

        @callback(self.manager)
        def camAbortCompleteClbk():
            print time.time(), "[cam] Abort complete."

        cam = self.manager.getProxy(Camera)
        cam.exposeBegin += exposeBeginClbk
        cam.exposeComplete += exposeCompleteClbk
        cam.readoutBegin += readoutBeginClbk
        cam.readoutComplete += readoutCompleteClbk
        cam.abortComplete += camAbortCompleteClbk

        @callback(self.manager)
        def slewBeginClbk(target):
            print time.time(), "[tel] Slew begin. target=%s" % str(target)

        @callback(self.manager)
        def slewCompleteClbk(position):
            print time.time(
            ), "[tel] Slew complete. position=%s" % str(position)

        @callback(self.manager)
        def telAbortCompleteClbk(position):
            print time.time(
            ), "[tel] Abort complete. position=%s" % str(position)

        self.tel = self.manager.getProxy(Telescope)
        self.tel.slewBegin += slewBeginClbk
        self.tel.slewComplete += slewCompleteClbk
        self.tel.abortComplete += telAbortCompleteClbk

        @callback(self.manager)
        def domeSlewBeginClbk(target):
            print
            print time.time(), "[dome] Slew begin. target=%s" % str(target)

        @callback(self.manager)
        def domeSlewCompleteClbk(position):
            print time.time(
            ), "[dome] Slew complete. position=%s" % str(position)

        @callback(self.manager)
        def domeAbortCompleteClbk(position):
            print time.time(
            ), "[dome] Abort slew at position=%s" % str(position)

        dome = self.manager.getProxy(Dome)
        dome.slewBegin += domeSlewBeginClbk
        dome.slewComplete += domeSlewCompleteClbk
        dome.abortComplete += domeAbortCompleteClbk

    def teardown(self):
        self.manager.shutdown()
        del self.manager

    def test_map(self):

        tel = self.manager.getProxy(Telescope)
        cam = self.manager.getProxy(Camera)
        dome = self.manager.getProxy(Dome)

        site = self.manager.getProxy(Site)
Ejemplo n.º 28
0
class TestManager(object):
    def setup(self):
        self.manager = Manager()

    def teardown(self):
        self.manager.shutdown()
        del self.manager

    def test_add_start(self):

        # add by class
        assert self.manager.addClass(Simple, "simple", start=True)

        # already started
        assert_raises(InvalidLocationException, self.manager.addClass, Simple,
                      "simple")

        assert_raises(NotValidChimeraObjectException, self.manager.addClass,
                      NotValid, "nonono")
        assert_raises(InvalidLocationException, self.manager.addClass, Simple,
                      "")

        # by location
        assert self.manager.addLocation('/ManagerHelper/h',
                                        path=[os.path.dirname(__file__)])
        assert_raises(ClassLoaderException, self.manager.addLocation,
                      '/What/h')
        assert_raises(InvalidLocationException, self.manager.addLocation,
                      'foo')

        # start with error
        #assert self.manager.addLocation('/ManagerHelperWithError/h', start=False)
        #assert_raises(ChimeraObjectException, self.manager.start, '/ManagerHelperWithError/h')

        # start who?
        assert_raises(InvalidLocationException, self.manager.start,
                      "/Who/am/I")

        # exceptional cases
        # __init__
        assert_raises(ChimeraObjectException, self.manager.addLocation,
                      "/ManagerHelperWithInitException/h",
                      [os.path.dirname(__file__)])

        # __start__
        assert_raises(ChimeraObjectException, self.manager.addLocation,
                      "/ManagerHelperWithStartException/h",
                      [os.path.dirname(__file__)])

        # __main__
        #assert_raises(ChimeraObjectException, self.manager.addLocation, "/ManagerHelperWithMainException/h")

    def test_remove_stop(self):

        assert self.manager.addClass(Simple, "simple")

        # who?
        assert_raises(InvalidLocationException, self.manager.remove,
                      'Simple/what')
        assert_raises(InvalidLocationException, self.manager.remove, 'foo')

        # stop who?
        assert_raises(InvalidLocationException, self.manager.stop, 'foo')

        # ok
        assert self.manager.remove('/Simple/simple') == True

        # __stop__ error
        assert self.manager.addLocation("/ManagerHelperWithStopException/h",
                                        path=[os.path.dirname(__file__)])
        assert_raises(ChimeraObjectException, self.manager.stop,
                      '/ManagerHelperWithStopException/h')

        # another path to stop
        assert_raises(ChimeraObjectException, self.manager.remove,
                      '/ManagerHelperWithStopException/h')

        # by index
        assert self.manager.addClass(Simple, "simple")
        assert self.manager.remove('/Simple/0') == True

    def test_proxy(self):

        assert self.manager.addClass(Simple, "simple")

        # who?
        assert_raises(InvalidLocationException, self.manager.getProxy, 'wrong')
        assert_raises(InvalidLocationException, self.manager.getProxy,
                      'Simple/simple')

        # ok
        assert self.manager.getProxy('/Simple/simple')
        assert self.manager.getProxy('/Simple/0')

        # calling
        p = self.manager.getProxy('/Simple/0')
        assert isinstance(p, Proxy)

        assert p.answer() == 42

        # oops
        assert_raises(AttributeError, p.wrong)

    def test_manager(self):

        assert self.manager.addClass(Simple, "simple")

        p = self.manager.getProxy(Simple)
        assert p

        m = p.getManager()
        assert m.GUID() == self.manager.GUID()
Ejemplo n.º 29
0
class TestEvents(object):
    def setup(self):
        self.manager = Manager()

    def teardown(self):
        self.manager.shutdown()
        del self.manager

    def test_publish(self):

        assert self.manager.addClass(Publisher, "p") != False
        assert self.manager.addClass(Subscriber, "s") != False

        p = self.manager.getProxy("/Publisher/p")
        assert isinstance(p, Proxy)

        s = self.manager.getProxy("/Subscriber/s")
        assert isinstance(s, Proxy)

        p.fooDone += s.fooDoneClbk

        assert p.foo() == 42
        time.sleep(0.5)  # delay to get messages delivered
        assert s.getCounter() == 1
        assert p.getCounter() == 1

        assert p.foo() == 42
        time.sleep(0.5)  # delay to get messages delivered
        assert s.getCounter() == 2
        assert p.getCounter() == 2

        # unsubscribe
        p.fooDone -= s.fooDoneClbk
        p.fooDone -= p.fooDoneClbk

        assert p.foo() == 42
        time.sleep(0.5)  # delay to get messages delivered
        assert s.getCounter() == 2
        assert p.getCounter() == 2

    def test_performance(self):

        assert self.manager.addClass(Publisher, "p") != False
        assert self.manager.addClass(Subscriber, "s") != False

        p = self.manager.getProxy("/Publisher/p")
        assert isinstance(p, Proxy)

        s = self.manager.getProxy("/Subscriber/s")
        assert isinstance(s, Proxy)

        p.fooDone += s.fooDoneClbk

        for check in range(1):

            start = time.time()
            for i in range(100):
                p.foo()
            end = time.time()

            time.sleep(5)

            results = s.getResults()

            dt = [(t - t0) * 1000 for t0, t in results]
            mean = sum(dt) / len(dt)

            sigma = math.sqrt(sum([(t - mean)**2 for t in dt]) / len(dt))

            print("#" * 25)
            print("# %d events (%.3f s)" % (len(dt), (end - start)))
            print("# %.2f events/s" % (len(dt) / (end - start)))
            print("# min   : %-6.3f ms" % min(dt))
            print("# max   : %-6.3f ms" % max(dt))
            print("# mean  : %-6.3f ms" % mean)
            print("# sigma : %-6.3f ms" % sigma)
            print("#" * 25)
Ejemplo n.º 30
0
class TestCamera(object):
    def setup(self):

        self.manager = Manager(port=8000)

        #self.manager.addClass(SBIG, "sbig", {"device": Device.USB})
        #self.manager.addClass(Camera, "cam", {"driver": "/SBIG/sbig"})

        self.manager.addClass(FakeCamera, "fake", {"device": Device.USB})
        self.manager.addClass(Camera, "cam", {"driver": "/FakeCamera/fake"})

        @callback(self.manager)
        def exposeBeginClbk(request):
            print
            print time.time(), "Expose begin for request %s." % request

        @callback(self.manager)
        def exposeCompleteClbk(request):
            print time.time(), "Expose complete for request %s." % request

        @callback(self.manager)
        def readoutBeginClbk(request):
            print time.time(
            ), "Readout begin for request %s." % request["filename"]

        @callback(self.manager)
        def readoutCompleteClbk(request):
            print time.time(
            ), "Readout complete for request %s." % request["filename"]

        @callback(self.manager)
        def abortCompleteClbk():
            print time.time(), "Abort complete."

        cam = self.manager.getProxy(Camera)
        cam.exposeBegin += exposeBeginClbk
        cam.exposeComplete += exposeCompleteClbk
        cam.readoutBegin += readoutBeginClbk
        cam.readoutComplete += readoutCompleteClbk
        cam.abortComplete += abortCompleteClbk

    def teardown(self):
        self.manager.shutdown()

    def test_simple(self):

        cam = self.manager.getProxy(Camera)
        assert cam.isExposing() == False

    def test_expose(self):

        cam = self.manager.getProxy(Camera)

        frames = 0

        try:
            frames = cam.expose(exptime=2,
                                frames=2,
                                interval=0.5,
                                filename="autogen-expose.fits")
        except Exception, e:
            log.exception("problems")

        assert len(frames) == 2
        assert isinstance(frames[0], Proxy)
        assert isinstance(frames[1], Proxy)
Ejemplo n.º 31
0
class TestManager (object):

    def setup (self):
        self.manager = Manager()

    def teardown (self):
        self.manager.shutdown()
        del self.manager

    def test_add_start (self):

        # add by class
        assert self.manager.addClass(Simple, "simple", start=True)

        # already started
        assert_raises(InvalidLocationException, self.manager.addClass, Simple, "simple")
       
        assert_raises(NotValidChimeraObjectException, self.manager.addClass, NotValid, "nonono")
        assert_raises(InvalidLocationException, self.manager.addClass, Simple, "")

        # by location
        assert self.manager.addLocation('/ManagerHelper/h', path=[os.path.dirname(__file__)])
        assert_raises(ClassLoaderException, self.manager.addLocation, '/What/h')
        assert_raises(InvalidLocationException, self.manager.addLocation, 'foo')

        # start with error
        #assert self.manager.addLocation('/ManagerHelperWithError/h', start=False)
        #assert_raises(ChimeraObjectException, self.manager.start, '/ManagerHelperWithError/h')

        # start who?
        assert_raises(InvalidLocationException, self.manager.start, "/Who/am/I")

        # exceptional cases
        # __init__
        assert_raises(ChimeraObjectException, self.manager.addLocation,
                                             "/ManagerHelperWithInitException/h",
                                             [os.path.dirname(__file__)])

        # __start__
        assert_raises(ChimeraObjectException, self.manager.addLocation,
                                             "/ManagerHelperWithStartException/h",
                                             [os.path.dirname(__file__)])

        # __main__
        #assert_raises(ChimeraObjectException, self.manager.addLocation, "/ManagerHelperWithMainException/h")
        

    def test_remove_stop (self):

        assert self.manager.addClass(Simple, "simple")

        # who?
        assert_raises(InvalidLocationException, self.manager.remove, 'Simple/what')
        assert_raises(InvalidLocationException, self.manager.remove, 'foo')

        # stop who?
        assert_raises(InvalidLocationException, self.manager.stop, 'foo')

        # ok
        assert self.manager.remove('/Simple/simple') == True

        # __stop__ error
        assert self.manager.addLocation("/ManagerHelperWithStopException/h", path=[os.path.dirname(__file__)])
        assert_raises(ChimeraObjectException, self.manager.stop, '/ManagerHelperWithStopException/h')

        # another path to stop
        assert_raises(ChimeraObjectException, self.manager.remove, '/ManagerHelperWithStopException/h')

        # by index
        assert self.manager.addClass(Simple, "simple")
        assert self.manager.remove('/Simple/0') == True

    def test_proxy (self):

        assert self.manager.addClass(Simple, "simple")

        # who?
        assert_raises(InvalidLocationException, self.manager.getProxy, 'wrong')
        assert_raises(InvalidLocationException, self.manager.getProxy, 'Simple/simple')

        # ok
        assert self.manager.getProxy ('/Simple/simple')
        assert self.manager.getProxy ('/Simple/0')

        # calling
        p = self.manager.getProxy ('/Simple/0')
        assert isinstance(p, Proxy)

        assert p.answer() == 42

        # oops
        assert_raises (AttributeError, p.wrong)

    def test_manager (self):

        assert self.manager.addClass(Simple, "simple")
        
        p = self.manager.getProxy(Simple)
        assert p

        m = p.getManager()
        assert m.GUID() == self.manager.GUID()
Ejemplo n.º 32
0
class TestTelescope (object):

    def setup (self):

        self.manager = Manager(port=8000)

        #self.manager.addClass(Site, "lna", {"name": "LNA",
        #                                    "latitude": "-22 32 03",
        #                                    "longitude": "-45 34 57",
        #                                    "altitude": "1896",
        #                                    "utc_offset": "-3"})

        self.manager.addClass(Site, "lna", {"name": "UFSC",
                                            "latitude": "-27 36 13 ",
                                            "longitude": "-48 31 20",
                                            "altitude": "20",
                                            "utc_offset": "-3"})

        #self.manager.addClass(Meade, "meade", {"device": "/dev/ttyS6"})
        #self.manager.addClass(Telescope, "meade", {"driver": "/Meade/meade"})

        self.manager.addClass(FakeTelescope, "fake")
        self.manager.addClass(Telescope, "fake", {"driver": "/FakeTelescope/fake"})

        #self.manager.addClass(Telescope, "meade",
        #                      {"driver": "200.131.64.134:7666/TheSkyTelescope/0"})

        self.tel = self.manager.getProxy(Telescope)

    def teardown (self):
        self.manager.shutdown()

    def test_slew (self):

        ra  = self.tel.getRa()
        dec = self.tel.getDec()

        dest_ra  = (ra+"1 00 00")
        dest_dec = (dec+"15 00 00")

        @callback(self.manager)
        def slewBeginClbk(target):
            assert target.ra == dest_ra
            assert target.dec == dest_dec

        @callback(self.manager)
        def slewCompleteClbk(position):
            assertEpsEqual(position.ra, dest_ra, 60)
            assertEpsEqual(position.dec, dest_dec, 60)

        self.tel.slewBegin += slewBeginClbk
        self.tel.slewComplete += slewCompleteClbk

        self.tel.slewToRaDec((dest_ra, dest_dec))

    def test_slew_abort (self):

        last_ra  = self.tel.getRa()
        last_dec = self.tel.getDec()

        dest_ra  = last_ra  + "01 00 00"
        dest_dec = last_dec + "10 00 00"

        @callback(self.manager)
        def abortCompleteClbk(position):
            assert last_ra  < position.ra  < dest_ra
            assert last_dec < position.dec < dest_dec

        self.tel.abortComplete += abortCompleteClbk

        # async slew
        def slew():
            self.tel = self.manager.getProxy(Telescope)
            self.tel.slewToRaDec((dest_ra, dest_dec))

        pool = ThreadPool()
        pool.queueTask(slew)

        # wait thread to be scheduled
        time.sleep(2)

        # abort and test (on abortCompleteClbk).
        self.tel.abortSlew()

        pool.joinAll()

    def test_sync (self):

        # get current position, drift the scope, and sync on the first
        # position (like done when aligning the telescope).

        real_ra  = self.tel.getRa()
        real_dec = self.tel.getDec()

        @callback(self.manager)
        def syncCompleteClbk(position):
            assert position.ra == real_ra
            assert position.dec == real_dec

        self.tel.syncComplete += syncCompleteClbk

        # drift to "real" object coordinate
        self.tel.slewToRaDec((real_ra+"01 00 00", real_dec+"01 00 00"))

        self.tel.syncRaDec((real_ra, real_dec))

    def test_park (self):
        
        # FIXME: make a real test.
        return

        def printPosition():
            print self.tel.getPositionRaDec(), self.tel.getPositionAltAz()
            sys.stdout.flush()
            
        print

        ra  = self.tel.getRa()
        dec = self.tel.getDec()

        print "current position:", self.tel.getPositionRaDec()
        print "moving to:", (ra-"01 00 00"), (dec-"01 00 00")

        self.tel.slewToRaDec((ra-"01 00 00", dec-"01 00 00"))

        for i in range(10):
            printPosition()
            time.sleep(0.5)

        print "parking..."
        sys.stdout.flush()
        self.tel.park()

        t0 = time.time()
        wait = 30

        for i in range(10):
            printPosition()
            time.sleep(0.5)
       
        while time.time() < t0+wait:
            print "\rwaiting ... ",
            sys.stdout.flush()
            time.sleep(1)

        print "unparking..."
        sys.stdout.flush()

        self.tel.unpark()

        for i in range(10):
            printPosition()
            time.sleep(0.5)
Ejemplo n.º 33
0
    def test_autolock(self):
        class Minimo(ChimeraObject):
            def __init__(self):
                ChimeraObject.__init__(self)

                self.t0 = time.time()

            def doUnlocked(self):
                time.sleep(1)
                t = time.time() - self.t0
                print("[unlocked] - %s - %.3f" %
                      (threading.currentThread().getName(), t))
                return t

            @lock
            def doLocked(self):
                time.sleep(1)
                t = time.time() - self.t0
                print("[ locked ] - %s - %.3f" %
                      (threading.currentThread().getName(), t))
                return t

#            def doLockedWith (self):
#                with self:
#                    time.sleep(1)
#                    t = time.time()-self.t0
#                    print "[ locked ] - %s - %.3f" % (threading.currentThread().getName(), t)
#                    return t

        def doTest(obj):
            """Rationale: We use 5 threads for each method (locked and
            unlocked). As unlocked methods isn't serialized, they runs
            'at the same instant', while locked methods will be
            serialized and will run only when the previous one
            finishes.  Each method simulate a load (sleep of 1s) and
            then returns the time of completion (with an arbitrary
            zero point to give small numbers). The deviation from the
            mean of unlocked methods termination times should be
            nearly zero, as every methods runs at the same time. For
            locked ones, the termination time will be a linear
            function with the slope equals to the load (sleep in this
            case), and as we use 10 threads for the locked case, the
            deviation will be ~ 2.872. We use a simple equals_eps to
            handle load factors that may influence scheduler
            performance and timmings.
            """
            unlocked = []
            locked = []

            def getObj(o):
                """
                Copy Proxy to share between threads.
                """
                if isinstance(o, Proxy):
                    return copy.copy(o)
                return o

            def runUnlocked():
                unlocked.append(getObj(obj).doUnlocked())

            def runLocked():
                locked.append(getObj(obj).doLocked())

#            def runLockedWith():
#                locked.append(getObj(obj).doLockedWith())

            threads = []

            print()

            for i in range(10):
                t1 = threading.Thread(target=runUnlocked,
                                      name="unlocked-%d" % i)
                t2 = threading.Thread(target=runLocked, name="  lock-%d" % i)
                #t3 = threading.Thread(target=runLockedWith, name="  with-%d" % i)

                t1.start()
                t2.start()
                #t3.start()

                threads += [t1, t2]

            for t in threads:
                t.join()

            unlocked_mean = sum(unlocked) / len(unlocked)
            locked_mean = sum(locked) / len(locked)

            unlocked_sigma = sqrt(
                sum([(unlocked_mean - u)**2
                     for u in unlocked]) / len(unlocked))
            locked_sigma = sqrt(
                sum([(locked_mean - l)**2 for l in locked]) / len(locked))

            def equals_eps(a, b, eps=1e-3):
                return abs(a - b) <= eps

            print("unlocked: mean: %.6f sigma: %.6f" %
                  (unlocked_mean, unlocked_sigma))
            print("locked  : mean: %.6f sigma: %.6f" %
                  (locked_mean, locked_sigma))

            assert equals_eps(unlocked_sigma, 0.0, 0.5)
            assert equals_eps(locked_sigma, 2.875, 1.0)

        # direct metaobject
        m = Minimo()
        doTest(m)

        # proxy
        manager = Manager()
        manager.addClass(Minimo, "m", start=True)

        p = manager.getProxy(Minimo)
        doTest(p)

        manager.shutdown()
Ejemplo n.º 34
0
    def test_autolock(self):
        class Minimo(ChimeraObject):
            def __init__(self):
                ChimeraObject.__init__(self)

                self.t0 = time.time()

            def doUnlocked(self):
                time.sleep(1)
                t = time.time() - self.t0
                print "[unlocked] - %s - %.3f" % (threading.currentThread().getName(), t)
                return t

            @lock
            def doLocked(self):
                time.sleep(1)
                t = time.time() - self.t0
                print "[ locked ] - %s - %.3f" % (threading.currentThread().getName(), t)
                return t

        #            def doLockedWith (self):
        #                with self:
        #                    time.sleep(1)
        #                    t = time.time()-self.t0
        #                    print "[ locked ] - %s - %.3f" % (threading.currentThread().getName(), t)
        #                    return t

        def doTest(obj):

            """Rationale: We use 5 threads for each method (locked and
            unlocked). As unlocked methods isn't serialized, they runs
            'at the same instant', while locked methods will be
            serialized and will run only when the previous one
            finishes.  Each method simulate a load (sleep of 1s) and
            then returns the time of completion (with an arbitrary
            zero point to give small numbers). The deviation from the
            mean of unlocked methods termination times should be
            nearly zero, as every methods runs at the same time. For
            locked ones, the termination time will be a linear
            function with the slope equals to the load (sleep in this
            case), and as we use 10 threads for the locked case, the
            deviation will be ~ 2.872. We use a simple equals_eps to
            handle load factors that may influence scheduler
            performance and timmings.
            """
            unlocked = []
            locked = []

            def getObj(o):
                """
                Copy Proxy to share between threads.
                """
                if isinstance(o, Proxy):
                    return copy.copy(o)
                return o

            def runUnlocked():
                unlocked.append(getObj(obj).doUnlocked())

            def runLocked():
                locked.append(getObj(obj).doLocked())

            #            def runLockedWith():
            #                locked.append(getObj(obj).doLockedWith())

            threads = []

            print

            for i in range(10):
                t1 = threading.Thread(target=runUnlocked, name="unlocked-%d" % i)
                t2 = threading.Thread(target=runLocked, name="  lock-%d" % i)
                # t3 = threading.Thread(target=runLockedWith, name="  with-%d" % i)

                t1.start()
                t2.start()
                # t3.start()

                threads += [t1, t2]

            for t in threads:
                t.join()

            unlocked_mean = sum(unlocked) / len(unlocked)
            locked_mean = sum(locked) / len(locked)

            unlocked_sigma = sqrt(sum([(unlocked_mean - u) ** 2 for u in unlocked]) / len(unlocked))
            locked_sigma = sqrt(sum([(locked_mean - l) ** 2 for l in locked]) / len(locked))

            def equals_eps(a, b, eps=1e-3):
                return abs(a - b) <= eps

            print "unlocked: mean: %.6f sigma: %.6f" % (unlocked_mean, unlocked_sigma)
            print "locked  : mean: %.6f sigma: %.6f" % (locked_mean, locked_sigma)

            assert equals_eps(unlocked_sigma, 0.0, 0.5)
            assert equals_eps(locked_sigma, 2.875, 1.0)

        # direct metaobject
        m = Minimo()
        doTest(m)

        # proxy
        manager = Manager()
        manager.addClass(Minimo, "m", start=True)

        p = manager.getProxy(Minimo)
        doTest(p)

        manager.shutdown()
Ejemplo n.º 35
0
class ChimeraCLI (object):
    """
    Create a command line program with automatic parsing of actions
    and parameters based on decorators.

    This class define common methods for a command line interface
    (CLI) program. You should extends it and add methods with specific
    decorators to create personalized CLI programs.

    This class defines a CLI program which accepts parameters (of any
    kind) and do actions using those parameters. Only one action will
    run for a given command line. if more than one action was asked,
    only the first will run.

    The general form of the arguments that CLI accepts is given
    below:

    cli-program (--action-1|--action-2|...|--action-n)
                [--param-1=value1,--param-2=value-2|...|--param-n=value-n]

    Al parameters are optional, action code will check for required
    parameters and shout if needed.

    At least one action is required, if none given, --help will be
    fired.

    There are a few auto-generated options:
     --help --quiet --verbose (default=True) --log=file

    To create actions, use 'action' decorator. If that action was
    detected on the command line arguments, action method will be
    called with an object containing all the parameters available.

    For example:

    @action(short='s', long='slew'):
    def slew(self, options):
        inst.slew(options.ra, options.dec)

    To define parameters, use parameter decorator or addParameter method.
    The parameter method passed to the decorator will be called to validate
    the parameter value given on the command line. Otherwise, no
    validation, besides type checking, will be done.

    For example:

    self.addParameter(name='ra', help='Help for RA', type=string)

    or

    @parameter(long='ra', type=string)
    def ra(self, value):
        '''
        Help for RA
        '''
        # validate
        # return valid value or throw ValueError

    When you define a Parameter using @parameter decorator,
    the name of the decorated function will be available in the options
    dictionary passed to every action. Otherwise, you need to use name
    keyword to define different names or to use with attribute based parameters

    Before run the selected action, ChimeraCLI runs the method
    __start__, passing all the parameters and the action that would
    run. After the action be runned, __stop__ would be called.

    """
            
    def __init__ (self, prog, description, version,
                  port=None, verbosity=True,
                  instrument_path=True, controllers_path=True):

        self.parser = optparse.OptionParser(prog=prog,
                                            description=_chimera_description_ + " - " + description,
                                            version="Chimera: %s\n%s: %s" % (_chimera_version_, prog, version))

        # hack to inject our exit funciton into the parser
        def parser_exit(status=0, msg=None):
            return self.exit(msg=msg, ret=status)

        self.parser.exit = parser_exit

        self.options = None

        self._actions = {}
        self._parameters = {}
        
        self._helpGroups = {}
        
        self._aborting = False

        self._keepRemoteManager = True

        # shutdown event
        self.died = threading.Event()
        
        # base actions and parameters

        if verbosity:
            self.addParameters(dict(name="quiet", short="q", long="quiet",
                                    type=ParameterType.BOOLEAN, default=True,
                                    help="Don't display information while working."),

                               dict(name="verbose", short="v", long="verbose",
                                    type=ParameterType.BOOLEAN, default=False,
                                    help="Display information while working"))

        self.addHelpGroup("LOCALMANAGER", "Client Configuration")
        self.addParameters(dict(name="port", short="P", helpGroup="LOCALMANAGER", default=port or 9000,
                                help="Port to which the local Chimera instance will listen to."),
                           dict(name="config", default=SYSTEM_CONFIG_DEFAULT_FILENAME,
                                    help="Chimera configuration file to use. default=%default",
                                    helpGroup="LOCALMANAGER"))

        self.localManager  = None
        self._remoteManager = None
        self.sysconfig = None

        self._needInstrumentsPath = instrument_path
        self._needControllersPath = controllers_path

    def _print(self, *args, **kwargs):
        sep = kwargs.pop("sep", " ")
        end = kwargs.pop("end", "\n")
        stream = kwargs.pop("file", sys.stdout)
        
        for arg in args:
            stream.write(arg)
            stream.write(sep)

        stream.write(end)
        stream.flush()
        
    def out(self, *args, **kwargs):
        self._print(*args, **kwargs)

    def err(self, *args, **kwargs):
        kwargs["file"] = sys.stderr
        self._print(*args, **kwargs)
        
    def addParameters(self, *params):
        for param in params:
            p = Parameter(**param)
            self._parameters[p.name] = p

    def addActions(self, *actions):
        for action in actions:
            act = Action(**action)
            self._actions[act.name] = act

    def addHelpGroup(self, name, shortdesc, longdesc=None):
        self._helpGroups[name] = optparse.OptionGroup(self.parser, shortdesc, longdesc)

    def addInstrument (self, **params):
        params["type"] = ParameterType.INSTRUMENT
        self.addParameters(params)

        if self._needInstrumentsPath:
            if not "PATHS" in self._helpGroups:
                self.addHelpGroup("PATHS", "Object Paths")

            self.addParameters(dict(name="inst_dir", short="I", long="instruments-dir", helpGroup="PATHS",
                                    type=ParameterType.INCLUDE_PATH, default=[ChimeraPath.instruments()],
                                    help="Append PATH to %s load path. "
                                    "This option could be setted multiple "
                                    "times to add multiple directories." % params["name"].capitalize(),
                                    metavar="PATH"))
            self._needInstrumentsPath = False
            

    def addController (self, **params):
        params["type"] = ParameterType.CONTROLLER
        self.addParameters(params)

        if self._needControllersPath:
            if not "PATHS" in self._helpGroups:
                self.addHelpGroup("PATHS", "Object Paths")

            self.addParameters(dict(name="ctrl_dir", short="C", long="controllers-dir", helpGroup="PATHS",
                                    type=ParameterType.INCLUDE_PATH, default=[ChimeraPath.controllers()],
                                    help="Append PATH to controllers load path. "
                                    "This option could be setted multiple "
                                    "times to add multiple directories.",
                                    metavar="PATH"))
            self._needControllersPath = False

    def exit(self, msg=None, ret=1):
        self.__stop__(self.options)

        if msg:
            self.err(msg)

        self.died.set()
        
        sys.exit(ret)

    def run (self, cmdlineArgs):
        t = threading.Thread(target=self._run, args=(cmdlineArgs,))
        t.setDaemon(True)
        t.start()

    def _run(self, cmdlineArgs):

        # create parser from defined actions and parameters
        self._createParser()

        # run the parser
        self.options, args = self.parser.parse_args(cmdlineArgs, values=CLIValues(defaults=self.parser.get_default_values().__dict__))
        
        # check which actions should run and if there is any conflict
        actions = self._getActions(self.options)

        if not actions:
            self.exit("Please select one action or --help for more information.")
            
        # for each defined parameter, run validation code
        self._validateParameters(self.options)

        # setup objects
        self._setupObjects(self.options)

        self.__start__(self.options, args)

        # run actions
        for action in actions:
            if not self._runAction(action, self.options):
                self.exit(ret=1)

        self.__stop__(self.options)
        
        self.died.set()

    def wait(self, abort=True):
        try:
            while not self.died.isSet():
                time.sleep(0.1)
        except KeyboardInterrupt:
            if abort: self.abort()

    def _startSystem (self, options):
        
        try:
            self.sysconfig = SystemConfig.fromFile(options.config)
            self.localManager = Manager(self.sysconfig.chimera["host"], getattr(options, 'port', 9000))
            self._remoteManager = ManagerLocator.locate(self.sysconfig.chimera["host"], self.sysconfig.chimera["port"])
        except ManagerNotFoundException:
            # FIXME: better way to start Chimera
            site = SiteController(wait=False)
            site.startup()

            self._keepRemoteManager = False
            self._remoteManager = ManagerLocator.locate(self.sysconfig.chimera["host"], self.sysconfig.chimera["port"])

    def _belongsTo(self, meHost, mePort, location):
        
        if not location: return False

        meName = socket.gethostbyname(meHost)
        return (location.host == None or location.host in (meHost, meName)) and \
               (location.port == None or location.port == mePort)

    def _setupObjects (self, options):

        # CLI requested objects
        instruments = dict([(x.name, x) for x in self._parameters.values() if x.type == ParameterType.INSTRUMENT])
        controllers = dict([(x.name, x) for x in self._parameters.values() if x.type == ParameterType.CONTROLLER])

        # starts a local Manager (not using sysconfig) or a full sysconfig backed if needed.
        self._startSystem(self.options)

        # create locations
        for inst in instruments.values() + controllers.values():
            
            # use user instrument if given
            if inst.default != getattr(options, inst.name):
                try:
                    inst.location = Location(getattr(options, inst.name))
                except InvalidLocationException:
                    self.exit("Invalid location: %s. See --help for more information" % getattr(options, inst.name))

            else:
                # no instrument selected, ask remote Chimera instance for the newest
                if self._remoteManager:
                    insts = self._remoteManager.getResourcesByClass(inst.cls)
                    if insts:
                        # get the older
                        inst.location = insts[0]

            if not inst.location and inst.required:
                self.exit("Couldn't find %s configuration. "
                          "Edit %s or see --help for more information" % (inst.name.capitalize(), os.path.abspath(options.config)))


        for inst in instruments.values() + controllers.values():

            inst_proxy = None

            try:
                inst_proxy = self._remoteManager.getProxy(inst.location)
            except ObjectNotFoundException:
                if inst.required == True:
                    self.exit("Couldn't find %s. (see --help for more information)" % inst.name.capitalize())

            # save values in CLI object (which users are supposed to inherites from).
            setattr(self, inst.name, inst_proxy)                

    def __start__ (self, options, args):
        pass

    def __stop__ (self, options):
        if self.localManager:
            self.localManager.shutdown()

        try:
            if self._remoteManager and not self._keepRemoteManager:
                self._remoteManager.shutdown()
        except Pyro.errors.ConnectionClosedError:
            pass

    def _createParser (self):

        for name in dir(self):
            attr = getattr(self, name)

            if isinstance(attr, Action) or hasattr(attr, '__payload__'):

                try:
                    # decorated methods
                    payload = getattr(attr, '__payload__')
                except AttributeError:
                    # pure attribute
                    payload = attr

                if type(payload) == Action:
                    self._actions[payload.name] = payload
                elif type(payload) == Parameter:
                    self._parameters[payload.name] = payload

        for action in self._actions.values():
            
            if not action.actionGroup:
                action.actionGroup = action.name

            if action.type:
                kind = "store"
            else:
                kind = "store_true"

            group = self._helpGroups.get(action.helpGroup, self.parser)

            if action.short:
                group.add_option(action.short, action.long,
                                 action=kind, type=action.type, dest=action.name,
                                 help=action.help, metavar=action.metavar)
            else:
                group.add_option(action.long, dest=action.name,
                                 action=kind, type=action.type,
                                 help=action.help, metavar=action.metavar)

        for param in self._parameters.values():

            if not param.type:
                param.type = "string"

            group = self._helpGroups.get(param.helpGroup, self.parser)

            option_action = "store"
            option_callback = None
            option_choices = None
            option_const = None
            option_type = param.type or None

            if param.type in (ParameterType.INSTRUMENT, ParameterType.CONTROLLER):
                option_type = "string"
                option_action = "callback"
                option_callback  = CLICheckers.check_location

            if param.type == ParameterType.BOOLEAN:
                option_action = "store_true"
                option_type = None

            if param.type == ParameterType.CONSTANT:
                option_action = "store_const"
                option_type = None
                option_const = param.const

            if param.type == ParameterType.INCLUDE_PATH:
                option_action = "callback"
                option_type = "string"
                option_callback = CLICheckers.check_includepath
                
            if param.type == ParameterType.CHOICE:
                option_action = "store"
                option_type = "choice"
                option_choices = param.choices
                
            option_kwargs = dict(action=option_action,
                                 dest=param.name,
                                 help=param.help, metavar=param.metavar)

            if option_callback:
                option_kwargs["callback"] = option_callback

            if option_type:
                option_kwargs["type"] = option_type
                
            if option_choices:
                option_kwargs["choices"] = option_choices

            if option_const:
                option_kwargs["const"] = option_const

            if param.short:
                group.add_option(param.short, param.long, **option_kwargs)
            else:
                group.add_option(param.long, **option_kwargs)

        for group in self._helpGroups.values():
            self.parser.add_option_group(group)

        defaults = {}

        for action in self._actions.values():
            if action.default is not None:
                defaults[action.name] = action.default

        for param in self._parameters.values():
            if param.default is not None:
                defaults[param.name] = param.default

        self.parser.set_defaults(**defaults)

    def _getActions(self, options):

        # actions in command line (and run) order
        actions = [ self._actions[action] for action in self.options.__order__ if action in self._actions ]
        
        # add default actions
        # FIXME: there is no way to disable a default action?
        actions.extend([ action for action in self._actions.values() if action.default == True])
        
        if not actions: return []
        
        for action in actions:
            for other in actions:
                if action != other and action.actionGroup == other.actionGroup:
                    self.exit("Cannot use %s and %s at the same time." % (action.long, other.long))

        # remove duplicates
        uniqueActions = []
        
        for action in actions:
            if action in uniqueActions: continue
            uniqueActions.append(action)

        return uniqueActions

    def _validateParameters(self, options):

        paramValues =  [ getattr(options, param) for param in self._parameters.keys() ]

        for name, value in zip(self._parameters.keys(), paramValues):
            param = self._parameters[name]

            try:
                # to signal invalid values, use self.exit or throws a ValueError exception
                # if None returned, just copy passed value
                if param.target is not None:
                    newValue = getattr(self, param.target.__name__)(value)
                    setattr(options, name, newValue or value)
            except ValueError, e:
                self.exit("Invalid value for %s: %s" % (name, e))
Ejemplo n.º 36
0
class TestEvents (object):

    def setup (self):
        self.manager = Manager()

    def teardown (self):
        self.manager.shutdown()
        del self.manager

    def test_publish (self):

        assert self.manager.addClass (Publisher, "p") != False
        assert self.manager.addClass (Subscriber, "s") != False

        p = self.manager.getProxy("/Publisher/p")
        assert isinstance(p, Proxy)
        
        s = self.manager.getProxy("/Subscriber/s")
        assert isinstance(s, Proxy)

        p.fooDone += s.fooDoneClbk

        assert p.foo() == 42
        time.sleep (0.5) # delay to get messages delivered
        assert s.getCounter() == 1
        assert p.getCounter() == 1

        assert p.foo() == 42
        time.sleep (0.5) # delay to get messages delivered
        assert s.getCounter() == 2
        assert p.getCounter() == 2        

        # unsubscribe
        p.fooDone -= s.fooDoneClbk
        p.fooDone -= p.fooDoneClbk        
        
        assert p.foo() == 42
        time.sleep (0.5) # delay to get messages delivered
        assert s.getCounter() == 2
        assert p.getCounter() == 2        

    def test_performance (self):

        assert self.manager.addClass (Publisher, "p") != False
        assert self.manager.addClass (Subscriber, "s") != False

        p = self.manager.getProxy("/Publisher/p")
        assert isinstance(p, Proxy)
        
        s = self.manager.getProxy("/Subscriber/s")
        assert isinstance(s, Proxy)

        p.fooDone += s.fooDoneClbk

        for check in range (1):

            start = time.time()
            for i in range (100):
                p.foo()
            end = time.time()

            time.sleep (5)

            results = s.getResults()

            dt   = [ (t - t0)*1000 for t0, t in results]
            mean = sum (dt) / len(dt)
        
            sigma = math.sqrt(sum([ (t - mean)**2 for t in dt]) / len(dt))

            print "#"*25
            print "# %d events (%.3f s)" % (len(dt), (end-start))
            print "# %.2f events/s" % (len(dt)/(end-start))
            print "# min   : %-6.3f ms" % min(dt)
            print "# max   : %-6.3f ms" % max(dt)        
            print "# mean  : %-6.3f ms" % mean
            print "# sigma : %-6.3f ms" % sigma
            print "#"*25
Ejemplo n.º 37
0
def doEventClbk(result):
    print result


m.eventDone += doEventClbk
m.doEvent()

# exception
try:
    m.doRaise()
except MinimoException, e:
    printException(e)

# static method
print m.doStatic()

# class method
print m.doClass()

# configuration
print "option1 =>", m['option1']
print "option2 =>", m['option2']

m += {"option1": "new value 1", "option2": "new value 2"}

print "option1 =>", m['option1']
print "option2 =>", m['option2']

# bye
manager.shutdown()
Ejemplo n.º 38
0
class SiteController(object):
    def __init__(self, args=[], wait=True):

        self.wait = wait

        self.options, self.args = self.parseArgs(args)

        if self.options.verbose == 1:
            chimera.core.log.setConsoleLevel(logging.INFO)
            #log.setConsoleLevel(logging.INFO)

        if self.options.verbose > 1:
            chimera.core.log.setConsoleLevel(logging.DEBUG)
            #log.setConsoleLevel(logging.DEBUG)

        self.manager = None

        self.paths = {"instruments": [], "controllers": []}

        # add system and plugins paths
        Path = ChimeraPath()
        self.paths["instruments"].extend(Path.instruments)
        self.paths["controllers"].extend(Path.controllers)

    def parseArgs(self, args):
        def check_location(option, opt_str, value, parser):
            try:
                l = Location(value)
            except InvalidLocationException:
                raise optparse.OptionValueError("%s isnt't a valid location." %
                                                value)

            eval('parser.values.%s.append ("%s")' % (option.dest, value))

        def check_includepath(option, opt_str, value, parser):

            if not value or not os.path.isdir(os.path.abspath(value)):
                raise optparse.OptionValueError(
                    "Couldn't found %s include path." % value)

            eval('parser.values.%s.append ("%s")' % (option.dest, value))

        parser = optparse.OptionParser(
            prog="chimera",
            version=_chimera_version_,
            description=_chimera_description_,
            usage="chimera --help for more information")

        manag_group = optparse.OptionGroup(parser, "Basic options")
        manag_group.add_option(
            "-H",
            "--host",
            action="store",
            dest="pyro_host",
            type="string",
            help="Host name/IP address to run as; [default=%default]",
            metavar="HOST")

        manag_group.add_option(
            "-P",
            "--port",
            action="store",
            dest="pyro_port",
            type="string",
            help="Port on which to listen for requests; [default=%default]",
            metavar="PORT")

        config_group = optparse.OptionGroup(parser, "Configuration")

        config_group.add_option(
            "--config",
            dest="config_file",
            help="Start Chimera using configuration from FILE.",
            metavar="FILE")

        config_group.add_option(
            "--daemon",
            action="store_true",
            dest='daemon',
            help=
            "Run Chimera in Daemon mode (will detach from current terminal).")

        misc_group = optparse.OptionGroup(parser, "General")

        misc_group.add_option(
            "--dry-run",
            action="store_true",
            dest="dry",
            help=
            "Only list all configured objects (from command line and configuration files) without starting the system."
        )

        misc_group.add_option(
            "-v",
            "--verbose",
            action="count",
            dest='verbose',
            help="Increase log level (multiple v's to increase even more).")

        inst_group = optparse.OptionGroup(
            parser, "Instruments and Controllers Management")

        inst_group.add_option(
            "-i",
            "--instrument",
            action="callback",
            callback=check_location,
            dest="instruments",
            type="string",
            help="Load the instrument defined by LOCATION."
            "This option could be set many times to load multiple instruments.",
            metavar="LOCATION")

        inst_group.add_option(
            "-c",
            "--controller",
            action="callback",
            callback=check_location,
            dest="controllers",
            type="string",
            help="Load the controller defined by LOCATION."
            "This option could be set many times to load multiple controllers.",
            metavar="LOCATION")

        inst_group.add_option("-I",
                              "--instruments-dir",
                              action="callback",
                              callback=check_includepath,
                              dest="inst_dir",
                              type="string",
                              help="Append PATH to instruments load path.",
                              metavar="PATH")

        inst_group.add_option("-C",
                              "--controllers-dir",
                              action="callback",
                              callback=check_includepath,
                              dest="ctrl_dir",
                              type="string",
                              help="Append PATH to controllers load path.",
                              metavar="PATH")

        parser.add_option_group(manag_group)
        parser.add_option_group(config_group)
        parser.add_option_group(misc_group)
        parser.add_option_group(inst_group)

        parser.set_defaults(instruments=[],
                            controllers=[],
                            config_file=SYSTEM_CONFIG_DEFAULT_FILENAME,
                            inst_dir=[],
                            ctrl_dir=[],
                            drv_dir=[],
                            dry=False,
                            verbose=0,
                            daemon=False,
                            pyro_host=MANAGER_DEFAULT_HOST,
                            pyro_port=MANAGER_DEFAULT_PORT)

        return parser.parse_args(args)

    def startup(self):

        if self.options.daemon:
            # detach
            log.info("FIXME: Daemon...")

        # system config
        try:
            self.config = SystemConfig.fromFile(self.options.config_file)
        except (InvalidLocationException, IOError) as e:
            log.exception(e)
            log.error(
                "There was a problem reading your configuration file. (%s)" %
                e)
            sys.exit(1)

        # manager
        if not self.options.dry:
            log.info("Starting system.")
            log.info("Chimera: %s" % _chimera_version_)
            log.info("Chimera prefix: %s" % ChimeraPath().root())
            log.info("Python: %s" % platform.python_version())
            log.info("System: %s" % ' '.join(platform.uname()))

            try:
                self.manager = Manager(**self.config.chimera)
            except ChimeraException as e:
                log.error(
                    "Chimera is already running on this machine. Use chimera-admin to manage it."
                )
                sys.exit(1)

            log.info("Chimera: running on " + self.manager.getHostname() +
                     ":" + str(self.manager.getPort()))
            log.info("Chimera: reading configuration from %s" %
                     os.path.realpath(self.options.config_file))

        # add site object
        if not self.options.dry:

            for site in self.config.sites:
                self.manager.addClass(Site, site.name, site.config, True)

        # search paths
        log.info(
            "Setting objects include path from command line parameters...")
        for _dir in self.options.inst_dir:
            self.paths["instruments"].append(_dir)

        for _dir in self.options.ctrl_dir:
            self.paths["controllers"].append(_dir)

        # init from config
        log.info("Trying to start instruments...")
        for inst in self.config.instruments + self.options.instruments:

            if self.options.dry:
                print(inst)
            else:
                self._add(inst, path=self.paths["instruments"], start=True)

        log.info("Trying to start controllers...")
        for ctrl in self.config.controllers + self.options.controllers:

            if self.options.dry:
                print(ctrl)
            else:
                self._add(ctrl, path=self.paths["controllers"], start=True)

        log.info("System up and running.")

        # ok, let's wait manager work
        if self.wait and not self.options.dry:
            self.manager.wait()

    def _add(self, location, path, start):
        try:
            self.manager.addLocation(location, path, start)
        except Exception as e:
            printException(e)

    def shutdown(self):
        log.info("Shutting down system.")
        self.manager.shutdown()
Ejemplo n.º 39
0
class ChimeraCLI(object):
    """
    Create a command line program with automatic parsing of actions
    and parameters based on decorators.

    This class define common methods for a command line interface
    (CLI) program. You should extends it and add methods with specific
    decorators to create personalized CLI programs.

    This class defines a CLI program which accepts parameters (of any
    kind) and do actions using those parameters. Only one action will
    run for a given command line. if more than one action was asked,
    only the first will run.

    The general form of the arguments that CLI accepts is given
    below:

    cli-program (--action-1|--action-2|...|--action-n)
                [--param-1=value1,--param-2=value-2|...|--param-n=value-n]

    Al parameters are optional, action code will check for required
    parameters and shout if needed.

    At least one action is required, if none given, --help will be
    fired.

    There are a few auto-generated options:
     --help --quiet --verbose (default=True) --log=file

    To create actions, use 'action' decorator. If that action was
    detected on the command line arguments, action method will be
    called with an object containing all the parameters available.

    For example:

    @action(short='s', long='slew'):
    def slew(self, options):
        inst.slew(options.ra, options.dec)

    To define parameters, use parameter decorator or addParameter method.
    The parameter method passed to the decorator will be called to validate
    the parameter value given on the command line. Otherwise, no
    validation, besides type checking, will be done.

    For example:

    self.addParameter(name='ra', help='Help for RA', type=string)

    or

    @parameter(long='ra', type=string)
    def ra(self, value):
        '''
        Help for RA
        '''
        # validate
        # return valid value or throw ValueError

    When you define a Parameter using @parameter decorator,
    the name of the decorated function will be available in the options
    dictionary passed to every action. Otherwise, you need to use name
    keyword to define different names or to use with attribute based parameters

    Before run the selected action, ChimeraCLI runs the method
    __start__, passing all the parameters and the action that would
    run. After the action be runned, __stop__ would be called.

    """
    def __init__(self,
                 prog,
                 description,
                 version,
                 port=None,
                 verbosity=True,
                 instrument_path=True,
                 controllers_path=True):

        self.parser = optparse.OptionParser(
            prog=prog,
            description=_chimera_description_ + " - " + description,
            version="Chimera: %s\n%s: %s" % (_chimera_version_, prog, version))

        # hack to inject our exit funciton into the parser
        def parser_exit(status=0, msg=None):
            return self.exit(msg=msg, ret=status)

        self.parser.exit = parser_exit

        self.options = None

        self._actions = {}
        self._parameters = {}

        self._helpGroups = {}

        self._aborting = False

        self._keepRemoteManager = True

        # shutdown event
        self.died = threading.Event()

        # base actions and parameters

        if verbosity:
            self.addParameters(
                dict(name="quiet",
                     short="q",
                     long="quiet",
                     type=ParameterType.BOOLEAN,
                     default=True,
                     help="Don't display information while working."),
                dict(name="verbose",
                     short="v",
                     long="verbose",
                     type=ParameterType.BOOLEAN,
                     default=False,
                     help="Display information while working"))

        self.addHelpGroup("LOCALMANAGER", "Client Configuration")
        self.addParameters(
            dict(
                name="port",
                short="P",
                helpGroup="LOCALMANAGER",
                default=port or 9000,
                help="Port to which the local Chimera instance will listen to."
            ),
            dict(name="config",
                 default=SYSTEM_CONFIG_DEFAULT_FILENAME,
                 help="Chimera configuration file to use. default=%default",
                 helpGroup="LOCALMANAGER"))

        self.localManager = None
        self._remoteManager = None
        self.sysconfig = None

        self._needInstrumentsPath = instrument_path
        self._needControllersPath = controllers_path

    def _print(self, *args, **kwargs):
        sep = kwargs.pop("sep", " ")
        end = kwargs.pop("end", "\n")
        stream = kwargs.pop("file", sys.stdout)

        for arg in args:
            stream.write(arg)
            stream.write(sep)

        stream.write(end)
        stream.flush()

    def out(self, *args, **kwargs):
        self._print(*args, **kwargs)

    def err(self, *args, **kwargs):
        kwargs["file"] = sys.stderr
        self._print(*args, **kwargs)

    def addParameters(self, *params):
        for param in params:
            p = Parameter(**param)
            self._parameters[p.name] = p

    def addActions(self, *actions):
        for action in actions:
            act = Action(**action)
            self._actions[act.name] = act

    def addHelpGroup(self, name, shortdesc, longdesc=None):
        self._helpGroups[name] = optparse.OptionGroup(self.parser, shortdesc,
                                                      longdesc)

    def addInstrument(self, **params):
        params["type"] = ParameterType.INSTRUMENT
        self.addParameters(params)

        if self._needInstrumentsPath:
            if not "PATHS" in self._helpGroups:
                self.addHelpGroup("PATHS", "Object Paths")

            self.addParameters(
                dict(name="inst_dir",
                     short="I",
                     long="instruments-dir",
                     helpGroup="PATHS",
                     type=ParameterType.INCLUDE_PATH,
                     default=ChimeraPath().instruments,
                     help="Append PATH to %s load path. "
                     "This option could be setted multiple "
                     "times to add multiple directories." %
                     params["name"].capitalize(),
                     metavar="PATH"))
            self._needInstrumentsPath = False

    def addController(self, **params):
        params["type"] = ParameterType.CONTROLLER
        self.addParameters(params)

        if self._needControllersPath:
            if not "PATHS" in self._helpGroups:
                self.addHelpGroup("PATHS", "Object Paths")

            self.addParameters(
                dict(name="ctrl_dir",
                     short="C",
                     long="controllers-dir",
                     helpGroup="PATHS",
                     type=ParameterType.INCLUDE_PATH,
                     default=ChimeraPath().controllers,
                     help="Append PATH to controllers load path. "
                     "This option could be setted multiple "
                     "times to add multiple directories.",
                     metavar="PATH"))
            self._needControllersPath = False

    def exit(self, msg=None, ret=1):
        self.__stop__(self.options)

        if msg:
            self.err(msg)

        self.died.set()

        sys.exit(ret)

    def run(self, cmdlineArgs):
        t = threading.Thread(target=self._run, args=(cmdlineArgs, ))
        t.setDaemon(True)
        t.start()

    def _run(self, cmdlineArgs):

        # create parser from defined actions and parameters
        self._createParser()

        # run the parser
        self.options, args = self.parser.parse_args(
            cmdlineArgs,
            values=CLIValues(
                defaults=self.parser.get_default_values().__dict__))

        # check which actions should run and if there is any conflict
        actions = self._getActions(self.options)

        if not actions:
            self.exit(
                "Please select one action or --help for more information.")

        # for each defined parameter, run validation code
        self._validateParameters(self.options)

        # setup objects
        self._setupObjects(self.options)

        self.__start__(self.options, args)

        # run actions
        for action in actions:
            if not self._runAction(action, self.options):
                self.exit(ret=1)

        self.__stop__(self.options)

        self.died.set()

    def wait(self, abort=True):
        try:
            while not self.died.isSet():
                time.sleep(0.1)
        except KeyboardInterrupt:
            if abort:
                self.abort()

    def _startSystem(self, options):

        try:
            self.sysconfig = SystemConfig.fromFile(options.config)
            self.localManager = Manager(self.sysconfig.chimera["host"],
                                        getattr(options, 'port', 9000))
            self._remoteManager = ManagerLocator.locate(
                self.sysconfig.chimera["host"], self.sysconfig.chimera["port"])
        except ManagerNotFoundException:
            # FIXME: better way to start Chimera
            site = SiteController(wait=False)
            site.startup()

            self._keepRemoteManager = False
            self._remoteManager = ManagerLocator.locate(
                self.sysconfig.chimera["host"], self.sysconfig.chimera["port"])

    def _belongsTo(self, meHost, mePort, location):

        if not location:
            return False

        meName = socket.gethostbyname(meHost)
        return (location.host is None or location.host in (meHost, meName)) and \
               (location.port is None or location.port == mePort)

    def _setupObjects(self, options):

        # CLI requested objects
        instruments = dict([(x.name, x) for x in self._parameters.values()
                            if x.type == ParameterType.INSTRUMENT])
        controllers = dict([(x.name, x) for x in self._parameters.values()
                            if x.type == ParameterType.CONTROLLER])

        # starts a local Manager (not using sysconfig) or a full sysconfig
        # backed if needed.
        self._startSystem(self.options)

        # create locations
        for inst in instruments.values() + controllers.values():

            # use user instrument if given
            if inst.default != getattr(options, inst.name):
                try:
                    inst.location = Location(getattr(options, inst.name))
                except InvalidLocationException:
                    self.exit(
                        "Invalid location: %s. See --help for more information"
                        % getattr(options, inst.name))

            else:
                # no instrument selected, ask remote Chimera instance for the
                # newest
                if self._remoteManager:
                    insts = self._remoteManager.getResourcesByClass(inst.cls)
                    if insts:
                        # get the older
                        inst.location = insts[0]

            if not inst.location and inst.required:
                self.exit(
                    "Couldn't find %s configuration. "
                    "Edit %s or see --help for more information" %
                    (inst.name.capitalize(), os.path.abspath(options.config)))

        for inst in instruments.values() + controllers.values():

            inst_proxy = None

            try:
                inst_proxy = self._remoteManager.getProxy(inst.location)
            except ObjectNotFoundException:
                if inst.required == True:
                    self.exit(
                        "Couldn't find %s. (see --help for more information)" %
                        inst.name.capitalize())

            # save values in CLI object (which users are supposed to inherites
            # from).
            setattr(self, inst.name, inst_proxy)

    def __start__(self, options, args):
        pass

    def __stop__(self, options):
        if self.localManager:
            self.localManager.shutdown()

        try:
            if self._remoteManager and not self._keepRemoteManager:
                self._remoteManager.shutdown()
        except Pyro.errors.ConnectionClosedError:
            pass

    def _createParser(self):

        for name in dir(self):
            attr = getattr(self, name)

            if isinstance(attr, Action) or hasattr(attr, '__payload__'):

                try:
                    # decorated methods
                    payload = getattr(attr, '__payload__')
                except AttributeError:
                    # pure attribute
                    payload = attr

                if type(payload) == Action:
                    self._actions[payload.name] = payload
                elif type(payload) == Parameter:
                    self._parameters[payload.name] = payload

        for action in self._actions.values():

            if not action.actionGroup:
                action.actionGroup = action.name

            if action.type:
                kind = "store"
            else:
                kind = "store_true"

            group = self._helpGroups.get(action.helpGroup, self.parser)

            if action.short:
                group.add_option(action.short,
                                 action.long,
                                 action=kind,
                                 type=action.type,
                                 dest=action.name,
                                 help=action.help,
                                 metavar=action.metavar)
            else:
                group.add_option(action.long,
                                 dest=action.name,
                                 action=kind,
                                 type=action.type,
                                 help=action.help,
                                 metavar=action.metavar)

        for param in self._parameters.values():

            if not param.type:
                param.type = "string"

            group = self._helpGroups.get(param.helpGroup, self.parser)

            option_action = "store"
            option_callback = None
            option_choices = None
            option_const = None
            option_type = param.type or None

            if param.type in (ParameterType.INSTRUMENT,
                              ParameterType.CONTROLLER):
                option_type = "string"
                option_action = "callback"
                option_callback = CLICheckers.check_location

            if param.type == ParameterType.BOOLEAN:
                option_action = "store_true"
                option_type = None

            if param.type == ParameterType.CONSTANT:
                option_action = "store_const"
                option_type = None
                option_const = param.const

            if param.type == ParameterType.INCLUDE_PATH:
                option_action = "callback"
                option_type = "string"
                option_callback = CLICheckers.check_includepath

            if param.type == ParameterType.CHOICE:
                option_action = "store"
                option_type = "choice"
                option_choices = param.choices

            option_kwargs = dict(action=option_action,
                                 dest=param.name,
                                 help=param.help,
                                 metavar=param.metavar)

            if option_callback:
                option_kwargs["callback"] = option_callback

            if option_type:
                option_kwargs["type"] = option_type

            if option_choices:
                option_kwargs["choices"] = option_choices

            if option_const:
                option_kwargs["const"] = option_const

            if param.short:
                group.add_option(param.short, param.long, **option_kwargs)
            else:
                group.add_option(param.long, **option_kwargs)

        for group in self._helpGroups.values():
            self.parser.add_option_group(group)

        defaults = {}

        for action in self._actions.values():
            if action.default is not None:
                defaults[action.name] = action.default

        for param in self._parameters.values():
            if param.default is not None:
                defaults[param.name] = param.default

        self.parser.set_defaults(**defaults)

    def _getActions(self, options):

        # actions in command line (and run) order
        actions = [
            self._actions[action] for action in self.options.__order__
            if action in self._actions
        ]

        # add default actions
        # FIXME: there is no way to disable a default action?
        actions.extend([
            action for action in self._actions.values()
            if action.default == True
        ])

        if not actions:
            return []

        for action in actions:
            for other in actions:
                if action != other and action.actionGroup == other.actionGroup:
                    self.exit("Cannot use %s and %s at the same time." %
                              (action.long, other.long))

        # remove duplicates
        uniqueActions = []

        for action in actions:
            if action in uniqueActions:
                continue
            uniqueActions.append(action)

        return uniqueActions

    def _validateParameters(self, options):

        paramValues = [
            getattr(options, param) for param in self._parameters.keys()
        ]

        for name, value in zip(self._parameters.keys(), paramValues):
            param = self._parameters[name]

            try:
                # to signal invalid values, use self.exit or throws a
                # ValueError exception if None returned, just copy passed value
                if param.target is not None:
                    newValue = getattr(self, param.target.__name__)(value)
                    setattr(options, name, newValue or value)
            except ValueError, e:
                self.exit("Invalid value for %s: %s" % (name, e))
Ejemplo n.º 40
0
class TestSite(object):
    def setup(self):

        self.manager = Manager(port=8000)

        #self.manager.addClass(Site, "lna", {"name": "LNA",
        #                                    "latitude": "-22 32 03",
        #                                    "longitude": "-45 34 57",
        #                                    "altitude": "1896"}

        self.manager.addClass(
            Site, "lna", {
                "name": "UFSC",
                "latitude": "-27 36 13 ",
                "longitude": "-48 31 20",
                "altitude": "20"
            })

    def teardown(self):
        self.manager.shutdown()

    def test_times(self):

        site = self.manager.getProxy(Site)

        try:
            print()
            print("local:", site.localtime())
            print("UT   :", site.ut())
            print("JD   :", site.JD())
            print("MJD  :", site.MJD())
            print("LST  :", site.LST())
            print("GST  :", site.GST())
        except Exception as e:
            printException(e)

    def test_sidereal_clock(self):

        return True

        site = self.manager.getProxy(Site)

        times = []
        real_times = []

        for i in range(100):
            t0 = time.clock()
            t0_r = time.time()
            print("\r%s" % site.LST(), end=' ')
            times.append(time.clock() - t0)
            real_times.append(time.time() - t0_r)

        print()
        print(sum(times) / len(times))
        print(sum(real_times) / len(real_times))

    def test_astros(self):

        site = self.manager.getProxy(Site)

        try:
            print()
            print("local   :", site.localtime())
            print()
            print("moonrise  :", site.moonrise())
            print("moonset   :", site.moonset())
            print("moon pos  :", site.moonpos())
            print("moon phase:", site.moonphase())
            print()
            print("sunrise:", site.sunrise())
            print("sunset :", site.sunset())
            print("sun pos:", site.sunpos())
            print()

            sunset_twilight_begin = site.sunset_twilight_begin()
            sunset_twilight_end = site.sunset_twilight_end()
            sunset_twilight_duration = relativedelta(sunset_twilight_end,
                                                     sunset_twilight_begin)

            sunrise_twilight_begin = site.sunrise_twilight_begin()
            sunrise_twilight_end = site.sunrise_twilight_end()
            sunrise_twilight_duration = relativedelta(sunrise_twilight_end,
                                                      sunrise_twilight_begin)

            print("next sunset twilight begins at:", sunset_twilight_begin)
            print("next sunset twilight ends   at:", sunset_twilight_end)
            print("sunset twilight duration      :", sunset_twilight_duration)
            print()
            print("next sunrise twilight begins at:", sunrise_twilight_begin)
            print("next sunrise twilight ends   at:", sunrise_twilight_end)
            print("sunrise twilight duration      :",
                  sunrise_twilight_duration)

        except Exception as e:
            printException(e)
Ejemplo n.º 41
0
def doEventClbk (result):
    print result

m.eventDone += doEventClbk
m.doEvent()

# exception
try:
    m.doRaise()
except MinimoException, e:
    printException(e)

# static method
print m.doStatic()

# class method
print m.doClass()

# configuration
print "option1 =>", m['option1']
print "option2 =>", m['option2']

m += {"option1": "new value 1",
      "option2": "new value 2"}

print "option1 =>", m['option1']
print "option2 =>", m['option2']

# bye
manager.shutdown()
Ejemplo n.º 42
0
class TestAutofocus(object):
    def setup(self):

        self.manager = Manager(port=8000)

        # fake
        self.manager.addClass(FakeCamera, "fake")
        self.manager.addClass(Camera, "cam", {"driver": "/FakeCamera/fake"})

        self.manager.addClass(FakeFocuser, "fake")
        self.manager.addClass(Focuser, "focus", {"driver": "/FakeFocuser/0"})

        # real
        #self.manager.addClass(SBIG, "sbig", {"device": "USB"})
        #self.manager.addClass(Camera, "cam", {"driver": "/SBIG/0"})

        #self.manager.addClass(OptecTCFS, "optec", {"device": "/dev/ttyS0"})
        #self.manager.addClass(Focuser, "focus", {"driver": "/OptecTCFS/0"})

        #self.manager.addClass(Autofocus, "autofocus", {"camera" : "200.131.64.203:7666/Camera/0",
        #                                               "focuser": "******"})

        self.manager.addClass(Autofocus, "autofocus", {
            "camera": "/Camera/0",
            "focuser": "******"
        })

        @callback(self.manager)
        def exposeBeginClbk(exp_time):
            print time.time(), "Expose begin for %.3f s." % exp_time

        @callback(self.manager)
        def exposeCompleteClbk():
            print time.time(), "Expose complete."

        @callback(self.manager)
        def readoutBeginClbk(frame):
            print time.time(), "Readout begin for %s." % frame

        @callback(self.manager)
        def readoutCompleteClbk(frame):
            print time.time(), "Readout complete for %s." % frame

        @callback(self.manager)
        def abortCompleteClbk():
            print time.time(), "Abort complete."

        cam = self.manager.getProxy(Camera)
        cam.exposeBegin += exposeBeginClbk
        cam.exposeComplete += exposeCompleteClbk
        cam.readoutBegin += readoutBeginClbk
        cam.readoutComplete += readoutCompleteClbk
        cam.abortComplete += abortCompleteClbk

    def teardown(self):
        self.manager.shutdown()
        del self.manager

    def test_focus(self):

        autofocus = self.manager.getProxy(Autofocus)
        best_focus = autofocus.focus(debug="/home/henrique/ph/basic-run")