Exemplo n.º 1
0
def set_array_frec():
    client = PySimpleClient()
    master = client.getComponent("CONTROL/MASTER")
    arrayList = master.getAutomaticArrayComponents() + master.getManualArrayComponents()
    for array in arrayList:
        master.destroyArray(array.ComponentName)
    arrayList = []    
    antennas = master.getAvailableAntennas()
    master.createManualArray(antennas)
    arrayList = master.getAutomaticArrayComponents() +  master.getManualArrayComponents()
    if ( arrayList != 1 ):
        if( len(arrayList) == 0):
            print "Could not create an array!!"
            client.releaseComponent("CONTROL/MASTER")
            sys.exit(0)
        else:
            print "Could not destroy previosly arrays and create a new fresh array!"
            client.releaseComponent("CONTROL/MASTER")
            sys.exist(0)
    currentArray = client.getComponent(arrayList[0].ComponentName)
    client.releaseComponent("CONTROL/MASTER")
    setArrayName(currentArray.getArrayName())
    array = getArray()
    tp = array.getTotalPowerObservingMode()
    return tp
Exemplo n.º 2
0
 def __init__(self):
     try:
         #This stuff is only for get the antennas of a manual array
         from Acspy.Clients.SimpleClient import PySimpleClient
         c = PySimpleClient()
         master = c.getComponent('CONTROL/MASTER')
         arrayname  =  master.getManualArrays()
         array = c.getComponent('CONTROL/'+arrayname[0])
         self.antennalist = array.getAntennas()
         self.logger = getLogger()
         del master
         del array
         c.disconnect()
     except Exception, e:
         print e
Exemplo n.º 3
0
class TestStorageMethods(unittest.TestCase):
    def test_full(self):
        self.client = PySimpleClient()
        self.storage = self.client.getComponent("STORAGE")

        self.storage.clearAllData()

        targets = []
        images = []
        for i in range(10):
            targets.append(TYPES.Target(i, TYPES.Position(10.0, 45.0), 2))
            image = bytearray()
            for j in range(1000000):
                image.append(j % 256)
            images.append(bytes(image))
        proposal = TYPES.Proposal(0, targets, 0)
        self.storage.storeObservation(proposal, images)

        id = self.storage.getNextValidId()
        print "ID", id
        self.assertEqual(1, id, "Checking ID")

        result = self.storage.getObservation(0)
        self.assertEqual(10, len(result), "Number of observations")

        self.storage.clearAllData()

        self.client.releaseComponent(self.storage._get_name())
Exemplo n.º 4
0
class TestStorageMethods(unittest.TestCase):
    def test_full(self):
        self.client = PySimpleClient()
        self.storage = self.client.getComponent("STORAGE")

        self.storage.clearAllData()

        targets = []
        images = []
        for i in range(10):
            targets.append(TYPES.Target(i, TYPES.Position(10.0, 45.0), 2))
            image = bytearray()
            for j in range(1000000):
                image.append(j % 256)
            images.append(bytes(image))
        proposal = TYPES.Proposal(0, targets, 0)
        self.storage.storeObservation(proposal, images)

        id = self.storage.getNextValidId()
        print "ID", id
        self.assertEqual(1, id, "Checking ID")

        result = self.storage.getObservation(0)
        self.assertEqual(10, len(result), "Number of observations")

        self.storage.clearAllData()

        self.client.releaseComponent(self.storage._get_name())
Exemplo n.º 5
0
class MoreComponentUtilTest(unittest.TestCase):
    """
    Test the integration of the component utilities
    """
    def setUp(self):
        self._my_acs_client = PySimpleClient()
        logger = self._my_acs_client.getLogger()
        logger.setLevel(logging.WARNING)

    def tearDown(self):
        self._my_acs_client.disconnect()

    def test_is_characteristic_component(self):
        my_component = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_COMPONENT", True)
        self.assertTrue(
            component_util.is_characteristic_component(my_component))
        # Now check a component that is not characteristic
        my_component2 = self._my_acs_client.getComponent("TIMER1", True)
        self.assertFalse(
            component_util.is_characteristic_component(my_component2))

    def test_is_python_char_component(self):
        my_component = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_PYTHON", True)
        self.assertTrue(component_util.is_python_char_component(my_component))
        # Now check a component that is not characteristic

        my_component2 = self._my_acs_client.getComponent("TIMER1", True)

        self.assertRaises(AttributeError,
                          component_util.is_python_char_component,
                          my_component2)

        my_component3 = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_COMPONENT", True)

        self.assertFalse(
            component_util.is_python_char_component(my_component3))

    def test_is_a_property_recorder_component(self):
        my_component = self._my_acs_client.getComponent(
            "propertyRecorder1", True)
        self.assertTrue(
            component_util.is_a_property_recorder_component(my_component))
        # Now check a component that is not characteristic
        my_component2 = self._my_acs_client.getComponent("TIMER1", True)
        self.assertFalse(
            component_util.is_a_property_recorder_component(my_component2))

    def test_is_component_state_ok(self):
        my_component = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_COMPONENT", True)
        self.assertTrue(component_util.is_component_state_ok(my_component))
Exemplo n.º 6
0
 def subsystemsOffline(self, subsystem):
     from Acspy.Clients.SimpleClient import PySimpleClient
     client = PySimpleClient()
     mcI = client._ContainerServices__importComponentStubs(comp_type="IDL:alma/ACS/MasterComponent:1.0")
     subsystem = client.getComponent(subsystem)
     subsystem.doTransition(mcI.SUBSYSEVENT_SHUTDOWNPASS1)
     (state, flag) = self.__waitForSubsystemState(subsystem._get_currentStateHierarchy(), "AVAILABLE.OFFLINE.PRESHUTDOWN", 300)
     if flag is False:
         return (state, flag)
     subsystem.doTransition(mcI.SUBSYSEVENT_SHUTDOWNPASS2)
     (state, flag) =  self.__waitForSubsystemState(subsystem._get_currentStateHierarchy(), "AVAILABLE.OFFLINE.SHUTDOWN", 300)
     if flag is False:
         return (state, flag)
     return (state, flag)
Exemplo n.º 7
0
 def checkOnline(self):
     masters_states = []
     from Acspy.Clients.SimpleClient import PySimpleClient
     masters_comps = self.parser.get_masters_from_execconfig()
     for master in masters_comps:
         client = PySimpleClient()
         subsystem = client.getComponent(master)
         currentStateHierarchy = subsystem._get_currentStateHierarchy()
         state = currentStateHierarchy.get_sync()
         #if (state[0][1] is 'OPERATIONAL'):
         masters_states.append([master,state[0][1]])
     for state in masters_states:
         if(state[1] == 'OPERATIONAL'):
             print state
             pass
         else:
             return state
     return "OK"
Exemplo n.º 8
0
def mostRecentAsdm(date=None) :
    if date == None :
        date='%4.2d-%2.2d-%2.2d'%(time.gmtime()[0], time.gmtime()[1], time.gmtime()[2])
    client = PySimpleClient()
    archConn = client.getComponent('ARCHIVE_CONNECTION')
    archOp = archConn.getOperational('XMLQueryTest')
    uids = archOp.queryRecent('ASDM',date+'T00:00:00.000')
    asdm_name=[]
    for uid in uids:
        result = archOp.retrieveDirty(uid)
        dataSet = ArchivedAsdm(result.xmlString)
        dateOfCreation =  dataSet.getDateOfCreation()
        if dataSet.isAsdm() & (dateOfCreation==date):
            asdm_name.append("%s \t%s" % (dateOfCreation,uid))
    asdm_name.sort()
    client.releaseComponent('ARCHIVE_CONNECTION')
    client.disconnect()
    if len(asdm_name) == 0 :
        print 'there are no asdms for %s' % date
        return None
    else :
        return asdm_name[-1].split('\t')[1]
Exemplo n.º 9
0
def mostRecentAsdm(date = None):
    '''
    Get the most recent Asdm, given a date. 
    If the date is None, it takes the  actual hour.

    return asdm or None
    '''
    from Acspy.Clients.SimpleClient import PySimpleClient
    from ArchivedAsdm import ArchivedAsdm
    if date == None :
        date_T = '%4.2d-%2.2d-%2.2dT00:00:00.000' % (gmtime()[0] , gmtime()[1] , gmtime()[2])
        date  = '%4.2d-%2.2d-%2.2d'% (gmtime()[0] , gmtime()[1] , gmtime()[2]) 
    else:
        date_T = '%4.2d-%2.2d-%2.2dT%2.2d:00:00.00' % (date[0] , date[1] , date[2] , date[3])
        date  = '%4.2d-%2.2d-%2.2d'% (date[0] , date[1] , date[2]) 
    client = PySimpleClient()
    archConn = client.getComponent('ARCHIVE_CONNECTION')
    archOp = archConn.getOperational('XMLQueryTest')
    uids = archOp.queryRecent('ASDM' , date_T)
    print "Connection entablish with archive ..."
    asdm_name = []
    for uid in uids:
        print "Checking date of " +str(uid),
        result = archOp.retrieveDirty(uid)
        dataSet = ArchivedAsdm(result.xmlString)
        dateOfCreation =  dataSet.getDateOfCreation()
        print "  created: "+str(dataSet.getDateTimeOfCreation()),
        if dataSet.isAsdm() & (dateOfCreation==date):
            asdm_name.append("%s \t%s" % (dataSet.getDateTimeOfCreation() , uid))
            print " --> is an asdm!",
        print ""
    asdm_name.sort()
    client.releaseComponent('ARCHIVE_CONNECTION')
    client.disconnect()
    if len(asdm_name) == 0 :
        print 'There are no asdms for %s' % date
        return None
    else :
        return asdm_name[-1].split('\t')[1]
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307  USA
#

from Acspy.Clients.SimpleClient import PySimpleClient
from sys import argv
from sys import exit
from TMCDB import MonitorCollector
from TMCDB import propertySerailNumber
import MonitorErrImpl
import MonitorErr

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

# Test Case 1: Register collocated device with multiple serial non registrable
#              Test EH(registerCollocatedMonitoredDeviceWithMultipleSerial): RegisteringDeviceProblem"
print "Test Case 1: Register collocated device with multiple serial non registrable"
print "--------------------------------------------"
try:
    psns = [
        propertySerailNumber('asds', ['12124']),
        propertySerailNumber('sdfsfs', ['3432535'])
    ]
    mc.registerCollocatedMonitoredDeviceWithMultipleSerial('FAKE_DEVICE', psns)
    print " TEST FAIL: FAKE_DEVICE registered"
except MonitorErr.RegisteringDeviceProblemEx, _ex:
    ex = MonitorErrImpl.RegisteringDeviceProblemExImpl(exception=_ex)
    ex.Print()
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA 02111-1307  USA
#

from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from sys                        import exit
from TMCDB                      import MonitorCollector
from TMCDB                      import propertySerailNumber
import MonitorErrImpl
import MonitorErr

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

# Test Case 1: Register collocated device with multiple serial non registrable
#              Test EH(registerCollocatedMonitoredDeviceWithMultipleSerial): RegisteringDeviceProblem"
print "Test Case 1: Register collocated device with multiple serial non registrable"
print "--------------------------------------------"
try:
    psns =[propertySerailNumber('asds', ['12124']),propertySerailNumber('sdfsfs', ['3432535'])]
    mc.registerCollocatedMonitoredDeviceWithMultipleSerial('FAKE_DEVICE', psns)
    print " TEST FAIL: FAKE_DEVICE registered"
except MonitorErr.RegisteringDeviceProblemEx, _ex:
    ex = MonitorErrImpl.RegisteringDeviceProblemExImpl(exception=_ex)
    ex.Print();
    print " TEST SUCCESS: FAKE_DEVICE not registered"

# Test Case 2: Register collocated device with multiple serial when property does not exist
Exemplo n.º 12
0
    catch it and call processEvent(...) which will hopefully have been overriden.
    '''
    global count

    count = count + 1
    if count < 5:
        for data in someParam:
            print "TIME STAMP: ", data.sampTime
            print "VALUE: ", data.sampVal.value()
    print "Received: ", count
    return
#------------------------------------------------------------------------------
if __name__ == "__main__":

    client = PySimpleClient()
    samp = client.getComponent(argv[1])
    sampObj = samp.initSampObj("LAMP1", "brightness", 1000000, 10000000)

    print "acssampConsumer entering ..."
    g = Consumer("NC_LAMP1_brightness_1000000_10000000")
    g.addSubscription("SampDataBlockSeq", handlerFunction=dataHandler)
    g.consumerReady()

    sampObj.start()
    print " ACS sampling started"
    sleep(5)
    sampObj.suspend()
    print "ACS sampling suspended"
    
    sleep(5)
    sampObj.resume()
Exemplo n.º 13
0
from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from sys                        import exit
from sys                        import stdout
from TMCDB                      import MonitorCollector
from TMCDB                      import propertySerailNumber
from omniORB                    import any
import MonitorErrImpl
import MonitorErr
import time

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

try:
    tc =   simpleClient.getComponent('MC_TEST_ALARMS_COMPONENT')
    psns =[propertySerailNumber('doubleROProp',    ['1' ]),
           propertySerailNumber('floatROProp',     ['2' ]),
           propertySerailNumber('longROProp',      ['3' ]),
           propertySerailNumber('uLongROProp',     ['4' ]),
           propertySerailNumber('longLongROProp',  ['5' ]),
           propertySerailNumber('uLongLongROProp', ['6' ]),
           propertySerailNumber('booleanROProp',   ['7' ]),
           propertySerailNumber('doubleSeqROProp', ['8' ]),
           propertySerailNumber('floatSeqROProp',  ['9' ]),
           propertySerailNumber('longSeqROProp',   ['10']),
           propertySerailNumber('uLongSeqROProp',  ['11']),
           propertySerailNumber('booleanSeqROProp',['12']),
Exemplo n.º 14
0
#!/usr/bin/env python
from Acspy.Clients.SimpleClient import PySimpleClient

remoteComponent="MOUNT2_LOOP"

#Make an instance of the PySimpleClient
simpleClient = PySimpleClient()  

#Get the MOUNT1 Mount device
mount  = simpleClient.getComponent(remoteComponent)  

#Get the actAz property
actAzProperty = mount._get_actAz()

#Get the current value of the property
(azm, compl) = actAzProperty.get_sync()  
print "MOUNT actual azimuth: ", azm

#Cleanly disconnect
simpleClient.releaseComponent(remoteComponent)
simpleClient.disconnect()
Exemplo n.º 15
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307  USA
#
# @(#) $Id: acsncTestConSup.py,v 1.6 2006/03/08 17:50:44 dfugate Exp $
"""
"""

from Acspy.Common.Log import getLogger
from Acspy.Clients.SimpleClient import PySimpleClient
from sys import argv
from time import sleep
import threading

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

# Get logger
logger = getLogger()

name = "SUP_MTH_COMP_1"
supplier = simpleClient.getComponent(name)
logger.logAlert("Calling supplier.sendEvents")
supplier.sendEvents(10)
logger.logAlert("Waiting 10 seconds ...")
sleep(15)
logger.logAlert("Releasing component %s" % (name))
simpleClient.releaseComponent(name)
sleep(10)

simpleClient.disconnect()
Exemplo n.º 16
0
Tests a callback void method.
'''
from sys import argv
from time import sleep
from Acspy.Clients.SimpleClient import PySimpleClient
from Acspy.Common.Callbacks     import CBvoid
from ACS import CBDescIn

compName = argv[1]
compMethod = argv[2]

print "Parameters to this generic test script are:", argv[1:]

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()
comp = simpleClient.getComponent(compName)

myCB = CBvoid()
myCorbaCB = simpleClient.activateOffShoot(myCB)
myDescIn = CBDescIn(0L, 0L, 0L)

joe = eval("comp." + compMethod + "(myCorbaCB, myDescIn)")
print "Method executed...now just waiting on CB status"

for i in range(0, 50):
    if myCB.status == 'DONE':
        print "The callback has finished!"
        break
    else:
        sleep(1)
    
Exemplo n.º 17
0
    '''
    global count
    
    if count < 5:
        count = count + 1
        LOGGER.logInfo('The temperature difference is ' + str(someParam.absoluteDiff))
        
    return
#------------------------------------------------------------------------------
if __name__ == "__main__":
    
    print 'Making sure there is a fridge available...'
    
    #Start publishing events through a C++ Supplier
    simpleClient = PySimpleClient()
    aFridge = simpleClient.getComponent("FRIDGE1")
    aFridge.on()

    #Create a FridgeConsumer
    simpleClient.getLogger().logInfo('Creating FridgeConsumer')
    g = Consumer(FRIDGE.CHANNELNAME_FRIDGE)

    #Subscribe to temperatureDataBlockEvent events and register this handler to process
    #those events
    g.addSubscription(FRIDGE.temperatureDataBlockEvent, fridgeDataHandler)

    #Let the Notification Service know we are ready to start processing events.
    g.consumerReady()

    #After five events have been received, disconnect from the channel
    simpleClient.getLogger().logInfo("Waiting for events . . .")
Exemplo n.º 18
0
#!/usr/bin/env python
from Acspy.Clients.SimpleClient import PySimpleClient

remoteComponent = "MOUNT2_LOOP"

#Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

#Get the MOUNT1 Mount device
mount = simpleClient.getComponent(remoteComponent)

#Get the actAz property
actAzProperty = mount._get_actAz()

#Get the current value of the property
(azm, compl) = actAzProperty.get_sync()
print "MOUNT actual azimuth: ", azm

#Cleanly disconnect
simpleClient.releaseComponent(remoteComponent)
simpleClient.disconnect()
Exemplo n.º 19
0
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307  USA
#
# @(#) $Id: javaSupplierComponent.py,v 1.1 2008/05/23 12:53:45 eallaert Exp $
"""
"""
from Acspy.Clients.SimpleClient import PySimpleClient
from time import sleep
import sys

simpleClient = PySimpleClient()
sleep(5)

print "Getting the Supplier"
sys.stdout.flush()
mySupplierComp = simpleClient.getComponent("SUPPLIERCOMP1")

print "Sending events"
sys.stdout.flush()
for i in range(50):
    mySupplierComp.sendEvents(1)
    sleep(1)

simpleClient.releaseComponent("SUPPLIERCOMP1")

print "Finished sending events"
sys.stdout.flush()
Exemplo n.º 20
0
# Import the acspy.PySimpleClient class
import time
from Acspy.Clients.SimpleClient import PySimpleClient

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

# Print information about the available COBs

# Do something on a device.
simpleClient.getLogger().logInfo(
    "We can directly manipulate a device once we get it, which is easy.")
try:
    # Get the standard MOUNT1 Mount device
    ws = simpleClient.getComponent("MONITOR_COLLECTOR")

    # Get the humidity
    ws.registerMonitoredDevice("SensorTag", "1")
    # Print value
    ws.startMonitoring("SensorTag")
    raw_input("##################Press enter to quit#########################")
    # Release it
    simpleClient.releaseComponent("MONITOR_COLLECTOR")

except Exception, e:
    simpleClient.getLogger().logCritical(
        "Sorry, I expected there to be a Mount in the system and there isn't.")
    simpleClient.getLogger().logDebug("The exception was:" + str(e))
simpleClient.disconnect()
print "The end __oOo__"
Exemplo n.º 21
0
# local monitoring component prefix
COMPONENT_PREFIX_LOCAL = 'ACS:L'
# name of the queue used for monitoring
QUEUE_NAME = 'ACS:MonitorQueue'
# name of the queue used for polling
POLLING_QUEUE = 'ACS:PollingQueue'
# name of the queue used for querying from db
MONGO_QUEUE = 'ACS:MongoQueue'
# prefix of the dicts used for comparing the values in the db
DICT_SET_NAME = 'ACS:DictSet'
# the monitoring dictionary that contains the references of all active monitors
MONITOR_DICT = 'ACS:Monitor:Dict'

# Create a client and the ArraySupervisor component
client = PySimpleClient()
supervisor = client.getComponent("ArraySupervisor")

# Local property monitor dict
local_queue = Counter()
# dict used for storing active polling threads
polling_threads = dict()
# dict for storing references to the components
dict_of_components = dict()

# get the components
TEST_JAVA_T1 = client.getComponent("TEST_JAVA_T1")
TEST_JAVA_T2 = client.getComponent("TEST_JAVA_T2")
# you can add more here

# add the components to the dict
dict_of_components[TEST_JAVA_T1.name] = TEST_JAVA_T1
Exemplo n.º 22
0
"""
"""

from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from time                       import sleep

# Get input parameters
test_num = int(argv[1])
comp_name = str(argv[2])
ch_name = str(argv[3])

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()
consumer = simpleClient.getComponent(comp_name)

if test_num == 1:
    autoconnect = str(argv[4]) == 'autoreconnect'
    sleep_time = int(argv[5])
    counter_lower_than = int(argv[6])
    counter_greater_than = int(argv[7])
    consumer.execTest(ch_name, autoconnect)
    sleep(sleep_time)
    if counter_lower_than > 0:
        consumer.checkCounterLowerThan(counter_lower_than)
    if counter_greater_than > 0:
        consumer.checkCounterGreaterThan(counter_greater_than)

elif test_num == 2:
    consumer.execTestResumeSuspend(ch_name)
Exemplo n.º 23
0
class MockSched():
    # ------------------------------------------------------------------
    #
    # ------------------------------------------------------------------
    def __init__(self, site_type):
        self.log = my_log(title=__name__)
        self.log.info([['y', " - MockSched - "], ['g', site_type]])

        self.site_type = site_type
        self.tel_ids = tel_ids[site_type]

        self.debug = False
        self.expire = 86400  # one day

        self.cycle_blocks = []
        self.acs_blocks = dict()
        self.acs_blocks['sched_block'] = dict()
        self.acs_blocks['metadata'] = dict()

        self.active_sched_block = 0

        self.client = PySimpleClient()
        self.supervisor = self.client.getComponent("ArraySupervisor")
        # print 'got ArraySupervisor ............'

        self.n_sched_block = [5, 15]
        self.max_n_obs_block = 7 if self.site_type == "N" else 32
        self.max_n_obs_block = min(self.max_n_obs_block, len(self.tel_ids))
        # self.max_n_obs_block = len(self.tel_ids)
        self.loop_sleep = 4

        self.az_min_max = [0, 360]
        self.zen_min_max_tel = [0, 70]
        self.zen_min_max_pnt = [0, 20]

        rnd_seed = getTime()
        rnd_seed = 10987268332
        self.rnd_gen = Random(rnd_seed)

        print 'xxxxxxxxxxx'
        active = self.supervisor.listSchedulingBlocks()
        print '-----', active

        self.cancel_sched_blocks(active[0])
        print 'sleep...'
        sleep(10)
        print 'check...'
        print '---', len(
            self.supervisor.getSbOperationStatus(active[0]).ob_statuses
        ), '------------', self.supervisor.getSbOperationStatus(active[0]).ob_statuses
        print '---', self.supervisor.getSbOperationStatus(active[0]
                                                          ).ob_statuses[-1].status
        activeNow = self.supervisor.listSchedulingBlocks()
        print 'active now ....', activeNow

        # self.threads = []
        # run_event = threading.Event()
        # run_event.set()

        # t = threading.Thread(target=self.loop, args = (run_event,))
        # t.start()
        # self.threads.append(t)

        # try:
        #   while 1:
        #     sleep(.1)
        # except KeyboardInterrupt:
        #   run_event.clear()
        #   for t in self.threads:
        #     t.join()

        return

    # ------------------------------------------------------------------
    #
    # ------------------------------------------------------------------
    def cancel_sched_blocks(self, sched_blk_id):
        class MyVoid(ACS__POA.CBvoid):
            def working(self, completion, desc):
                # print "bbbbbbbbbb Callback working",sched_blk_id
                return

            def done(self, completion, desc):
                # print "bbbbbbbbbbbbb Callback done",sched_blk_id
                return

        desc = CBDescIn(0L, 0L, 0L)
        cb = MyVoid()

        self.log.info([['r', " ---- MockSched.cancel_sched_blocks() ... "],
                       ['g', sched_blk_id]])
        self.supervisor.cancelSchedulingBlock(
            sched_blk_id, self.client.activateOffShoot(cb), desc
        )
        self.log.info([['r', " ++++ MockSched.cancel_sched_blocks() ... "],
                       ['g', sched_blk_id]])

        return

    # ------------------------------------------------------------------
    #
    # ------------------------------------------------------------------
    def cancel_zombie_sched_blocks(self, sched_block_ids=None):
        if sched_block_ids is None:
            try:
                active = self.supervisor.listSchedulingBlocks()
            except Exception as e:
                self.log.debug([['b', "- Exception - MockSched.listSchedulingBlocks: "],
                                ['r', e]])
                active = []
            sched_block_ids = [
                x for x in active if x not in self.acs_blocks['sched_block']
            ]

        sched_block_ids = active

        if len(sched_block_ids) == 0:
            return

        self.log.info([['r', " - MockSched.cancel_zombie_sched_blocks() ..."],
                       ['y', sched_block_ids]])
        for sched_block_id_now in sched_block_ids:
            self.cancel_sched_blocks(sched_block_id_now)
            # t = threading.Thread(target=self.cancel_sched_blocks,args=(sched_block_id_now,))
            # t.start()
            # t.join()
            # self.threads.append(t)

        return

    # ------------------------------------------------------------------
    #
    # ------------------------------------------------------------------
    def init_block_cycle(self):
        self.log.info([['p', " - MockSched.init_block_cycle() ..."]])

        script_name = "guiACS_sched_blocks_script0"
        self.nCycles = [1, 5]
        self.n_sched_block = 40
        self.max_n_obs_block = 1
        self.obs_block_seconds = 20

        # cancel sched_blocks which should have expired
        # self.cancel_zombie_sched_blocks()

        # init local bookkeeping objects
        self.cycle_blocks = []
        self.acs_blocks = dict()
        self.acs_blocks['sched_block'] = dict()
        self.acs_blocks['metadata'] = dict()

        nCycles = self.rnd_gen.randint(self.nCycles[0], self.nCycles[1])
        for n_cycle_now in range(nCycles):
            base_name = str(getTime()) + "_"

            tel_ids = copy.deepcopy(self.tel_ids)
            n_tels = len(tel_ids)
            # n_sched_blocks = self.rnd_gen.randint(1, min(n_tels, self.n_sched_block))
            n_sched_blocks = self.n_sched_block

            # generate random target/pointing ids
            target_pos = dict()
            blockTrgs = dict()
            blockTrgPnt = dict()
            n_trgs = self.rnd_gen.randint(1, n_sched_blocks)
            for n_trg_try in range(n_sched_blocks):
                n_trg_now = self.rnd_gen.randint(0, n_trgs - 1)
                if n_trg_now not in blockTrgs:
                    blockTrgs[n_trg_now] = [n_trg_try]
                else:
                    blockTrgs[n_trg_now].append(n_trg_try)

                blockTrgPnt[n_trg_try] = {
                    "n_trg": n_trg_now,
                    "n_pnt": len(blockTrgs[n_trg_now]) - 1
                }

            cycle_blocks = []
            for n_sched_block_now in range(n_sched_blocks):
                sched_block_id = "schBlock_" + base_name + str(n_sched_block_now)

                n_tel_now = self.rnd_gen.randint(1, max(1, len(tel_ids) - n_sched_blocks))

                # sched_tel_ids = random.sample(tel_ids, n_tel_now)
                # tel_ids = [x for x in tel_ids if x not in sched_tel_ids]

                sub_arr = []
                # for sched_tel_id_now in sched_tel_ids:
                #   tel_type = sb.SST if sched_tel_id_now[0] == 'S' else sb.MST if sched_tel_id_now[0] == 'M' else sb.LST
                #   sub_arr += [ sb.Telescope(sched_tel_id_now, tel_type) ]

                sched_conf = sb.Configuration(
                    sb.InstrumentConfiguration(
                        sb.PointingMode(2, sb._divergent(2)), sb.Subarray([], sub_arr)
                    ), "camera", "rta"
                )

                n_obs_blocks = self.rnd_gen.randint(1, self.max_n_obs_block)

                n_trg = blockTrgPnt[n_sched_block_now]["n_trg"]
                n_pnt = blockTrgPnt[n_sched_block_now]["n_pnt"]

                if not n_trg in target_pos:
                    target_pos[n_trg] = [
                        (
                            self.rnd_gen.random() *
                            (self.az_min_max[1] - self.az_min_max[0])
                        ) + self.az_min_max[0],
                        (
                            self.rnd_gen.random() *
                            (self.zen_min_max_tel[1] - self.zen_min_max_tel[0])
                        ) + self.zen_min_max_tel[0]
                    ]

                target_id = "target_" + str(n_trg)

                obs_blocks = []
                for n_blockNow in range(n_obs_blocks):
                    obs_block_id = "obs_block_" + str(getTime())

                    point_pos = copy.deepcopy(target_pos[n_trg])
                    point_pos[0] += (self.rnd_gen.random() - 0.5) * 10
                    point_pos[1] += (self.rnd_gen.random() - 0.5) * 10

                    if point_pos[0] > self.az_min_max[1]:
                        point_pos[0] -= 360
                    elif point_pos[0] < self.az_min_max[0]:
                        point_pos[0] += 360

                    obs_coords = sb.Coordinates(
                        2,
                        sb.HorizontalCoordinates(
                            target_pos[n_trg][1], target_pos[n_trg][0]
                        )
                    )
                    # obs_coords = sb.Coordinates(3,sb.GalacticCoordinates(target_pos[n_trg][1],target_pos[n_trg][0]))
                    obs_mode = sb.ObservingMode(
                        sb.Slewing(1), sb.ObservingType(2, sb.GridSurvey(1, 1, 1))
                    )
                    obs_source = sb.Source(
                        target_id, sb.placeholder, sb.High, sb.RegionOfInterest(100),
                        obs_mode, obs_coords
                    )
                    obs_conds = sb.ObservingConditions(
                        sb.DateTime(1), self.obs_block_seconds, 1, sb.Quality(1, 1, 1),
                        sb.Weather(1, 1, 1, 1)
                    )
                    obs_block = sb.ObservationBlock(
                        obs_block_id, obs_source, obs_conds, script_name, 0
                    )

                    obs_blocks += [obs_block]

                    # temporary way to store meta-data
                    # should be replaced by global coordinate access function
                    self.acs_blocks['metadata'][obs_block_id + "_"
                                                + "point_pos"] = point_pos

                sched_block = sb.SchedulingBlock(
                    sched_block_id, sb.Proposal("proposalId"), sched_conf, obs_blocks
                )

                cycle_blocks.append(sched_block)

                self.acs_blocks['sched_block'][sched_block_id] = sched_block

            self.cycle_blocks.append(cycle_blocks)

        return

    # ------------------------------------------------------------------
    # move one from wait to run
    # ------------------------------------------------------------------
    def submit_block_cycle(self):
        self.log.info([['g', " - starting MockSched.submit_block_cycle ..."]])

        if len(self.cycle_blocks) >= self.active_sched_block:
            self.active_sched_block = 0
            self.init_block_cycle()

        # grab the current sched_block from the queue
        blockCycle = self.cycle_blocks[self.active_sched_block]
        self.active_sched_block += 1

        # submit the scheduling blocks
        self.log.info([['g', " - submitting ..."]])
        for sched_block in blockCycle:
            try:
                self.log.info([['y', " --- try putSchedulingBlock ", sched_block.id]])
                complt = self.supervisor.putSchedulingBlock(sched_block)
            except Exception as e:
                self.log.debug([['b', "- Exception - MockSched.putSchedulingBlock: "],
                                ['r', e]])

        self.log.info([['y', " ----- try putSchedulingBlock done !"]])
        return

    # ------------------------------------------------------------------
    # move one from wait to run
    # ------------------------------------------------------------------
    def check_sched_blocks(self):
        self.log.debug([['b', " - starting MockSched.check_sched_blocks ..."]])

        try:
            active = self.supervisor.listSchedulingBlocks()
        except Exception as e:
            self.log.debug([['b', "- Exception - MockSched.listSchedulingBlocks: "],
                            ['r', e]])
            active = []

        active = [x for x in active if x in self.acs_blocks['sched_block']]

        self.log.debug([['b', " --- got ", len(active), " active blocks"]])

        # for block_name in active:
        #   status = self.supervisor.getSchedulingBlockStatus(block_name)
        #   opstatus = self.supervisor.getSbOperationStatus(block_name)
        #   self.log.info([['y'," - active_scheduling_blocks - "],['g',active,'-> '],['y',status,' ']])

        #   for nob in range(len(opstatus.ob_statuses)):
        #     phases = opstatus.ob_statuses[nob].phases
        #     # for p in phases:
        #     #   self.log.info([['y'," -- phases - ",block_name,' ',opstatus.ob_statuses[nob].id,' ',opstatus.ob_statuses[nob].status,' '],['g',p.heartbeat_counter,' ',p.name,' ',p.status,' ',p.progress_message]])
        #     #   break

        return len(active)

    # ------------------------------------------------------------------
    #
    # ------------------------------------------------------------------
    def loop(self, run_event):
        self.log.info([['g', " - starting MockSched.loop ..."]])

        self.submit_block_cycle()

        while run_event.is_set():
            n_sched_blocks = self.check_sched_blocks()
            self.log.info([['g', " - will now wait for 5 sec ..."]])
            sleep(5)
            self.log.info([['g', " - will now try to cancel all ..."]])
            self.cancel_zombie_sched_blocks()

            if n_sched_blocks == 0:
                self.submit_block_cycle()

            sleep(self.loop_sleep)

        return
Exemplo n.º 24
0
from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from sys                        import exit
from sys                        import stdout
from TMCDB                      import MonitorCollector
from TMCDB                      import propertySerailNumber
from omniORB                    import any
import MonitorErrImpl
import MonitorErr
import time

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

try:
    tc =   simpleClient.getComponent('MC_TEST_PROPERTIES_COMPONENT')
    psns =[propertySerailNumber('doubleROProp',    ['1' ]),
           propertySerailNumber('floatROProp',     ['2' ]),
           propertySerailNumber('longROProp',      ['3' ]),
           propertySerailNumber('uLongROProp',     ['4' ]),
           propertySerailNumber('patternROProp',   ['5' ]),
           propertySerailNumber('stringROProp',    ['6' ]),
           propertySerailNumber('longLongROProp',  ['7' ]),
           propertySerailNumber('uLongLongROProp', ['8' ]),
           propertySerailNumber('booleanROProp',   ['9' ]),
           propertySerailNumber('doubleSeqROProp', ['10']),
           propertySerailNumber('floatSeqROProp',  ['11']),
           propertySerailNumber('longSeqROProp',   ['12']),
Exemplo n.º 25
0
#!/usr/bin/env python

from Acspy.Clients.SimpleClient import PySimpleClient
import sys

client   = PySimpleClient()
supplier = client.getComponent('NC_Reliability')

supplier.sendEvents(int(sys.argv[1]))
Exemplo n.º 26
0
 
parser = OptionParser()
parser.add_option("-f", "--frequency", dest="skyFreq",
                       metavar='SkyFreq',
                       help="The desired sky frequency for the beacon")

(options, args) = parser.parse_args()
if options.skyFreq == None:
	print "You must specify a sky frequency use the \"-f\" option"
	sys.exit(-1)

options.skyFreq = float(options.skyFreq)

# Check with the Control Master to see what arrays are in existence
client = PySimpleClient()
master = client.getComponent("CONTROL/MASTER")

arrayList = master.getAutomaticArrayComponents() + \
            master.getManualArrayComponents()
client.releaseComponent("CONTROL/MASTER")

if len(arrayList) != 1:
    if len(arrayList) == 0:
        print "Error: No Arrays in existence, unable to set frequency"
    else:
        print "Error: Multiple arrays detected...are you sure your at the ATF"
    sys.exit


array = client.getComponent(arrayList[0].ComponentName)
Exemplo n.º 27
0
"""

from Acspy.Clients.SimpleClient import PySimpleClient
import Acspy.Common.QoS as QofS
import sys

def exitGracefully(client):
   client.releaseComponent("TEST_QOS_COMPONENT")
   client.disconnect() 
   sys.exit()

# instantiate the simple client
mySimpleClient = PySimpleClient()

# get the test component used for the method invocations that we invoke to test timeouts
testQoSComponent = mySimpleClient.getComponent("TEST_QOS_COMPONENT")

# first, call method on the servant with no QoS timeout set
try:
	testQoSComponent.echo(0, 1000)
	print "Method w/o timeout executed successfully."

except Exception, e:
	print "ERROR 0: timeout exception caught on method invocation when not expected."
	exitGracefully(mySimpleClient)

# test setting/resetting of a (local) timeout and also test invocation of a method 
# (with a timeout set) that doesn't exceed the time out
try:
   timeoutOne = QofS.Timeout(400)
Exemplo n.º 28
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA 02111-1307  USA
#
# @(#) $Id: acspyTestCompReload.py,v 1.1 2005/04/29 21:15:40 dfugate Exp $
###############################################################################
'''
Tests reloading components
'''
from Acspy.Clients.SimpleClient import PySimpleClient
from time import sleep
###############################################################################
if __name__ == "__main__":
    simpleClient = PySimpleClient()
    #this bit a code should make the container print out one special statement
    print "...should see 1 module message now..."
    c1 = simpleClient.getComponent("RELOADCOMP1")
    sleep(4)
    #releasing it should do the same thing
    print "...and another one after it's released..."
    simpleClient.releaseComponent("RELOADCOMP1")
    sleep(4)
    
    print "...there should not be one here though..."
    c1 = simpleClient.getComponent("RELOADCOMP1")
    sleep(4)
    print "...or here..."
    c2 = simpleClient.getComponent("RELOADCOMP2")
    sleep(4)
    print "...or even here"
    simpleClient.releaseComponent("RELOADCOMP1")
    sleep(4)
Exemplo n.º 29
0
class FrontEndTest(unittest.TestCase):
    """
    This test requires ACS running with the testacsproperties CDB and
    the myC cpp container up
    """
    def setUp(self):
        self._my_acs_client = PySimpleClient()
        self._my_acs_client.getLogger().setLevel(logging.CRITICAL)
        self._front_end = FrontEnd(RecorderConfig(), self._my_acs_client)
        self.__my_component_id = "TEST_PROPERTIES_COMPONENT"

    def test_is_acs_client_ok(self):
        self.assertTrue(self._front_end.is_acs_client_ok)

    def test_update_acs_client(self):
        other_client = PySimpleClient()
        other_client.getLogger().setLevel(logging.CRITICAL)
        self._front_end.update_acs_client(other_client)
        self.assertTrue(self._front_end.is_acs_client_ok)
        self._front_end.start_recording()
        yet_other_client = PySimpleClient()
        yet_other_client.getLogger().setLevel(logging.CRITICAL)
        self._front_end.update_acs_client(yet_other_client)
        self._front_end.stop_recording()

    def test_start_recording(self):
        self._front_end.start_recording()
        self.assertTrue(self._front_end.is_recording)
        self._front_end.stop_recording()

        self._my_acs_client.getComponent(self.__my_component_id, True)
        self._front_end.start_recording()
        self.assertTrue(self._front_end.is_recording)
        self._front_end.stop_recording()
        self._my_acs_client.releaseComponent(self.__my_component_id)

    def test_process_component(self):
        self._my_acs_client.getComponent(self.__my_component_id, True)

        self._front_end.process_component(self.__my_component_id)

        self._my_acs_client.releaseComponent(self.__my_component_id)

        self.assertRaises(CannotAddComponentException,
                          self._front_end.process_component, "I_DO_NOT_EXIST")

    def test_remove_wrong_components(self):
        self._my_acs_client.getComponent(self.__my_component_id, True)
        self._front_end.start_recording()

        time.sleep(3)

        self._my_acs_client.releaseComponent(self.__my_component_id)

        time.sleep(10)

        self._front_end.stop_recording()

    def tearDown(self):
        self._front_end.cancel()
        self._front_end = None
Exemplo n.º 30
0
LINKS
- <a href="../../idl/html/interfaceHelloWorld_1_1HelloWorld.html">HelloWorld IDL Documentation</a>
'''

import ACSErrTypeCommon
import ACSErrTypeCommonImpl

# Import the acspy.PySimpleClient class
from Acspy.Clients.SimpleClient import PySimpleClient

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

try:
    # Get the standard HelloWorld device
    hw = simpleClient.getComponent("HELLOWORLD1")
    simpleClient.getLogger().logInfo("Trying to invoke bad method")
    hw.badMethod()

except ACSErrTypeCommon.UnknownEx, e:
    simpleClient.getLogger().logCritical(
        "Caught an ACSException...don't worry because this SHOULD happen.")
    helperException = ACSErrTypeCommonImpl.UnknownExImpl(exception=e)
    helperException.Print()
    helperException.log(simpleClient.getLogger())
    # Release it
    simpleClient.releaseComponent("HELLOWORLD1")

except Exception, e:
    simpleClient.getLogger().logAlert("Caught the wrong type of exception!!!")
    simpleClient.getLogger().logDebug("The exception was:" + str(e))
Exemplo n.º 31
0
import time


# definition of in-test exceptions
class noDataException(Exception):
    pass


class notNulDataException(Exception):
    pass


# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

# Test preparation
cname = 'MC_TEST_COMPONENT4'
try:
    tc = simpleClient.getComponent(cname)
    psns = [
        propertySerailNumber('doubleSeqProp', ['12124']),
        propertySerailNumber('doubleProp', ['3432535'])
    ]
    # doubleSeqProp component archival delta percent defined to 10.0 (MC_TEST_COMPONENT4.xml)
    # doubleProp component archival delta defined percent to 10.0 (MC_TEST_COMPONENT4.xml)
    # longProp component archival delta defined percent to 20.0 (MC_TEST_COMPONENT4.xml)
    # longSeqProp component archival delta defined percent to 20.0 (MC_TEST_COMPONENT4.xml)
    # patternProp component archival delta defined percent to 7.0 (MC_TEST_COMPONENT4.xml)
    mc.registerMonitoredDeviceWithMultipleSerial(cname, psns)
Exemplo n.º 32
0
from Acspy.Clients.SimpleClient import PySimpleClient
c = PySimpleClient()
tmcdb = c.getComponent('TMCDBAccess')
antenna_cai = {}
for i in range(1,25+1):
    antenna = 'DV'+str(i).zfill(2)
#    print "%s -> %s" % (antenna, tmcdb.getAntennaAcaCAI(antenna))
    antenna_cai[tmcdb.getAntennaAcaCAI(antenna)] = antenna

for i in range(1,4+1):
    antenna = 'PM'+str(i).zfill(2)
#    print "%s -> %s" % (antenna, tmcdb.getAntennaAcaCAI(antenna))
    antenna_cai[tmcdb.getAntennaAcaCAI(antenna)] = antenna

for i in range(1,12+1):
    antenna = 'CM'+str(i).zfill(2)
#    print "%s -> %s" % (antenna, tmcdb.getAntennaAcaCAI(antenna))
    antenna_cai[tmcdb.getAntennaAcaCAI(antenna)] = antenna

for i in range(41,65+1):
    antenna = 'DA'+str(i).zfill(2)
#    print "%s -> %s" % (antenna, tmcdb.getAntennaAcaCAI(antenna))
    antenna_cai[tmcdb.getAntennaAcaCAI(antenna)] = antenna
print "#################-----#############"
under = {}
upper = {}
for cai in sorted(antenna_cai):
#    print "%s -> %s" % (cai, antenna_cai[cai])
    if int(cai) <= 31:
        if int(cai) == -1:
            pass
Exemplo n.º 33
0
    def __init__(self, site_type):
        self.log = HMILog(title=__name__)
        self.log.info([['y', " - TmpTest - "], ['g', site_type]])

        self.site_type = site_type
        self.tel_ids = tel_ids[site_type]

        self.redis = redis.StrictRedis(host='localhost',
                                       port=redis_port[site_type],
                                       db=0)
        self.redPipe = self.redis.pipeline()

        self.loop_sleep = 4

        # rnd_seed = 10987268332
        rnd_seed = getTime()
        self.rnd_gen = Random(rnd_seed)

        # Create a client and the ArraySupervisor component
        client = PySimpleClient()
        supervisor = client.getComponent("ArraySupervisor")

        config = sb.Configuration(
            sb.InstrumentConfiguration(sb.PointingMode(2, sb._divergent(2)),
                                       sb.Subarray([], [])), "camera", "rta")
        coords = sb.Coordinates(3, sb.GalacticCoordinates(10, 10))
        observing_mode = sb.ObservingMode(
            sb.Slewing(1), sb.ObservingType(2, sb.GridSurvey(1, 1, 1)))
        src = sb.Source("source", sb.placeholder, sb.High,
                        sb.RegionOfInterest(100), observing_mode, coords)
        obs = sb.ObservingConditions(sb.DateTime(1), 60,
                                     1, sb.Quality(1, 1, 1),
                                     sb.Weather(1, 1, 1, 1))

        ob = sb.ObservationBlock("ob", src, obs, "guiACS_sched_blocks_script0",
                                 0)
        # ob.observing_conditions.duration = 20
        print 'xxxxxxxx', obs, '------', ob.observing_conditions.duration
        schedulingBlock = sb.SchedulingBlock("sb", sb.Proposal("id"), config,
                                             [ob])

        # Submit the scheduling block to the array supervisor
        print "Submit the scheduling block to the array supervisor"
        comp = supervisor.putSchedulingBlock(schedulingBlock)
        # Print the command execution completion
        print comp
        print ""

        # Retrieve the ids of all scheduling blocks currently running on the array supervisor
        print ""
        print "Retrieve the ids of all scheduling blocks currently running on the array supervisor"
        active = supervisor.listSchedulingBlocks()
        while True:
            active = supervisor.listSchedulingBlocks()
            for block_name in active:
                status = supervisor.getSchedulingBlockStatus(block_name)
                opstatus = supervisor.getSbOperationStatus(block_name)
                phases = opstatus.ob_statuses[0].phases
                for p in phases:
                    print 'xxx', block_name, p
                self.log.info([['y', " - active_scheduling_blocks - "],
                               ['g', active, '-> '], ['y', status, ' '],
                               ['p', opstatus]])
            if len(active) == 0:
                break
            sleep(.5)

        # # Read the status of the scheduling block with the id "sb"
        # print "Read the status of the scheduling block with the id 'sb'"
        # status = supervisor.getSchedulingBlockStatus("sb")
        # print status
        # print ""

        # # Read the operation status of the scheduling block with the id "sb"
        # print "Read the operation status of the scheduling block with the id 'sb'"
        # opstatus = supervisor.getSbOperationStatus("sb")
        # print opstatus
        # print ""

        # active_scheduling_blocks = supervisor.listSchedulingBlocks()
        # print active_scheduling_blocks

        # zz = jsonAcs.classFactory.defaultValues[sb.SchedulingBlock]
        # print zz
        # print '--------------------------------'
        # for block in zz.observation_blocks:
        #     block.observing_conditions.duration = 30  # .observing_conditions
        # print zz.observation_blocks
        # zz = jsonAcs.encode(zz)

        # sb3 = jsonAcs.decode(zz)
        # sb3.id = 'sb3'

        # supervisor.putSchedulingBlock(sb3)
        # active_scheduling_blocks = supervisor.listSchedulingBlocks()
        # self.log.info([['y', " - active_scheduling_blocks - "],
        #                ['g', active_scheduling_blocks]])

        # while len(active_scheduling_blocks) > 0:
        #     self.log.info([['y', " - active_scheduling_blocks - "],
        #                    ['g', active_scheduling_blocks]])
        #     sleep(.5)
        #     active_scheduling_blocks = supervisor.listSchedulingBlocks()

        # print 'ended!', active_scheduling_blocks

        # # self.init()

        # # gevent.spawn(self.loop)

        return
Exemplo n.º 34
0
class ComponentUtilTest(unittest.TestCase):
    """
    This test requires ACS running with the testacsproperties CDB and
    the myC cpp container up
    """
    def setUp(self):
        self._my_acs_client = PySimpleClient()
        logger = self._my_acs_client.getLogger()
        logger.setLevel(logging.WARNING)
        # disable annoying output from the tests

    def tearDown(self):
        self._my_acs_client.disconnect()

    def test_get_enum_prop_dict(self):

        my_component = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_COMPONENT", True)

        enum_prop = my_component._get_EnumTestROProp()

        decoded = component_util.get_enum_prop_dict(enum_prop)
        expected_value = {'0': 'STATE1', '1': 'STATE2', '2': 'STATE3'}
        self.assertEqual(expected_value, decoded)

        enum_prop = my_component._get_EnumTestRWProp()

        decoded = component_util.get_enum_prop_dict(enum_prop)
        expected_value = {'0': 'STATE1', '1': 'STATE2', '2': 'STATE3'}
        self.assertEqual(expected_value, decoded)

        self._my_acs_client.releaseComponent("TEST_PROPERTIES_COMPONENT")

    def test_get_property_type(self):
        my_component = self._my_acs_client.getComponent(
            "TEST_PROPERTIES_COMPONENT", True)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_EnumTestROProp()._NP_RepositoryId),
            PropertyType.OBJECT)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_EnumTestRWProp()._NP_RepositoryId),
            PropertyType.OBJECT)

        PropertyType.OBJECT

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_doubleROProp()._NP_RepositoryId),
            PropertyType.DOUBLE)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_floatSeqRWProp()._NP_RepositoryId),
            PropertyType.FLOAT_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longSeqRWProp()._NP_RepositoryId),
            PropertyType.LONG_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongLongRWProp()._NP_RepositoryId),
            PropertyType.LONG_LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongLongRWProp()._NP_RepositoryId),
            PropertyType.LONG_LONG)
        self.assertEqual(
            component_util.get_property_type(
                my_component._get_doubleRWProp()._NP_RepositoryId),
            PropertyType.DOUBLE)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongROProp()._NP_RepositoryId),
            PropertyType.LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_booleanROProp()._NP_RepositoryId),
            PropertyType.BOOL)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_doubleSeqROProp()._NP_RepositoryId),
            PropertyType.DOUBLE_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longLongROProp()._NP_RepositoryId),
            PropertyType.LONG_LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_patternROProp()._NP_RepositoryId),
            PropertyType.BIT_FIELD)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongRWProp()._NP_RepositoryId),
            PropertyType.LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_booleanRWProp()._NP_RepositoryId),
            PropertyType.BOOL)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_doubleSeqRWProp()._NP_RepositoryId),
            PropertyType.DOUBLE_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longLongRWProp()._NP_RepositoryId),
            PropertyType.LONG_LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_patternRWProp()._NP_RepositoryId),
            PropertyType.BIT_FIELD)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongSeqROProp()._NP_RepositoryId),
            PropertyType.LONG_SEQ)

        self.assertRaises(
            UnsupporterPropertyTypeError, component_util.get_property_type,
            my_component._get_booleanSeqROProp()._NP_RepositoryId)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_floatROProp()._NP_RepositoryId),
            PropertyType.FLOAT)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longROProp()._NP_RepositoryId),
            PropertyType.LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_stringROProp()._NP_RepositoryId),
            PropertyType.STRING)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongSeqRWProp()._NP_RepositoryId),
            PropertyType.LONG_SEQ)

        self.assertRaises(
            UnsupporterPropertyTypeError, component_util.get_property_type,
            my_component._get_booleanSeqRWProp()._NP_RepositoryId)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_floatRWProp()._NP_RepositoryId),
            PropertyType.FLOAT)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longRWProp()._NP_RepositoryId),
            PropertyType.LONG)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_stringRWProp()._NP_RepositoryId),
            PropertyType.STRING)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_floatSeqROProp()._NP_RepositoryId),
            PropertyType.FLOAT_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_longSeqROProp()._NP_RepositoryId),
            PropertyType.LONG_SEQ)

        self.assertEqual(
            component_util.get_property_type(
                my_component._get_uLongLongROProp()._NP_RepositoryId),
            PropertyType.LONG_LONG)

    def test_is_archive_delta_enabled(self):

        # First test the cases when it should be false
        self.assertFalse(component_util.is_archive_delta_enabled(None))
        self.assertFalse(component_util.is_archive_delta_enabled(False))
        self.assertFalse(component_util.is_archive_delta_enabled("0"))
        self.assertFalse(component_util.is_archive_delta_enabled("0.0"))
        self.assertFalse(component_util.is_archive_delta_enabled(0))
        self.assertFalse(component_util.is_archive_delta_enabled(0.0))
Exemplo n.º 35
0
magicNumber = int(argv[2])


def myHandler(ts, device, parameter, value):
    '''
    '''
    global count
    if count < magicNumber:
        count = count + 1
    return


#create the consumer
myConsumer = ArchiveConsumer(myHandler)
myConsumer.consumerReady()
#activate the component which will publish the events automatically
joe = PySimpleClient()
ps = joe.getComponent("TEST_PS_1")
#give the consumer a chance to receive the events
sleep(int(argv[1]))

#shutdown everything cleanly
myConsumer.disconnect()
joe.releaseComponent("TEST_PS_1")
joe.disconnect()

if count == magicNumber:
    print "Test passed!"
else:
    print "Test failed:", count
Exemplo n.º 36
0
from sys                        import exit
from TMCDB                      import MonitorCollector
from TMCDB                      import propertySerailNumber
from omniORB                    import any
import MonitorErrImpl
import MonitorErr
import time

# definition of in-test exceptions
class noDataException (Exception) : pass
class notNulDataException (Exception) : pass

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

mc = simpleClient.getComponent(argv[1])

# Test preparation
cname = 'MC_TEST_COMPONENT'
try:
    tc =   simpleClient.getComponent(cname)
    psns =[propertySerailNumber('doubleSeqProp', ['12124']),
           propertySerailNumber('doubleProp', ['3432535'])
           ]
    # doubleSeqProp component archive_max_int defined to 1 (MC_TEST_COMPONENT.xml)
    # doubleProp component archive_max_inta defined to 1 (MC_TEST_COMPONENT.xml)
    # longProp component archive_max_int defined to 1 (MC_TEST_COMPONENT.xml)
    # longSeqProp component archive_max_int defined to 1 (MC_TEST_COMPONENT.xml)
    # patternProp component archive_max_int defined to 1 (MC_TEST_COMPONENT.xml)
    mc.registerMonitoredDeviceWithMultipleSerial(cname, psns)
    print "Test preparation with SUCCESS"
Exemplo n.º 37
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307  USA
#
# @(#) $Id: acspyexmplTestPyContainer.py,v 1.8 2006/10/25 14:10:28 bjeram Exp $
"""
Test very simple components.
"""

from Acspy.Clients.SimpleClient import PySimpleClient

simpleClient = PySimpleClient()

try:
    #test an immortal cob first
    print "Testing HELLODEMO1 (i.e., immortal components)"
    test1 = simpleClient.getComponent("HELLODEMO1")
    print test1.sayHello()
    print test1.sayHelloWithParameters("I'm an 'inString'", 3.14)

    print
    print "Now test HELLODEMO2 (i.e., non-immortal components)"
    test2 = simpleClient.getComponent("HELLODEMO2")
    print test2.sayHello()
    print test2.sayHelloWithParameters("I'm an 'inString'", 3.14)

    print
    print "Now test getting HELLODEMO2 non sticky"
    test3 = simpleClient.getComponentNonSticky("HELLODEMO2")
    print test3.sayHello()
    print test3.sayHelloWithParameters("I'm an 'inString'", 3.14)
Exemplo n.º 38
0
class ServerRepresentationTest(unittest.TestCase):
    """
    Test cases for the Server representation.
    """

    #---------------------------------------------------------------------------
    def setUp(self):
        """
        Test case fixture.
        """
        self.client = PySimpleClient("ServerRepresentationTest")
        self.simulator = self.client.getComponent("SIMULATION_SERVER")
        self.lamp = self.client.getComponent("LAMP_ACCESS")

    #---------------------------------------------------------------------------
    def tearDown(self):
        """
        Test case fixture cleanup.
        """
        self.client.releaseComponent("SIMULATION_SERVER")
        self.client.releaseComponent("LAMP_ACCESS")
        self.client.disconnect()

    #---------------------------------------------------------------------------
    def testSetupBehavior(self):
        """
        Modify the behavior of the simulated LAMP_ACCESS component.
        Setup the getLampBrightness function so it returns a constant 
        number.
        """

        code = """LOGGER.logInfo('getLampBrightness called.')
6.8"""
        self.simulator.setMethod('LAMP_ACCESS', 'getLampBrightness', code, 0.0)

        brightness = self.lamp.getLampBrightness()
        assert abs(brightness - 6.8) <= 0.01

    #---------------------------------------------------------------------------
    def testPersistentData(self):
        """
        Data can be left in a global buffer located in the Goodies module.
        This allows to get input data to persist between calls to the simulated
        component.
        As this test case shows, this can be useful to simulate get/set methods.
        """
        code = """LOGGER.logInfo('setLampBrightness called; brightness='+str(parameters[0]))
from Acssim.Goodies import setGlobalData
setGlobalData('brightness', parameters[0])
None"""
        self.simulator.setMethod('LAMP_ACCESS', 'setLampBrightness', code, 0.0)
        code = """LOGGER.logInfo('getLampBrightness called.')
from Acssim.Goodies import setGlobalData
getGlobalData('brightness')"""
        self.simulator.setMethod('LAMP_ACCESS', 'getLampBrightness', code, 0.0)

        self.lamp.setLampBrightness(3.14)
        brightness = self.lamp.getLampBrightness()
        assert abs(brightness - 3.14) <= 0.01

    #---------------------------------------------------------------------------
    def testGetGlobalData(self):
        """
        The SIMULATION_SERVER component implements also a getGlobalData() function,
        which is tested here.
        """
        code = """LOGGER.logInfo('setLampBrightness called; brightness='+str(parameters[0]))
from Acssim.Goodies import setGlobalData
setGlobalData('brightness', parameters[0])
None"""
        self.simulator.setMethod('LAMP_ACCESS', 'setLampBrightness', code, 0.0)
        self.lamp.setLampBrightness(3.14)
        brightness = self.simulator.getGlobalData('brightness')
        assert brightness == '3.14'

    #---------------------------------------------------------------------------
    def testRaiseException(self):
        """
        Modify the behaviour of the LAMP_ACCESS component so it raises the
        LampUnavailable exception when the getLampBrightness() function is
        called.
        """
        code = """from demo import LampUnavailable
raise LampUnavailable()"""
        self.simulator.setMethod('LAMP_ACCESS', 'getLampBrightness', code, 0.0)

        try:
            b = self.lamp.getLampBrightness()
        except LampUnavailable, ex:
            return  # Correct exception was raised.
        except:
Exemplo n.º 39
0
        DevIO.__init__(self, 3.14)

    def read(self):
        return 3.14
#-------------------------------------------------------
class MyCallback(CBvoid):
     def working (self, completion, desc):
         '''
         '''
         print "Ramped PowerSupply startRamping CB: working method called"

#-------------------------------------------------------
from time import sleep
if __name__=="__main__":
    compName = "TEST_RPS_1"

    # Make an instance of the PySimpleClient
    simpleClient = PySimpleClient()
    comp = simpleClient.getComponent(compName)

    myCB = MyCallback()
    myCorbaCB = simpleClient.activateOffShoot(myCB)
    myDescIn = ACS.CBDescIn(0L, 0L, 0L)
    
    print "Ramped PowerSupply readback value:", comp._get_readback().get_sync()[0]

    comp.startRamping(1L, myCorbaCB, myDescIn)
    
    simpleClient.releaseComponent(compName)
    simpleClient.disconnect()
Exemplo n.º 40
0
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA 02111-1307  USA
#
# @(#) $Id: javaSupplierComponent.py,v 1.1 2008/05/23 12:53:45 eallaert Exp $
"""
"""
from Acspy.Clients.SimpleClient import PySimpleClient
from time import sleep
import sys

simpleClient = PySimpleClient()
sleep(5)

print "Getting the Supplier"
sys.stdout.flush()
mySupplierComp = simpleClient.getComponent("SUPPLIERCOMP1")


print "Sending events"
sys.stdout.flush()
for i in range(50):
    mySupplierComp.sendEvents(1)
    sleep(1)

simpleClient.releaseComponent("SUPPLIERCOMP1")

print "Finished sending events"
sys.stdout.flush()
Exemplo n.º 41
0
#! /usr/bin/env python

from sys import argv
from time import sleep
from Acspy.Clients.SimpleClient import PySimpleClient
import ACS
import time, os

simpleClient = PySimpleClient()
cdb_mount = simpleClient.getComponent("COMP99") 

sleep(10)

simpleClient.releaseComponent("COMP99")


Exemplo n.º 42
0
    print "whenSet:", propRef._get_whenSet()
    print "whenCleared:", propRef._get_whenCleared()
    #print ":", propRef._get_()

    print
    print "Testing ", propRef, " methods..."
    #print ":", propRef.


#------------------------------------------------------------------------------
# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()
DESC = ACS.CBDescIn(0L, 0L, 0L)
CBVOID = CBvoid()._this()

pybaci = simpleClient.getComponent("PYBACI1")
print "----------------------------------------------------------------"
testBasicROProperty(pybaci._get_stringROProp(), CBstring()._this())
print "----------------------------------------------------------------"
testBasicROProperty(pybaci._get_strSeqProp(), CBstringSeq()._this())
print "----------------------------------------------------------------"
testPatternROProperty(pybaci._get_patternROProp(), CBpattern()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_doubleROProp(), CBdouble()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_longROProp(), CBlong()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_longLongROProp(), CBlongLong()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_uLongLongROProp(), CBuLongLong()._this())
print "----------------------------------------------------------------"
Exemplo n.º 43
0
# @(#) $Id: acspyTestContainer.py,v 1.10 2005/05/26 17:23:26 dfugate Exp $

"""
Test component services via a component. In short, this provides complete
testing of the container.
"""

from Acspy.Clients.SimpleClient import PySimpleClient
import acspytest
from time import sleep

simpleClient = PySimpleClient()

#test an immortal component first
print "Testing TESTCOMPONENT (i.e., immortal components)"
test = simpleClient.getComponent("TESTCOMPONENT")
test.sayHello()
val = test.testServices()
if not val:
    print "TESTCOMPONENT.testServices() FAILED!!!"

#test a mortal component next
print "Testing TESTCOMPONENT1 (i.e., mortal components)"
test1 = simpleClient.getComponent("TESTCOMPONENT1")
test1.sayHello()
val = test1.testServices()
if not val:
    print "TESTCOMPONENT1.testServices() FAILED!!!"

#should have been activated and deactivated twice already
print "Testing TESTCOMPONENT2 (i.e., getComponent() and component activation/deactivation"
Exemplo n.º 44
0
import logging
import time
from time import sleep
from Acspy.Clients.SimpleClient import PySimpleClient

client = PySimpleClient()
supervisor = None

logging.basicConfig()
log = logging.getLogger()

while True:
    try:
        supervisor = client.getComponent("ArraySupervisor")
    except Exception as e:
        log.info(' - could not get supervisor ...' + str(e))

    log.info(' - I"m alive ... ' + str(time.time()))

    sleep(15)
Exemplo n.º 45
0
from Acspy.Clients.SimpleClient import PySimpleClient
import Acspy.Common.QoS as QofS
import sys


def exitGracefully(client):
    client.releaseComponent("TEST_QOS_COMPONENT")
    client.disconnect()
    sys.exit()


# instantiate the simple client
mySimpleClient = PySimpleClient()

# get the test component used for the method invocations that we invoke to test timeouts
testQoSComponent = mySimpleClient.getComponent("TEST_QOS_COMPONENT")

# first, call method on the servant with no QoS timeout set
try:
    testQoSComponent.echo(0, 1000)
    print "Method w/o timeout executed successfully."

except Exception, e:
    print "ERROR 0: timeout exception caught on method invocation when not expected."
    exitGracefully(mySimpleClient)

# test setting/resetting of a (local) timeout and also test invocation of a method
# (with a timeout set) that doesn't exceed the time out
try:
    timeoutOne = QofS.Timeout(400)
Exemplo n.º 46
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307  USA
#
# @(#) $Id: acspyTestClientMinimum.py,v 1.16 2007/09/21 20:00:37 agrimstrup Exp $
"""
Demonstration of how to use the acspyPySimpleClient class
to access an ACS DO from a Python program
"""

from Acspy.Clients.SimpleClient import PySimpleClient

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

# Get the standard MOUNT1 Mount device
mount = simpleClient.getComponent("MOUNT1")

# Get the actAz property and print it out
print "MOUNT1 actual azimuth: ", mount._get_actAz().get_sync()[0]

# See what's available
components = [c.name for c in simpleClient.availableComponents()]
components.sort()
print "Available components: ", components

from ACS__POA import OffShoot


class MyOffShoot(OffShoot):
    pass
Exemplo n.º 47
0
    print "bitDescription:", propRef._get_bitDescription()
    print "whenSet:", propRef._get_whenSet()
    print "whenCleared:", propRef._get_whenCleared()
    #print ":", propRef._get_()

    print
    print "Testing ", propRef, " methods..."
    #print ":", propRef.
    
#------------------------------------------------------------------------------
# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()
DESC   = ACS.CBDescIn(0L, 0L, 0L)
CBVOID = CBvoid()._this()

pybaci = simpleClient.getComponent("PYBACI1")
print "----------------------------------------------------------------"
testBasicROProperty(pybaci._get_stringROProp(), CBstring()._this())
print "----------------------------------------------------------------"
testBasicROProperty(pybaci._get_strSeqProp(), CBstringSeq()._this())
print "----------------------------------------------------------------"
testPatternROProperty(pybaci._get_patternROProp(),CBpattern()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_doubleROProp(), CBdouble()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_longROProp(), CBlong()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_longLongROProp(), CBlongLong()._this())
print "----------------------------------------------------------------"
testComplexROProperty(pybaci._get_uLongLongROProp(), CBuLongLong()._this())
print "----------------------------------------------------------------"
Exemplo n.º 48
0
from Acspy.Clients.SimpleClient import PySimpleClient

remoteComponentName = "TESTMAXMSGSIZE"

# Loop and call the sendSequence method on the component
# making the size of the sequence sent larger w/ each iteration
# at some point, the ORB should fail because omniorb's max
# msg size will have been exceeded.

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

while 1:
    try:
        characters = "1"

        # Get the test component by name
        remoteComponent = simpleClient.getComponent(remoteComponentName)

        for i in range(0, 22):
            print "Length being sent: ", len(characters)
            remoteComponent.sendSequence(characters)
            characters = characters + characters

        simpleClient.releaseComponent(remoteComponentName)
    except:
        print "FAILED to send: ", len(characters)
        time.sleep(1)

simpleClient.disconnect()
Exemplo n.º 49
0
#!/usr/bin/env python
from Acspy.Clients.SimpleClient import PySimpleClient     # Import the acspy.PySimpleClient class
from Acspy.Common.Callbacks     import CBdouble
import ACS                      # Import the Python CORBA stubs for BACI
from time                       import sleep

#------------------------------------------------------------------------------
simpleClient = PySimpleClient()

#Get the MOUNT1 Mount device
mount = simpleClient.getComponent("MOUNT2_LOOP")

#Get the actAz property
actAzProperty = mount._get_actAz()

#Create a callback monitor for the actAz Property
cbMon = CBdouble(name="actAz", archive=1)  
actMon = actAzProperty.create_monitor(cbMon._this(), ACS.CBDescIn(0L, 0L, 0L))

#Working method gets invoked once per second
actMon.set_timer_trigger(10000000)  

#Destroy the monitor after ten seconds
sleep(10)  
actMon.destroy()

print "The monitored values are: ", cbMon.values

# Release the component
simpleClient.releaseComponent("MOUNT2_LOOP")
simpleClient.disconnect()
Exemplo n.º 50
0
import datetime
import numpy as np
from Acspy.Clients.SimpleClient import PySimpleClient

print "Getting python client ..."
c = PySimpleClient()
names = []
tmcdb = c.getComponent('TMCDBAccess')

for i in range(1,17):
    names.append('CORR/CDP_NODE/N%s' % str(i).zfill(2))
names.append('CORR/CDP_MASTER')
print "Start profiling ..."
prof = {}
for comp_name in names:
    print "Getting: %s" % comp_name
    t0 = datetime.datetime.utcnow()
    node = c.getComponent(comp_name)
    t1 = datetime.datetime.utcnow()
    delta = (t1 - t0)#.total_seconds()
    prof[comp_name] = (delta.microseconds + 0.0 + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6

print "\nStats in seconds [s]\n"
for comp, delta in prof.items():
    print "%s => %f" % (comp, delta)

values = np.array(prof.values())
print "\nStats [s]\n"
print "min:  %f" % ((values.min()))
print "max:  %f" % ((values.max()))
print "mean: %f" % ((values.mean()))
Exemplo n.º 51
0
# @(#) $Id: acspyTestContainer.py,v 1.10 2005/05/26 17:23:26 dfugate Exp $

"""
Test component services via a component. In short, this provides complete
testing of the container.
"""

from Acspy.Clients.SimpleClient import PySimpleClient
import acspytest
from time import sleep

simpleClient = PySimpleClient()

#test an immortal component first
print "Testing TESTCOMPONENT (i.e., immortal components)"
test = simpleClient.getComponent("TESTCOMPONENT")
test.sayHello()
val = test.testServices()
if not val:
    print "TESTCOMPONENT.testServices() FAILED!!!"

#test a mortal component next
print "Testing TESTCOMPONENT1 (i.e., mortal components)"
test1 = simpleClient.getComponent("TESTCOMPONENT1")
test1.sayHello()
val = test1.testServices()
if not val:
    print "TESTCOMPONENT1.testServices() FAILED!!!"

#should have been activated and deactivated twice already
print "Testing TESTCOMPONENT2 (i.e., getComponent() and component activation/deactivation"
Exemplo n.º 52
0
#! /usr/bin/env python

from sys import argv
from time import sleep
from Acspy.Clients.SimpleClient import PySimpleClient
import ACS
import time, os

simpleClient = PySimpleClient()
cdb_mount = simpleClient.getComponent("COMP99")

sleep(10)

simpleClient.releaseComponent("COMP99")
Exemplo n.º 53
0
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA 02111-1307  USA
#
# @(#) $Id: acsncTestConSup.py,v 1.6 2006/03/08 17:50:44 dfugate Exp $

"""
"""

from Acspy.Clients.SimpleClient import PySimpleClient
from sys                        import argv
from time                       import sleep

# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

consumer = simpleClient.getComponent(argv[1])


if len(argv)==3:
    supplier = simpleClient.getComponent(argv[2])
    supplier.sendEvents(10)
else:
    sleep(10)

sleep(50)


simpleClient.releaseComponent(argv[1])
sleep(2)

if len(argv)==3:
Exemplo n.º 54
0
#
# @(#) $Id: acspyTestContainer.py,v 1.10 2005/05/26 17:23:26 dfugate Exp $
"""
Test component services via a component. In short, this provides complete
testing of the container.
"""

from Acspy.Clients.SimpleClient import PySimpleClient
import acspytest
from time import sleep

simpleClient = PySimpleClient()

#test an immortal component first
print "Testing TESTCOMPONENT (i.e., immortal components)"
test = simpleClient.getComponent("TESTCOMPONENT")
test.sayHello()
val = test.testServices()
if not val:
    print "TESTCOMPONENT.testServices() FAILED!!!"

#test a mortal component next
print "Testing TESTCOMPONENT1 (i.e., mortal components)"
test1 = simpleClient.getComponent("TESTCOMPONENT1")
test1.sayHello()
val = test1.testServices()
if not val:
    print "TESTCOMPONENT1.testServices() FAILED!!!"

#should have been activated and deactivated twice already
print "Testing TESTCOMPONENT2 (i.e., getComponent() and component activation/deactivation"
Exemplo n.º 55
0
# Make an instance of the PySimpleClient
simpleClient = PySimpleClient()

# Print information about the available COBs
components = simpleClient.availableComponents()

simpleClient.getLogger().logInfo("COBs available are: ")
for cob in components:
    simpleClient.getLogger().logInfo(cob.name + " of type " + cob.type)

# Do something on a device.
simpleClient.getLogger().logInfo("We can directly manipulate a device once we get it, which is easy.")
try:
    # Get the standard MOUNT1 Mount device
    mount = simpleClient.getComponent("MOUNT1")

    # Get the actAz property
    actAzProperty = mount._get_actAz()

    # Ask the current value of the property
    (azm, compl) = actAzProperty.get_sync()
    simpleClient.getLogger().logInfo("MOUNT1 actual azimuth: " + str(azm))

    # Release it
    simpleClient.releaseComponent("MOUNT1")
    
except Exception, e:
    simpleClient.getLogger().logCritical("Sorry, I expected there to be a Mount in the system and there isn't.")
    simpleClient.getLogger().logDebug("The exception was:" + str(e))