Esempio n. 1
0
class GC_start_stop_socket(object):

    def __init__(self):
        self.state = 'alive'
        self.injection_number = 0
        self.relay = Relay()
        
        self.name = 'Sigrun_GC_start_stop'
        self.socket = DataPushSocket(self.name,
                                     action='callback_direct',
                                     callback=self.callback,
                                     return_format='json',
                                     port=8502)
        self.socket.start()

    def callback(self, data):
        method_name = data.pop('method')
        method = self.__getattribute__(method_name)
        return method(**data)

    def stop(self):
        self.socket.stop()

    def start_run(self):
        self.relay.start_GC()
        print('Starting GC on '+time.ctime())
        self.run_in_progress = True
    
    def stop_run(self):
        self.relay.stop_GC()
        print('Stopping GC on '+time.ctime())
        self.run_in_progress = False
 def test_init_enqueue(self):
     """Test initialization with when action is enqueue"""
     dps = DataPushSocket(NAME, action='enqueue')
     dps.start()
     self.init_common_tests(dps, 'enqueue')
     assert(isinstance(dps.queue, Queue.Queue))
     assert(DATA[PORT]['queue'] is dps.queue)
     dps.stop()
Esempio n. 3
0
class I2CComm(object):
    """Handle I2C communication with DAC and ADC"""
    def __init__(self):
        self.measurements = {}
        self.mcp3428 = MCP3428()
        self.ad5667 = AD5667()
        self.dps = DataPushSocket(
            'large_CO2_mea_push_socket',
            action='callback_direct',
            callback=self.communicate,
            return_format='json',
        )

        # These two queues form a pair, that is used to interrupt the
        # continuous measurement of the values from the ADC to allow
        # setting the DAC and return copy the values from the ADC
        self.comm_flag = Queue()
        self.comm_return = Queue()

        self.dps.start()

    def measure(self):
        """Main measure loop (busy)"""
        while True:
            for channel in range(1, 5):
                self.measurements[channel] = self.mcp3428.read_sample(channel)
            print("Measured:", self.measurements)

            try:
                values_to_set = self.comm_flag.get(block=False)
            except Empty:
                continue

            # If we escaped the comm_flag test, we should set and enqueue current values
            if "no_voltages_to_set" not in values_to_set:
                print("Asked to set DAC values", values_to_set)
                sleep(0.01)
                self.ad5667.set_channel_A(values_to_set['A'])
                self.ad5667.set_channel_B(values_to_set['B'])
                sleep(0.01)
            self.comm_return.put(dict(self.measurements))

    def run(self):
        """Run method used to allow keyboard interrupts"""
        try:
            self.measure()
        except KeyboardInterrupt:
            self.dps.stop()

    def communicate(self, data):
        """Send the received values to be written on the DAC and return values
        from the ADC

        """
        self.comm_flag.put(data)
        # Wait until we get values back
        result = self.comm_return.get()
        return result
 def test_init_callback_direct_default(self):
     """Test initialization when action is callback_direct"""
     # Test init of callback
     dps = DataPushSocket(NAME, action='callback_direct', callback=dir)
     dps.start()
     self.init_common_tests(dps, 'callback_direct')
     assert(DATA[PORT]['callback'] is dir)
     assert(DATA[PORT]['return_format'] == 'json')
     dps.stop()
 def test_init_custom_queue(self):
     """Test initialization when action is enqueue and use custom queue"""
     queue = Queue.Queue()
     dps = DataPushSocket(NAME, action='enqueue', queue=queue)
     dps.start()
     self.init_common_tests(dps, 'enqueue')
     assert(dps.queue is queue)
     assert(DATA[PORT]['queue'] is queue)
     dps.stop()
 def test_init_callback_direct_raw(self):
     """Test initialization when action is callback_direct"""
     # Test init of callback
     dps_ = DataPushSocket(NAME, action='callback_direct', callback=dir,
                          return_format='raw')
     dps_.start()
     self.init_common_tests(dps_, 'callback_direct')
     assert DATA[PORT]['callback'] is dir
     assert DATA[PORT]['return_format'] == 'raw'
     dps_.stop()
def dps(request):
    """DataPushSocket fixture, if requested in a class that has dps_kwargs
    class variable, use those in init
    """
    if hasattr(request, 'cls') and hasattr(request.cls, 'dps_kwargs'):
        dps = DataPushSocket(NAME, **request.cls.dps_kwargs)
    else:
        dps = DataPushSocket(NAME)
    dps.start()
    yield dps
    dps.stop()
 def test_init_callback_async(self):
     """Test initialization when action is callback_async"""
     # Test init of callback
     dps = DataPushSocket(NAME, action='callback_async', callback=dir)
     dps.start()
     self.init_common_tests(dps, 'callback_async')
     assert(isinstance(dps.queue, Queue.Queue))
     assert(DATA[PORT]['queue'] is dps.queue)  
     assert(isinstance(dps._callback_thread, CallBackThread))
     assert(dps._callback_thread.callback is dir)
     dps.stop()
def class_dps(request):
    """DataPushSocket fixture

    If requested in a class that has dps_kwargs class variable, use those in init

    .. note:: This fixture lasts for the duration of a test class. It has been setup like this
       because the sockets take a long time to shut down. So in order to save time on the test
       run, we only initiate the socket once per class, but reset it in the dps fixture. It is
       the dps fixture that should be used.

    """
    if hasattr(request, 'cls') and hasattr(request.cls, 'dps_kwargs'):
        dps_ = DataPushSocket(NAME, **request.cls.dps_kwargs)
    else:
        dps_ = DataPushSocket(NAME)
    dps_.start()
    yield dps_
    dps_.stop()
Esempio n. 10
0
class I2CComm(object):
    """Handle I2C communication with DAC and ADC and use GPIO to control a valve relay"""

    def __init__(self):
        self.measurements = {}
        self.mcp3428 = MCP3428()
        #self.ad5667 = AD5667()
        self.dps = DataPushSocket(
            'large_CO2_mea_push_socket',
            action='callback_direct',
            callback=self.communicate,
            return_format='json',
        )
        
        # These two queues form a pair, that is used to interrupt the
        # continuous measurement of the values from the ADC to allow
        # setting the DAC and return copy the values from the ADC
        self.comm_flag = Queue()
        self.comm_return = Queue()

        self.relay_channel = [7]
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.relay_channel,GPIO.OUT, initial=GPIO.HIGH)

        self.dps.start()

    def measure(self):
        """Main measure loop (busy)"""
        last_print = 0
        while True:
            for channel in range(1, 5):
                self.measurements[channel] = self.mcp3428.read_sample(channel)

            now = time()
            if (now - last_print) > 10:
                print(now, "Measured:", self.measurements)
                last_print = now

            try:
                values_to_set = self.comm_flag.get(block=False)
            except Empty:
                continue

            # If we escaped the comm_flag test, we should set and enqueue current values
            # if "no_voltages_to_set" not in values_to_set:
            #     print("Asked to set DAC values", values_to_set)
            #     sleep(0.01)
            #     #self.ad5667.set_channel_A(values_to_set['A'])
            #     #self.ad5667.set_channel_B(values_to_set['B'])
            #     sleep(0.01)
            # Reads the commands about switching set the GPIO output



            if "switch anode" in values_to_set:
                print("switching to anode")
                # setup the GPIO board to use the correct channel
#                GPIO.setmode(GPIO.BOARD)
#                GPIO.setup(self.relay_channel,GPIO.OUT, initial=GPIO.HIGH)
                GPIO.output(self.relay_channel[0],GPIO.LOW)
            elif "switch cathode" in values_to_set:
                print("switching to cathode")
                GPIO.output(self.relay_channel[0],GPIO.HIGH)
                
            self.comm_return.put(dict(self.measurements))
            
    def run(self):
        """Run method used to allow keyboard interrupts"""
        try:
            self.measure()
        except KeyboardInterrupt:
            self.dps.stop()
            self.destroy()

    def destroy(self):
        GPIO.output(self.relay_channel,GPIO.HIGH)
        GPIO.cleanup()
        
    def communicate(self, data):
        """Send the received values to be written on the DAC and return values
        from the ADC

        """
        print("Received comm request")
        # Make sure there are no results hanging in the result queue
        while True:
            try:
                self.comm_return.get(block=False)
            except Empty:
                break

        print("Set comm flag")
        self.comm_flag.put(data)

        # Wait until we get values back
        result = self.comm_return.get()
        print("Got result, return")
        return result
Esempio n. 11
0
class LaserControl(object):
    """Class that controls the giant laser laser on the moon"""

    def __init__(self):
        self.settings = {'power': 100, 'focus': 100, 'target': None}
        self._state = 'idle'
        self._stop = False
        self._temperature_meas = Queue.Queue()
        
        name = 'Laser control, callback socket, for giant laser on the moon'
        self.dps = DataPushSocket(name, action='callback_direct',
                                  callback=self.callback,
                                  return_format='json')
        self.dps.start()

    def callback(self, data):
        """Callback and central control function"""
        method_name = data.pop('method')  # Don't pass the method name on
        method = self.__getattribute__(method_name)
        return method(**data)

    def update_settings(self, **kwargs):
        """Update settings"""
        for key in kwargs.keys():
            if key not in self.settings.keys():
                message = 'Not settings for key: {}'.format(key)
                raise ValueError(message)
        self.settings.update(kwargs)
        print 'Updated settings with: {}'.format(kwargs)
        return 'Updated settings with: {}'.format(kwargs)

    def state(self, state):
        """Set state"""
        self._state = state
        print 'State set to: {}'.format(state)
        return 'State set to: {}'.format(state)

    def run(self):
        """Monitor state and run temperature monitorint"""
        print 'Run started'
        while not self._stop:
            if self._state == 'active':
                self.monitor_temperature()
            time.sleep(1)
        self.dps.stop()
        print 'Run ended'

    def stop(self):
        """Stop the laser controller"""
        self._state = 'idle'
        self._stop = True
        print 'Stopped'
        return 'Stopped'

    def monitor_temperature(self):
        """Monitor the temperature"""
        while self._state == 'active':
            item = [time.strftime('%Y-%m-%d %X'), random.randint(30, 300)]
            self._temperature_meas.put(item)
            print 'At {} temperature is {}'.format(*item)
            time.sleep(1)

    def get_temperature(self):
        """Get the temperature measurements available"""
        out= []
        for _ in range(self._temperature_meas.qsize()):
            out.append(self._temperature_meas.get())
        return out
Esempio n. 12
0
class I2CComm(object):
    """Handle I2C communication with DAC and ADC"""

    def __init__(self):
        self.measurements = {}
        self.mcp3428 = MCP3428()
        #self.ad5667 = AD5667()
        self.dps = DataPushSocket(
            'large_CO2_mea_push_socket',
            action='callback_direct',
            callback=self.communicate,
            return_format='json',
        )

        # These two queues form a pair, that is used to interrupt the
        # continuous measurement of the values from the ADC to allow
        # setting the DAC and return copy the values from the ADC
        self.comm_flag = Queue()
        self.comm_return = Queue()

        self.dps.start()

    def measure(self):
        """Main measure loop (busy)"""
        last_print = 0
        while True:
            for channel in range(1, 5):
                self.measurements[channel] = self.mcp3428.read_sample(channel)

            now = time()
            if (now - last_print) > 10:
                print(now, "Measured:", self.measurements)
                last_print = now

            try:
                values_to_set = self.comm_flag.get(block=False)
            except Empty:
                continue

            # If we escaped the comm_flag test, we should set and enqueue current values
            if "no_voltages_to_set" not in values_to_set:
                print("Asked to set DAC values", values_to_set)
                sleep(0.01)
                #self.ad5667.set_channel_A(values_to_set['A'])
                #self.ad5667.set_channel_B(values_to_set['B'])
                sleep(0.01)
            self.comm_return.put(dict(self.measurements))

    def run(self):
        """Run method used to allow keyboard interrupts"""
        try:
            self.measure()
        except KeyboardInterrupt:
            self.dps.stop()

    def communicate(self, data):
        """Send the received values to be written on the DAC and return values
        from the ADC

        """
        print("Received comm request")
        # Make sure there are no results hanging in the result queue
        while True:
            try:
                self.comm_return.get(block=False)
            except Empty:
                break

        print("Set comm flag")
        self.comm_flag.put(data)

        # Wait until we get values back
        result = self.comm_return.get()
        print("Got result, return")
        return result
class LaserControl(object):
    """Class that controls the giant laser laser on the moon"""
    def __init__(self):
        self.settings = {'power': 100, 'focus': 100, 'target': None}
        self._state = 'idle'
        self._stop = False
        self._temperature_meas = Queue.Queue()

        name = 'Laser control, callback socket, for giant laser on the moon'
        self.dps = DataPushSocket(name,
                                  action='callback_direct',
                                  callback=self.callback,
                                  return_format='json')
        self.dps.start()

    def callback(self, data):
        """Callback and central control function"""
        method_name = data.pop('method')  # Don't pass the method name on
        method = self.__getattribute__(method_name)
        return method(**data)

    def update_settings(self, **kwargs):
        """Update settings"""
        for key in kwargs.keys():
            if key not in self.settings.keys():
                message = 'Not settings for key: {}'.format(key)
                raise ValueError(message)
        self.settings.update(kwargs)
        print 'Updated settings with: {}'.format(kwargs)
        return 'Updated settings with: {}'.format(kwargs)

    def state(self, state):
        """Set state"""
        self._state = state
        print 'State set to: {}'.format(state)
        return 'State set to: {}'.format(state)

    def run(self):
        """Monitor state and run temperature monitorint"""
        print 'Run started'
        while not self._stop:
            if self._state == 'active':
                self.monitor_temperature()
            time.sleep(1)
        self.dps.stop()
        print 'Run ended'

    def stop(self):
        """Stop the laser controller"""
        self._state = 'idle'
        self._stop = True
        print 'Stopped'
        return 'Stopped'

    def monitor_temperature(self):
        """Monitor the temperature"""
        while self._state == 'active':
            item = [time.strftime('%Y-%m-%d %X'), random.randint(30, 300)]
            self._temperature_meas.put(item)
            print 'At {} temperature is {}'.format(*item)
            time.sleep(1)

    def get_temperature(self):
        """Get the temperature measurements available"""
        out = []
        for _ in range(self._temperature_meas.qsize()):
            out.append(self._temperature_meas.get())
        return out