Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
    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(Meade, "meade", {"device": "/dev/ttyS0"})

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

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

        @callback(self.manager)
        def parkCompleteClbk(position):
            print time.time(), "Park complete. position=%s" % str(position)

        @callback(self.manager)
        def unparkCompleteClbk(position):
            print time.time(), "Unpark complete. position=%s" % str(position)

        self.m = self.manager.getProxy(Meade)
        self.m.slewBegin    += slewBeginClbk
        self.m.slewComplete += slewCompleteClbk
        self.m.parkComplete += parkCompleteClbk
        self.m.unparkComplete += unparkCompleteClbk
Exemplo n.º 3
0
    def startup(self):

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

        # system config
        self.config = SystemConfig.fromFile(self.options.config_file,
                                            self.options.use_global)

        # manager
        if not self.options.dry:
            log.info("Starting system.")
            log.info("Chimera version: %s" % find_dev_version()
                     or _chimera_version_)
            log.info("Chimera prefix: %s" % ChimeraPath.root())

            try:
                self.manager = Manager(**self.config.chimera)
            except ChimeraException, 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()))
            if self.options.use_global:
                log.info("Chimera: reading configuration from %s" %
                         SYSTEM_CONFIG_DEFAULT_GLOBAL)
            log.info("Chimera: reading configuration from %s" %
                     os.path.realpath(self.options.config_file))
Exemplo n.º 4
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)
Exemplo 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)
Exemplo n.º 6
0
    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()
Exemplo n.º 7
0
    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"
        })
Exemplo n.º 8
0
    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()
Exemplo n.º 9
0
    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()
Exemplo n.º 10
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()
Exemplo n.º 11
0
    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
Exemplo n.º 12
0
    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"})
Exemplo n.º 13
0
    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 = "******"
Exemplo n.º 14
0
    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()
Exemplo n.º 15
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()
Exemplo n.º 16
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)
Exemplo n.º 17
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)
Exemplo n.º 18
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()
Exemplo n.º 19
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()
Exemplo n.º 20
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)
Exemplo n.º 21
0
    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 = "******"
Exemplo n.º 22
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()
Exemplo n.º 23
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()
Exemplo n.º 24
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()
Exemplo n.º 25
0
    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"})
Exemplo n.º 26
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()
Exemplo n.º 27
0
	def setJD(self,options):
		'''
		Configure time domain by specifing a julian day. It will use information on exposure time to build time bins that will be 
		filled when selecting targets.
		'''
		
		sysconfig = SystemConfig.fromFile(options.config)

		manager = Manager()
		site = manager.getProxy(sysconfig.sites[0])
		jd = options.JD
		
		if not jd:
			jd = np.floor(site.JD())+0.5
		
		lat = np.array([float(tt) / 60.**i for i,tt in enumerate(str(site['latitude']).split(':'))])
		lat[1:] *= lat[0]/np.abs(lat[0])
		sitelat = np.sum(lat)
		long = np.array([float(tt) / 60.**i for i,tt in enumerate(str(site['longitude']).split(':'))])
		long[1:] *= long[0]/np.abs(long[0])
		sitelong = abs(np.sum(long)/360*24.)
		
		print site['latitude'],'->',sitelat
		print site['longitude'],'->',sitelong
		
		nightstart = _skysub.jd_sun_alt(self.sunMaxAlt, jd, sitelat, sitelong)
		nightend   = _skysub.jd_sun_alt(self.sunMaxAlt, jd+0.5, sitelat, sitelong)
		print('Nigh Start @JD= %.3f # Night End @JD = %.3f'%(nightstart,nightend))

		
		# Creating a 1 minute time bin
		tbin = self.tbin

		self.obsTimeBins = np.arange(nightstart,nightend+tbin,tbin)
		self.obsTimeMask = np.zeros(len(self.obsTimeBins))
		self.obsTimeMask[-1] = 1.0
		
		# Marking filled bins
		
		session = Session()
		
		scheduled = session.query(Program)
		
		for target in scheduled:
			tindex = np.abs(self.obsTimeBins - 2400000.5 - target.slewAt).argmin()
			self.obsTimeMask[tindex] = 1.0

		self.isJD = True
Exemplo n.º 28
0
    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"])
Exemplo n.º 29
0
    def __start__(self):

        self.sysconfig = SystemConfig.fromFile(self['chimera_config'])

        self.localManager = Manager(self.sysconfig.chimera["host"], 9090)

        self.offsets = dict(
            zip(self["focus_filters"].split(),
                [int(x) for x in self["focus_difference"].split()]))

        @callback(self.localManager)
        def filterChange(newFilter, oldFilter):
            self.log.debug("Moved from %s to %s" % (oldFilter, newFilter))
            diff = self.offsets[newFilter] - self.offsets[oldFilter]
            if diff < 0:
                diff = int(ceil(abs(diff)))
                self.log.debug("Moving focuser %i steps IN due filter change" %
                               diff)
                self.focuser.moveIn(diff)
            elif diff > 0:
                diff = int(ceil(abs(diff)))
                self.log.debug(
                    "Moving focuser %i steps OUT due filter change" % diff)
                self.focuser.moveOut(diff)

        self.filterwheel = self.getManager().getProxy(self["filterwheel"])
        self.filterwheel.filterChange += filterChange
        self.focuser = self.getManager().getProxy(self["focuser"])
Exemplo n.º 30
0
    def __start__(self):

        # Reset data
        self._data = dict()
        self.setHz(1. / self["query_delay"])

        self.localManager = Manager(self["local_manager_ip"],
                                    self["local_manager_port"])

        # Define callbacks for scheduler actions
        if self["schedulers"] is not None:

            self.CallBacks = []

            for sched in self["schedulers"]:
                self.schedname = sched.split('/')[-1]
                self._data['scheduler_msg_%s' % self.schedname] = dict()
                self._data['scheduler_state_%s' % self.schedname] = dict()

                self.CallBacks.append(
                    SchedCallbacks(self.localManager, self.schedname,
                                   self._data))

                self.getManager().getProxy(
                    sched
                ).actionBegin += self.CallBacks[-1].SchedActionBeginClbk
                self.getManager().getProxy(
                    sched
                ).stateChanged += self.CallBacks[-1].SchedStateChangedClbk

            self.update_schedulers()

        self.control()
Exemplo n.º 31
0
    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()
Exemplo n.º 32
0
    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()
Exemplo n.º 33
0
    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()
Exemplo n.º 34
0
class ChimeraGUI:

    def __init__(self):

        self.setupGUI()
        self.setupChimera()
        self.setupViews()

    def setupGUI(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file(
            os.path.join(os.path.dirname(__file__), "chimera.xml"))

        self.mainWindow = self.builder.get_object("mainWindow")
        self.builder.connect_signals({"window_destroy": self.chimera_quit,
                                      "chimera_connect_handler": self.chimera_connect_handler,
                                      "chimera_quit_handler": self.chimera_quit})

        self.dock = gdl.Dock()
        self.dock_layout = gdl.DockLayout()

        if os.path.exists("chimera_gui_layout.xml"):
            self.dock_layout.load_from_file("chimera_gui_layout.xml")
            self.dock_layout.load_layout("_-default__")

        self.builder.get_object("main_area").pack_end(self.dock)

        self.mainWindow.set_default_size(640, 480)
        self.mainWindow.show_all()

    def chimera_quit(self, *arga, **kwargs):
        # self.dock_layout.save_to_file("chimera_gui_layout.xml")
        gtk.main_quit()

    def chimera_connect_handler(self, action):
        threading.Thread(target=self.showConnectDialog).start()

    def showConnectDialog(self):
        dialog = self.builder.get_object("chimera_connect_dialog")
        response = dialog.run()
        dialog.hide()
        dialog.destroy()

    def setupChimera(self):
        try:
            self.sysconfig = SystemConfig.fromFile(
                SYSTEM_CONFIG_DEFAULT_FILENAME)
        except IOError, e:
            logging.exception(e)
            logging.error(
                "There was a problem reading your configuration file. (%s)" % e)
            return False

        self.localManager = Manager(
            host=self.sysconfig.chimera["host"], port=9000)
        self.manager = ManagerLocator.locate(
            self.sysconfig.chimera["host"], self.sysconfig.chimera["port"])
Exemplo n.º 35
0
    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 = "******"
Exemplo n.º 36
0
    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()
Exemplo n.º 37
0
    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 = "******"
Exemplo n.º 38
0
    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")
Exemplo n.º 39
0
    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()
Exemplo n.º 40
0
    def _startSystem(self, options, needRemoteManager=True):

        self.localManager = Manager(getattr(options, 'host', 'localhost'),
                                    getattr(options, 'port', 9000),
                                    local=True)

        # if we need a remote Manager, check if it is up, if not, start it
        if needRemoteManager:
            try:
                self._remoteManager = ManagerLocator.locate()
                self._remoteManager.ping()

            except ManagerNotFoundException:

                # FIXME: better way to start Chimera
                site = SiteController(wait=False)
                site.startup()

                self._keepRemoteManager = False

                self._remoteManager = ManagerLocator.locate()
                self._remoteManager.ping()
Exemplo n.º 41
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, e:
            assert e.cause != None
            log.exception("wow, something wrong")
Exemplo n.º 42
0
    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"])
Exemplo n.º 43
0
    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
Exemplo n.º 44
0
    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"})
Exemplo n.º 45
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, e:
            assert e.cause != None
            log.exception("wow, something wrong")
Exemplo n.º 46
0
    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()
Exemplo n.º 47
0
    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()
Exemplo n.º 48
0
    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")
Exemplo n.º 49
0
    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()
Exemplo n.º 50
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()
Exemplo n.º 51
0
    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()
Exemplo n.º 52
0
 def setup (self):
     self.manager = Manager()
Exemplo n.º 53
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)
Exemplo n.º 54
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))
Exemplo n.º 55
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()
Exemplo n.º 56
0
import logging
logging.getLogger("chimera").setLevel(logging.INFO)

from chimera.core.manager import Manager

from minimo import Minimo

manager = Manager(host='localhost', port=8000)
manager.addClass(Minimo, "m", config={"option1": "blah blah"}, start=True)
manager.wait()

Exemplo n.º 57
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()
Exemplo n.º 58
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
Exemplo n.º 59
0
import logging
logging.getLogger("chimera").setLevel(logging.WARNING)

from chimera.core.manager       import Manager
from chimera.core.callback      import callback
from chimera.core.exceptions    import printException

from minimo import Minimo, MinimoException

manager = Manager()

m = manager.getProxy(Minimo, "m", host='localhost', port=8000)

# method
print m.doMethod("bar")

# event

@callback(manager)
def doEventClbk (result):
    print result

m.eventDone += doEventClbk
m.doEvent()

# exception
try:
    m.doRaise()
except MinimoException, e:
    printException(e)
Exemplo n.º 60
0
from chimera.core.main     import chimera
from chimera.core.proxy    import Proxy
from chimera.core.manager  import Manager

# our example object
from minimo import Minimo


# create a new manager (default host (localhost), defaulr port 7666 or try next 4 from default)
manager = Manager()

#
# 1. Adding objects and getting a proxy
# 

# just add a min Minimoescope class (returns a valid proxy)
minimo = manager.addClass(Minimo, "min", start=True)

# synchronous "doFoo"
minimo.doFoo ("ra dec")

#
# 2. There are other ways to get proxy
#

# from manager (this ensure that the object exists on the manager, see ChimeraProxy below)
minimo = manager.getProxy ("/Minimo/min")
minimo.doFoo ("ra dec")

# if you don't know the name of the instance no problem, pass an index starting with 0