Example #1
0
        def send_evt_msg(zmq_driver_process):
            """
            Await events on the driver process event queue and publish them
            on a ZMQ PUB socket to the driver process client.
            """
            context = zmq.Context()
            sock = context.socket(zmq.PUB)
            sock.bind(zmq_driver_process.event_host_string)
            mi_logger.info('Driver process event socket bound to %s',
                           zmq_driver_process.event_host_string)

            zmq_driver_process.stop_evt_thread = False
            while not zmq_driver_process.stop_evt_thread:
                try:
                    evt = zmq_driver_process.events.pop(0)
                    mi_logger.debug('Event thread sending event %s', str(evt))
                    while evt:
                        try:
                            sock.send_pyobj(evt, flags=zmq.NOBLOCK)
                            evt = None
                            mi_logger.debug('Event sent!')
                        except zmq.ZMQError:
                            time.sleep(.1)
                            
                except IndexError:
                    time.sleep(.1)

            sock.close()
            context.term()
            mi_logger.info('Driver process event socket closed')
Example #2
0
 def recv_cmd_msg(zmq_driver_process):
     """
     Await commands on a ZMQ REP socket, forwaring them to the
     driver for processing and returning the result.
     """
     context = zmq.Context()
     sock = context.socket(zmq.REP)
     sock.bind(zmq_driver_process.cmd_host_string)
     mi_logger.info('Driver process cmd socket bound to %s',
                    zmq_driver_process.cmd_host_string)
 
     zmq_driver_process.stop_cmd_thread = False
     while not zmq_driver_process.stop_cmd_thread:
         try:
             msg = sock.recv_pyobj(flags=zmq.NOBLOCK)
             mi_logger.debug('Processing message %s', str(msg))
             reply = zmq_driver_process.cmd_driver(msg)
             while True:
                 try:
                     sock.send_pyobj(reply)
                     break
                 except zmq.ZMQError:
                     time.sleep(.1)
         except zmq.ZMQError:
             time.sleep(.1)
 
     sock.close()
     context.term()
     mi_logger.info('Driver process cmd socket closed.')
Example #3
0
        def recv_cmd_msg(zmq_driver_process):
            """
            Await commands on a ZMQ REP socket, forwaring them to the
            driver for processing and returning the result.
            """
            context = zmq.Context()
            sock = context.socket(zmq.REP)
            zmq_driver_process.cmd_port = sock.bind_to_random_port(zmq_driver_process.cmd_host_string)
            mi_logger.info("Driver process cmd socket bound to %i", zmq_driver_process.cmd_port)
            file(zmq_driver_process.cmd_port_fname, "w+").write(str(zmq_driver_process.cmd_port) + "\n")

            zmq_driver_process.stop_cmd_thread = False
            while not zmq_driver_process.stop_cmd_thread:
                try:
                    msg = sock.recv_pyobj(flags=zmq.NOBLOCK)
                    mi_logger.debug("Processing message %s", str(msg))
                    reply = zmq_driver_process.cmd_driver(msg)
                    while True:
                        try:
                            sock.send_pyobj(reply, flags=zmq.NOBLOCK)
                            break
                        except zmq.ZMQError:
                            time.sleep(0.1)
                            if zmq_driver_process.stop_cmd_thread:
                                break
                except zmq.ZMQError:
                    time.sleep(0.1)

            sock.close()
            context.term()
            mi_logger.info("Driver process cmd socket closed.")
Example #4
0
        def send_evt_msg(zmq_driver_process):
            """
            Await events on the driver process event queue and publish them
            on a ZMQ PUB socket to the driver process client.
            """
            context = zmq.Context()
            sock = context.socket(zmq.PUB)
            zmq_driver_process.evt_port = sock.bind_to_random_port(zmq_driver_process.event_host_string)
            mi_logger.info("Driver process event socket bound to %i", zmq_driver_process.evt_port)
            file(zmq_driver_process.evt_port_fname, "w+").write(str(zmq_driver_process.evt_port) + "\n")

            zmq_driver_process.stop_evt_thread = False
            while not zmq_driver_process.stop_evt_thread:
                try:
                    evt = zmq_driver_process.events.pop(0)
                    mi_logger.debug("Event thread sending event %s", str(evt))
                    while evt:
                        try:
                            sock.send_pyobj(evt, flags=zmq.NOBLOCK)
                            evt = None
                            mi_logger.debug("Event sent!")
                        except zmq.ZMQError:
                            time.sleep(0.1)
                            if zmq_driver_process.stop_evt_thread:
                                break
                except IndexError:
                    time.sleep(0.1)

            sock.close()
            context.term()
            mi_logger.info("Driver process event socket closed")
    def test_configure(self):
        """Driver configuration tests"""
        channels = Some.VALID_CHANNELS + Some.INVALID_CHANNELS

        mi_logger.debug("\n configure: %s" % str(channels))

        configs = {}
        for c in channels:
            configs[c] = {'method': 'ethernet',
                          'device_addr': '1.1.1.1',
                          'device_port': 1,
                          'server_addr': '2.2.2.2',
                          'server_port': 2}

        result = self.driver.configure(configs)

        _print_dict("\n configure result", result)

        for c in channels:
            self.assertTrue(c in result)

        for c in Some.INVALID_CHANNELS:
            self.assertEqual(result[c], InstErrorCode.INVALID_CHANNEL)

        for c in Some.VALID_CHANNELS:
            self.assertEqual(result[c], InstErrorCode.OK)
    def get(self, params, *args, **kwargs):
        mi_logger.debug("MyProtocol(%s).get: params=%s" % (self._channel,
                                                           str(params)))
        assert isinstance(params, (list, tuple))
        result = {}
        for param in params:
            if param in self._values:
                value = self._values[param]
            else:
                value = InstErrorCode.INVALID_PARAMETER
            result[param] = value

        return result
    def test_connect_disconnect(self):
        """Test state change when connecting and disconnecting"""
        result = self.driver.get_current_state()
        mi_logger.debug("Initial state result: %s", result)
        self.assertEquals(result[Channel.INSTRUMENT], DriverState.UNCONFIGURED)

        self.driver.chan_map[Channel.INSTRUMENT].connect = Mock(return_value = 12)
        result = self.driver.connect()
        result = self.driver.get_current_state()
        # Verify we hit the protocol since we are "connected"
        self.assertEquals(result[Channel.INSTRUMENT], DriverState.UNCONFIGURED)
        result = self.driver.disconnect()
        result = self.driver.get_current_state()
        # driver FSM should intercept
        self.assertEquals(result[Channel.INSTRUMENT], DriverConnectionState.DISCONNECTED)
    def test_get_params_channel_all(self):
        """Driver get all params tests"""
        params = [(Channel.ALL, Parameter.PARAM1),
                  (Channel.ALL, Parameter.PARAM2)]

        mi_logger.debug("\nGET: %s" % str(params))

        get_result = self.driver.get(params)

        _print_dict("\nGET get_result", get_result)

        for c in Channel.list():
            if c != Channel.ALL:
                self.assertTrue((c, Parameter.PARAM1) in get_result)
                self.assertTrue((c, Parameter.PARAM2) in get_result)
    def test_get_params(self):
        """Driver get params tests"""
        params = Some.VALID_PARAMS + Some.INVALID_PARAMS

        mi_logger.debug("\nGET: %s" % str(params))

        get_result = self.driver.get(params)

        _print_dict("\nGET get_result", get_result)

        self.assertEqual(get_result[("invalid_chan", Parameter.PARAM1)],
                         InstErrorCode.INVALID_CHANNEL)

        self.assertEqual(get_result[(Channel.CHAN1, "invalid_param")],
                         InstErrorCode.INVALID_PARAMETER)

        for cp in Some.VALID_PARAMS:
            self.assertTrue(cp in get_result)
    def test_connect(self):
        """Driver connection tests"""
        channels = Some.VALID_CHANNELS + Some.INVALID_CHANNELS

        mi_logger.debug("\n connect: %s" % str(channels))

        result = self.driver.connect(channels)

        _print_dict("\n connect result", result)

        for c in channels:
            self.assertTrue(c in result)

        for c in Some.INVALID_CHANNELS:
            self.assertEqual(result[c], InstErrorCode.INVALID_CHANNEL)

        for c in Some.VALID_CHANNELS:
            self.assertEqual(result[c], InstErrorCode.OK)
    def set(self, params, *args, **kwargs):
        mi_logger.debug("MyProtocol(%s).set: params=%s" % (self._channel,
                                                           str(params)))

        assert isinstance(params, dict)

        updated_params = 0
        result = {}
        for (param, value) in params.items():
            if param in self._values:
                if isinstance(value, int):
                    self._values[param] = value
                    result[param] = InstErrorCode.OK
                    updated_params += 1
                else:
                    result[param] = InstErrorCode.INVALID_PARAM_VALUE
            else:
                result[param] = InstErrorCode.INVALID_PARAMETER

#        self.announce_to_driver(DriverAnnouncement.CONFIG_CHANGE,
#                                msg="%s parameter(s) successfully set." %
#                                    updated_params)

        return result
Example #12
0
    def test_get_set(self):
        """
        Test driver parameter get/set interface including device persistence.
        TA2=-4.858579e-06
        PTCA1=-0.6603433
        TCALDATE=(8, 11, 2005)        
        """
        
        # Launch driver process.
        driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
            self.evt_port, self.dvr_mod,  self.dvr_cls)

        # Create client and start messaging.        
        driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
                                        self.evt_port)
        driver_client.start_messaging()
        time.sleep(3)

        # Configure driver for comms and transition to disconnected.
        reply = driver_client.cmd_dvr('configure', self.comms_config)
        time.sleep(2)

        # Establish devcie comms and transition to command.
        reply = driver_client.cmd_dvr('connect')
        time.sleep(2)
        
        # Get all parameters.
        get_params = [
            (SBE37Channel.CTD, SBE37Parameter.ALL)            
        ]
        reply = driver_client.cmd_dvr('get', get_params)
        time.sleep(2)
        
        # Check overall and individual parameter success. Check parameter types.
        self.assertIsInstance(reply, dict)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
                                                            float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
                                                            float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
                                                            (list, tuple))
        
        # Set up a param dict of the original values.
        old_ta2 = reply[(SBE37Channel.CTD, SBE37Parameter.TA2)]
        old_ptca1 = reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)]
        old_tcaldate = reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)]
        orig_params = {
            (SBE37Channel.CTD, SBE37Parameter.TA2): old_ta2,
            (SBE37Channel.CTD, SBE37Parameter.PTCA1): old_ptca1,
            (SBE37Channel.CTD, SBE37Parameter.TCALDATE): old_tcaldate            
        }

        # Set up a param dict of new values.
        new_ta2 = old_ta2*2
        new_ptcal1 = old_ptca1*2
        new_tcaldate = list(old_tcaldate)
        new_tcaldate[2] = new_tcaldate[2] + 1
        new_tcaldate = tuple(new_tcaldate)
        new_params = {
            (SBE37Channel.CTD, SBE37Parameter.TA2): new_ta2,
            (SBE37Channel.CTD, SBE37Parameter.PTCA1): new_ptcal1,
            (SBE37Channel.CTD, SBE37Parameter.TCALDATE): new_tcaldate
        }
        
        # Set the params to their new values.
        reply = driver_client.cmd_dvr('set', new_params)
        time.sleep(2)
        
        # Check overall success and success of the individual paramters.
        self.assertIsInstance(reply, dict)
        mi_logger.debug('set result: %s', str(reply))
        
        # Get the same paramters back from the driver.
        get_params = [
            (SBE37Channel.CTD, SBE37Parameter.TA2),
            (SBE37Channel.CTD, SBE37Parameter.PTCA1),
            (SBE37Channel.CTD, SBE37Parameter.TCALDATE)
        ]
        reply = driver_client.cmd_dvr('get', get_params)
        time.sleep(2)

        # Check success, and check that the parameters were set to the
        # new values.
        self.assertIsInstance(reply, dict)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
                                                            float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
                                                            float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
                                                            (list, tuple))
        self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
                                    new_ta2, delta=abs(0.01*new_ta2))
        self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
                                    new_ptcal1, delta=abs(0.01*new_ptcal1))
        self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
                                                            new_tcaldate)


        # Set the paramters back to their original values.        
        reply = driver_client.cmd_dvr('set', orig_params)
        self.assertIsInstance(reply, dict)
        mi_logger.debug('set result: %s', str(reply))

        # Get the parameters back from the driver.
        reply = driver_client.cmd_dvr('get', get_params)

        # Check overall and individual sucess, and that paramters were
        # returned to their original values.
        self.assertIsInstance(reply, dict)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
                                                    float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
                                                    float)
        self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
                                                    (list, tuple))
        self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
                                            old_ta2, delta=abs(0.01*old_ta2))
        self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
                                        old_ptca1, delta=abs(0.01*old_ptca1))
        self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
                                        old_tcaldate)
        
        # Disconnect driver from the device and transition to disconnected.
        reply = driver_client.cmd_dvr('disconnect', [SBE37Channel.CTD])
        time.sleep(2)
        
        # Deconfigure the driver and transition to unconfigured.
        reply = driver_client.cmd_dvr('initialize', [SBE37Channel.CTD])
        time.sleep(2)
        
        # End driver process and client messaging.
        driver_client.done()
        driver_process.wait()
def _print_dict(title, d):
    mi_logger.debug("%s:" % title)
    for item in d.items():
        mi_logger.debug("\t%s" % str(item))