Esempio n. 1
0
class GenericPyroLabDevice(HardwareDevice):
    """
    A class that passes all function calls on to the PyroLab driver.

    This class is used to pass all function calls and attribute requests on to
    a nonstandard PyroLab driver. This is useful for devices that are not
    implemented or described by the standard AutoGator API, such as custom,
    homebuilt hardware.

    Parameters
    ----------
    pyroname : str
        The name of the PyroLab object as registered with the nameserver.
    ns_host : str, optional
        The hostname of the PyroLab nameserver (default "localhost").
    ns_port : int, optional
        The port of the PyroLab nameserver (default "9090").
    """
    def __init__(self,
                 pyroname: str = "",
                 ns_host: str = "localhost",
                 ns_port: int = 9090) -> None:
        super().__init__(pyroname)
        with locate_ns(host=ns_host, port=ns_port) as ns:
            self.driver = Proxy(ns.lookup(pyroname))
            self.driver.autoconnect()

    def __getattr__(self, __name: str) -> Any:
        return self.driver.__getattr__(__name)
Esempio n. 2
0
    def init_camera(self):
        ns = locate_ns(host="camacholab.ee.byu.edu")
        objs = str(ns.list())
        while (True):
            temp_str = objs[objs.find('\'') + 1:-1]
            temp_obj = temp_str[0:temp_str.find('\'')]
            if (temp_obj[0:5] == "UC480"):
                temp_ser_no = int(temp_obj[6:len(temp_obj)])
                if (temp_ser_no == self.ser_num):
                    cam_str = temp_obj
            if (objs.find(',') == -1):
                break
            objs = objs[objs.find(',') + 1:-1]
        try:
            cam_str
        except NameError:
            raise Exception("Camera with serial number " + str(self.ser_num) +
                            " could not be found")
        self.cam = Proxy(ns.lookup(cam_str))

        self.cam.start(exposure=65)
        ip_address = self.cam.start_capture(self.color)
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect((str(ip_address), PORT))

        self.time_s = 0
        self.frame_rate = 0
        self.count = -1
Esempio n. 3
0
 def __init__(self,
              pyroname: str = "",
              ns_host: str = "localhost",
              ns_port: int = 9090) -> None:
     super().__init__(pyroname)
     with locate_ns(host=ns_host, port=ns_port) as ns:
         self.driver = Proxy(ns.lookup(pyroname))
         self.driver.autoconnect()
Esempio n. 4
0
    def init_camera(self):
        ns = locate_ns(host="camacholab.ee.byu.edu")
        objs = str(ns.list())
        while (True):
            temp_str = objs[objs.find('\'') + 1:-1]
            temp_obj = temp_str[0:temp_str.find('\'')]
            if (temp_obj[0:5] == "UC480"):
                temp_ser_no = int(temp_obj[6:len(temp_obj)])
                if (temp_ser_no == SER_NUMBER):
                    cam_str = temp_obj
            if (objs.find(',') == -1):
                break
            objs = objs[objs.find(',') + 1:-1]
        try:
            cam_str
        except NameError:
            raise Exception("Camera with serial number " + str(SER_NUMBER) +
                            " could not be found")

        self.cam = Proxy(ns.lookup(cam_str))

        self.cam.start(exposure=65)
        ip_address = self.cam.start_capture(COLOR)
        print("IP: " + str(ip_address))
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect((str(ip_address), PORT))

        now = datetime.now()
        dt_string = now.strftime("rec_" + str(SER_NUMBER) +
                                 "/%Y-%m-%d_%H-%M-%S.avi")
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        self.out = cv2.VideoWriter(dt_string, fourcc, 4.0, (640, 512))

        self.time_s = 0
        self.frame_rate = 0
        self.count = -1
        self.vid = cv2.VideoCapture("test.mp4")
Esempio n. 5
0
def get_daemon(abort=True, suppress_reload_message=False) -> PyroLabDaemon:
    if LOCKFILE.exists():
        ii = InstanceInfo.parse_file(LOCKFILE)
        DAEMON = Proxy(ii.uri)
        if not suppress_reload_message and RUNTIME_CONFIG.exists():
            if RUNTIME_CONFIG.stat().st_mtime < USER_CONFIG_FILE.stat(
            ).st_mtime:
                typer.secho(
                    "The configuration file has been updated. Run 'pyrolab reload' for changes to take effect.",
                    fg=typer.colors.RED)
        return DAEMON
    elif abort:
        typer.secho("PyroLab daemon is not running! Try 'pyrolab up' first.",
                    fg=typer.colors.RED)
        raise typer.Abort()
    else:
        return None
Esempio n. 6
0
class MyVideoCapture:
    def __init__(self, video_source=0, ser_num=0):
        self.vs = video_source
        if (video_source == 0):
            # Open the video source
            self.vid = cv2.VideoCapture(video_source)
            if not self.vid.isOpened():
                raise ValueError("Unable to open video source", video_source)

            # Get video source width and height
            self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
            self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
        else:
            self.live = False
            self.color = False
            self.stop_video = threading.Event()
            self.ser_num = ser_num
            self.exposure = 3.16
            self.filter = (255, 255, 255)
            self.width = 640
            self.height = 512
            self.terminate = False
            self.rec_state = 0
            self.cap_state = 0
            self.init_camera()
            self.stopEvent = threading.Event()
            self.thread = threading.Thread(target=self.videoLoop, args=())
            self.thread.start()
            while (True):
                time.sleep(0.001)
                if (self.live == True):
                    break

    def set_filter(self, filter):
        if (filter != None):
            self.filter = filter

    def set_color(self, color):
        self.cam.color_gray(color)

    def set_exposure(self, exposure):
        self.exposure = (pow(10.0, (exposure + 20.0) / 10.0)) / 1000.0
        self.cam.set_exposure(self.exposure)

    def capture(self, directory):
        if not os.path.exists(directory + "/images"):
            os.makedirs(directory + "/images")
        self.cap_state = 1
        self.directory = directory

    def set_rec_state(self, state, directory):
        if (state == 1):
            if not os.path.exists(directory + "/videos"):
                os.makedirs(directory + "/videos")
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            self.out = cv2.VideoWriter(
                directory + "/videos/video-" +
                time.strftime("%d-%m-%Y-%H-%M-%S") + ".avi", fourcc,
                self.frame_rate, (640, 512))
        else:
            self.out.release()
        self.rec_state = state

    def init_camera(self):
        ns = locate_ns(host="camacholab.ee.byu.edu")
        objs = str(ns.list())
        while (True):
            temp_str = objs[objs.find('\'') + 1:-1]
            temp_obj = temp_str[0:temp_str.find('\'')]
            if (temp_obj[0:5] == "UC480"):
                temp_ser_no = int(temp_obj[6:len(temp_obj)])
                if (temp_ser_no == self.ser_num):
                    cam_str = temp_obj
            if (objs.find(',') == -1):
                break
            objs = objs[objs.find(',') + 1:-1]
        try:
            cam_str
        except NameError:
            raise Exception("Camera with serial number " + str(self.ser_num) +
                            " could not be found")
        self.cam = Proxy(ns.lookup(cam_str))

        self.cam.start(exposure=65)
        ip_address = self.cam.start_capture(self.color)
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect((str(ip_address), PORT))

        self.time_s = 0
        self.frame_rate = 0
        self.count = -1

    def bayer_convert(self, bayer):
        if (self.color):
            ow = (bayer.shape[0] // 4) * 4
            oh = (bayer.shape[1] // 4) * 4

            R = bayer[0::2, 0::2]
            B = bayer[1::2, 1::2]
            G0 = bayer[0::2, 1::2]
            G1 = bayer[1::2, 0::2]
            G = G0[:oh, :ow] // 2 + G1[:oh, :ow] // 2
            bayer_R = np.array(R, dtype=np.uint8).reshape(512, 640)
            bayer_G = np.array(G, dtype=np.uint8).reshape(512, 640)
            bayer_B = np.array(B, dtype=np.uint8).reshape(512, 640)

            dStack = np.clip(
                np.dstack(
                    (bayer_B * (BRIGHTNESS / 5), bayer_G * (BRIGHTNESS / 5),
                     bayer_R * (BRIGHTNESS / 5))), 0, 255).astype('uint8')
        else:
            bayer_T = np.array(bayer, dtype=np.uint8).reshape(512, 640)
            dStack = np.clip((np.dstack(
                ((bayer_T * (self.filter[2] / 255)) * (BRIGHTNESS / 5),
                 (bayer_T * (self.filter[1] / 255)) * (BRIGHTNESS / 5),
                 (bayer_T * (self.filter[0] / 255)) * (BRIGHTNESS / 5)))), 0,
                             255).astype('uint8')
            #dStack = np.clip((np.dstack(((0.469 + bayer_T*0.75 - (bayer_T^2)*0.003)*(BRIGHTNESS/5),(bayer_T*0.95)*(BRIGHTNESS/5),(0.389 + bayer_T*1.34 - (bayer_T^2)*0.004)*(BRIGHTNESS/5)))),0,255).astype('uint8')
        #dStack = np.clip(np.dstack((bayer,bayer,bayer)),0,255).astype('uint8')
        return dStack

    def videoLoop(self):
        while not self.stop_video.is_set():
            if (self.count >= 0):
                t = time.time() - self.time_s
                self.frame_rate = (self.frame_rate * self.count +
                                   1 / t) / (self.count + 1)

            self.time_s = time.time()
            if (self.count < 50):
                self.count = self.count + 1
            else:
                self.count = 1

            msg = b''
            new_msg = True
            msg_len = None
            imList = None
            while True:
                if new_msg:
                    sub_msg = self.clientsocket.recv(HEADERSIZE)
                    msg_len = int((sub_msg[:HEADERSIZE]))
                    new_msg = False
                else:
                    sub_msg = self.clientsocket.recv(32800)
                    msg += sub_msg
                    if len(msg) == msg_len:
                        imList = pickle.loads(msg)
                        break

            if (imList.size == 327680):
                self.color = False
                self.count = 0
            else:
                self.color = True
                self.count = 0
            dStack = self.bayer_convert(imList)

            if (self.cap_state == 1):
                cv2.imwrite(
                    self.directory + "/images/frame-" +
                    time.strftime("%d-%m-%Y-%H-%M-%S") + ".jpg", dStack)
                self.cap_state = 0

            if (self.rec_state == 1):
                self.out.write(dStack)

            self.frame = cv2.cvtColor(dStack, cv2.COLOR_BGR2RGB)

            if (self.terminate == True):
                self.clientsocket.send(b'b')
                self.live = False
                break
            self.clientsocket.send(b'g')
            self.live = True

    def get_frame(self):
        if (self.vs == 0):
            if self.vid.isOpened():
                ret, frame = self.vid.read()
                if ret:
                    # Return a boolean success flag and the current frame converted to BGR
                    return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                else:
                    return (ret, None)
            else:
                return (ret, None)
        else:
            return (True, self.frame)

    # Release the video source when the object is destroyed
    def __del__(self):
        if (self.vs == 0):
            if self.vid.isOpened():
                self.vid.release()
        else:
            self.terminate = True
            while (True):
                time.sleep(0.001)
                if (self.live == False):
                    break
            self.cam.close()
            self.stop_video.set()
            try:
                self.out.release()
            except AttributeError:
                pass
Esempio n. 7
0
class PhotoBoothApp:
    def __init__(self):
        # store the video stream object and output path, then initialize
        # the most recently read frame, thread for reading frames, and
        # the thread stop event
        self.outputPath = "C:/Users/hilld/Desktop"
        self.frame = None
        self.thread = None
        self.stopEvent = None

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None

        # create a button, that when pressed, will take the current
        # frame and save it to file
        btn = tki.Button(self.root,
                         text="Snapshot!",
                         command=self.takeSnapshot)
        btn.pack(side="bottom", fill="both", expand="yes", padx=10, pady=10)

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.init_camera()
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

        # set a callback to handle when the window is closed
        self.root.wm_title("PyImageSearch PhotoBooth")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose)

    def clear(self):
        for widget in self.root.winfo_children():
            widget.destroy()

    def bayer_convert(self, bayer):
        if (COLOR):
            ow = (bayer.shape[0] // 4) * 4
            oh = (bayer.shape[1] // 4) * 4

            R = bayer[0::2, 0::2]
            B = bayer[1::2, 1::2]
            G0 = bayer[0::2, 1::2]
            G1 = bayer[1::2, 0::2]
            G = G0[:oh, :ow] // 2 + G1[:oh, :ow] // 2
            bayer_R = np.array(R, dtype=np.uint8).reshape(512, 640)
            bayer_G = np.array(G, dtype=np.uint8).reshape(512, 640)
            bayer_B = np.array(B, dtype=np.uint8).reshape(512, 640)

            dStack = np.clip(
                np.dstack(
                    (bayer_B * (BRIGHTNESS / 5), bayer_G * (BRIGHTNESS / 5),
                     bayer_R * (BRIGHTNESS / 5))), 0, 255).astype('uint8')
        else:
            bayer_T = np.array(bayer, dtype=np.uint8).reshape(512, 640)
            dStack = np.clip((np.dstack(
                ((0.469 + bayer_T * 0.75 - (bayer_T ^ 2) * 0.003) *
                 (BRIGHTNESS / 5), (bayer_T * 0.95) * (BRIGHTNESS / 5),
                 (0.389 + bayer_T * 1.34 -
                  (bayer_T ^ 2) * 0.004) * (BRIGHTNESS / 5)))), 0,
                             255).astype('uint8')
        #dStack = np.clip(np.dstack((bayer,bayer,bayer)),0,255).astype('uint8')
        return dStack

    def init_camera(self):
        ns = locate_ns(host="camacholab.ee.byu.edu")
        objs = str(ns.list())
        while (True):
            temp_str = objs[objs.find('\'') + 1:-1]
            temp_obj = temp_str[0:temp_str.find('\'')]
            if (temp_obj[0:5] == "UC480"):
                temp_ser_no = int(temp_obj[6:len(temp_obj)])
                if (temp_ser_no == SER_NUMBER):
                    cam_str = temp_obj
            if (objs.find(',') == -1):
                break
            objs = objs[objs.find(',') + 1:-1]
        try:
            cam_str
        except NameError:
            raise Exception("Camera with serial number " + str(SER_NUMBER) +
                            " could not be found")

        self.cam = Proxy(ns.lookup(cam_str))

        self.cam.start(exposure=65)
        ip_address = self.cam.start_capture(COLOR)
        print("IP: " + str(ip_address))
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect((str(ip_address), PORT))

        now = datetime.now()
        dt_string = now.strftime("rec_" + str(SER_NUMBER) +
                                 "/%Y-%m-%d_%H-%M-%S.avi")
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        self.out = cv2.VideoWriter(dt_string, fourcc, 4.0, (640, 512))

        self.time_s = 0
        self.frame_rate = 0
        self.count = -1
        self.vid = cv2.VideoCapture("test.mp4")

    def videoLoop(self):
        root = tki.Tk()
        while (True):
            self.clear()
            if (self.count >= 0):
                t = time.time() - self.time_s
                self.frame_rate = (self.frame_rate * self.count +
                                   1 / t) / (self.count + 1)

            self.time_s = time.time()
            self.count = self.count + 1

            msg = b''
            new_msg = True
            msg_len = None
            imList = None
            while True:
                if new_msg:
                    sub_msg = self.clientsocket.recv(HEADERSIZE)
                    msg_len = int((sub_msg[:HEADERSIZE]))
                    new_msg = False
                else:
                    sub_msg = self.clientsocket.recv(32800)
                    msg += sub_msg
                    if len(msg) == msg_len:
                        imList = pickle.loads(msg)
                        break

            dStack = self.bayer_convert(imList)

            #frame = Image.fromarray(dStack)
            self.out.write(dStack)

            ret, frame = self.vid.read()
            print(ret)

            img_1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image_mid = Image.fromarray(img_1)
            image = ImageTk.PhotoImage(image=image_mid)
            image.image = image_mid

            # if the panel is not None, we need to initialize it
            if self.panel is None:
                self.panel = tki.Label(image=image)
                self.panel.image = image
                self.panel.pack(side="left", padx=10, pady=10)

            # otherwise, simply update the panel
            else:
                self.panel.configure(image=image)
                self.panel.image = image

            cv2.imshow('scope', dStack)
            keyCode = cv2.waitKey(1)

            if cv2.getWindowProperty('scope', cv2.WND_PROP_VISIBLE) < 1:
                self.clientsocket.send(b'b')
                break
            self.clientsocket.send(b'g')

    def takeSnapshot(self):
        # grab the current timestamp and use it to construct the
        # output path
        ts = datetime.datetime.now()
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))
        p = os.path.sep.join((self.outputPath, filename))

        # save the file
        cv2.imwrite(p, self.frame.copy())
        print("[INFO] saved {}".format(filename))

    def onClose(self):
        # set the stop event, cleanup the camera, and allow the rest of
        # the quit process to continue
        print("[INFO] closing...")
        self.stopEvent.set()
        self.root.quit()
Esempio n. 8
0
# -*- coding: utf-8 -*-
#
# Copyright © PyroLab Project Contributors
# Licensed under the terms of the GNU GPLv3+ License
# (see pyrolab/__init__.py for details)
"""
Using a lockable service
------------------------


"""

from pyrolab.api import locate_ns, Proxy

ns = locate_ns(host="localhost")
uri = ns.lookup("test.SampleAutoconnectInstrument")

# Note that proxies are not connected until the first method call is made.
# This means that the following two lines set up the proxies without actually
# connecting to the remote objects.
service = Proxy(uri)

resp = service.autoconnect()
print(type(resp), resp)

resp = service.do_something()
print(type(resp), resp)
Esempio n. 9
0
# -*- coding: utf-8 -*-
#
# Copyright © PyroLab Project Contributors
# Licensed under the terms of the GNU GPLv3+ License
# (see pyrolab/__init__.py for details)

"""
2-Way SSL Server
----------------

...
"""

from pyrolab.api import config, locate_ns, Proxy
config.reset()

ns = locate_ns(host="localhost")
uri = ns.lookup("test.SampleService")

with Proxy(uri) as service:
    resp = service.echo("Hello, server!")
    print(type(resp), resp)

    resp = service.delayed_echo("This response will be delayed by 2 seconds.", 2)
    print(type(resp), resp)

    resp = service.multiply(4, 5, 100)
    print(type(resp), resp)
Esempio n. 10
0
folderPath = Path(Path.cwd(), folderName)
print("Saving data to {} in current directory.".format(folderName))
if not os.path.exists(folderPath):
    print("Creating {} directory.".format(folderName))
    os.makedirs(folderPath)

# ---------------------------------------------------------------------------- #
# Initialize Devices
# ---------------------------------------------------------------------------- #
# Initialize Laser
print("Initializing laser.")
try:
    # Remote Computer via PyroLab
    from pyrolab.api import locate_ns, Proxy
    ns = locate_ns(host="camacholab.ee.byu.edu")
    laser = Proxy(ns.lookup("lasers.TSL550"))
except:
    # Local Computer
    laser = TSL550("COM4")

laser.on()
laser.power_dBm(power_dBm)
laser.open_shutter()
laser.sweep_set_mode(continuous=True,
                     twoway=True,
                     trigger=False,
                     const_freq_step=False)
print("Enabling laser's trigger output.")
laser.trigger_enable_output()
triggerMode = laser.trigger_set_mode("Step")
triggerStep = laser.trigger_set_step(trigger_step)
Esempio n. 11
0
# Copyright © PyroLab Project Contributors
# Licensed under the terms of the GNU GPLv3+ License
# (see pyrolab/__init__.py for details)
"""
Instance Mode Client
--------------------

...
"""

from pyrolab.api import config, locate_ns, Proxy
config.reset()

print("\n-----PERCALL (different number possible every time)-----")
print("..Proxy 1..")
with Proxy("PYRONAME:instance.percall") as p:
    print(p.whoami())
    print(p.whoami())
print("..Proxy 2..")
with Proxy("PYRONAME:instance.percall") as p:
    print(p.whoami())
    print(p.whoami())

print("\n-----SESSION (same ID within session)-----")
print("..Proxy 1..")
with Proxy("PYRONAME:instance.session") as p:
    print(p.whoami())
    print(p.whoami())
print("..Proxy 2..")
with Proxy("PYRONAME:instance.session") as p:
    print(p.whoami())
Esempio n. 12
0
class Z825BLinearStage(LinearStageBase):
    """
    A linear motor.

    Parameters
    ----------
    pyroname : str
        The name of the PyroLab object as registered with the nameserver.
    ns_host : str, optional
        The hostname of the PyroLab nameserver (default "localhost").
    ns_port : int, optional
        The port of the PyroLab nameserver (default "9090").
    """
    def __init__(self,
                 pyroname: str = "",
                 ns_host: str = "localhost",
                 ns_port: int = 9090) -> None:
        super().__init__(pyroname)
        with locate_ns(host=ns_host, port=ns_port) as ns:
            self.driver = Proxy(ns.lookup(pyroname))
            self.driver.autoconnect()
        self._step_size = None

    @property
    def step_size(self) -> float:
        """The jog step size in mm."""
        return self._step_size

    @step_size.setter
    def step_size(self, step_size: float) -> None:
        if step_size != self._step_size:
            self.driver._pyroClaimOwnership()
            self.driver.jog_step_size = step_size
            self._step_size = step_size

    def move_to(self, position: float) -> None:
        """
        Moves to a new position.

        This motor adjusts for backlash; a given position will always be
        approached from the "negative" direction. That may require overshooting
        the commanded position in order to always approach it again from a
        consistent direction.

        If stepping in short steps, it is therefore most efficient to step from
        negative to positive values to avoid backlash adjustments on each step.

        Parameters
        ----------
        position : float
            The new position to move to.
        """
        self.driver._pyroClaimOwnership()
        if self._requires_backlash_adjustment(position):
            self.driver.move_to(position - (self.driver.backlash * 1.5))
        self.driver.move_to(position)

    def move_by(self, distance: float) -> None:
        """
        Jogs the motor by a fixed distance.

        Parameters
        ----------
        distance : float
            The distance to move the motor. A positive value will move the
            motor forward, and a negative value will move the motor backwards.
        """
        self.driver._pyroClaimOwnership()
        if np.abs(distance) != self.step_size:
            self.step_size = np.abs(distance)
        if distance > 0:
            self.driver.jog("forward")
        else:
            self.driver.jog("backward")

    def move_cont(self, direction: str) -> None:
        """
        Starts a continuous move in the specified direction.

        Parameters
        ----------
        direction : str
            The direction to move the motor, either "forward" or "backward".
        """
        self.driver._pyroClaimOwnership()
        self.driver.move_continuous(direction)

    def _requires_backlash_adjustment(self, position: float) -> bool:
        """
        Determine if the new position command needs to compensate for backlash.

        The ThorLabs linear stages have a small backlash distance. To ensure
        as accurate a reposition as possible when moving to the same location
        multiple times, the motor will always approach the position from the 
        same direction. This function determines whether that requires 
        overshooting the current position before reapproaching.

        Parameters
        ----------
        position : float
            The position to move to.

        Returns
        -------
        bool
            Whether backlash compensation is required.
        """
        if position < self.get_position():
            return True
        return False

    def stop(self) -> None:
        """
        Stop all motion.
        """
        self.driver._pyroClaimOwnership()
        self.driver.stop()

    def get_position(self) -> float:
        """
        Get the current position in millimeters.
        """
        self.driver._pyroClaimOwnership()
        return self.driver.get_position()

    def home(self) -> None:
        """
        Home the motor.
        """
        self.driver._pyroClaimOwnership()
        self.driver.go_home()

    def status(self) -> int:
        """
        Returns a nonzero value if the motor is busy.
        """
        pass
Esempio n. 13
0
class TSL550Laser(LaserBase):
    """
    A laser.

    Parameters
    ----------
    pyroname : str
        The name of the PyroLab object as registered with the nameserver.
    ns_host : str, optional
        The hostname of the PyroLab nameserver (default "localhost").
    ns_port : int, optional
        The port of the PyroLab nameserver (default "9090").
    """
    def __init__(self,
                 pyroname: str = "",
                 ns_host: str = "localhost",
                 ns_port: int = 9090):
        super().__init__(pyroname)
        with locate_ns(host=ns_host, port=ns_port) as ns:
            self.driver = Proxy(ns.lookup(pyroname))
            self.driver.autoconnect()

    def on(self, block=False) -> None:
        """
        Turn on the laser.

        If the laser diode is off, there is a warm-up time before the laser
        diode is ready. If block is True, this function will block until the
        warm-up time is complete.

        Parameters
        ----------
        block : bool, optional
            Whether to block until the warm-up time is complete (default False).
        """
        self.driver._pyroClaimOwnership()
        if self.driver.status()[0] != '-':
            self.driver.on()
            if block:
                while self.driver.status()[0] != '-':
                    time.sleep(5.0)
        self.driver.open_shutter()

    def off(self, diode: bool = True) -> None:
        """
        Turns off laser output by closing the shutter and optionally turning off the diode.

        Parameters
        ----------
        diode : bool, optional
            Whether to turn off the diode. If False, the laser diode will be
            turned off. There is a warm-up period to turn the laser back on if
            the diode has been turned off. If True, the laser diode will be
            left on but the shutter will be closed.
        """
        self.driver._pyroClaimOwnership()
        self.driver.close_shutter()
        if not diode:
            self.driver.off()

    def power(self, power: float) -> None:
        """
        Sets the laser power in dBm.

        Parameters
        ----------
        power : float
            The power to set the laser to.
        """
        self.driver._pyroClaimOwnership()
        self.driver.power_dBm(power)

    def wavelength(self, wavelength: float) -> None:
        """
        Sets the laser wavelength in nm.

        Parameters
        ----------
        wavelength : float
            The wavelength to set the laser to.
        """
        self.driver._pyroClaimOwnership()
        self.driver.wavelength(wavelength)

    def sweep(self, num: int = 1) -> None:
        """
        Starts the configured wavelength sweep.

        Parameters
        ----------
        num : int, optional
            The number of times to run the wavelength sweep (default 1).
        """
        self.driver._pyroClaimOwnership()
        self.driver.sweep_start(num)

    def sweep_wavelength(self,
                         wl_start: float = 1500,
                         wl_stop: float = 1630,
                         duration: float = 2,
                         number: int = 1):
        """
        Convenience function to run a continuous wavelength sweep.

        Parameters
        ----------
        wl_start : float, optional
            The starting wavelength (default 1500).
        wl_stop : float, optional
            The ending wavelength (default 1630).
        duration : float, optional
            The duration of the sweep (default 2).
        number : int, optional
            The number of times to run the sweep (default 1).
        """
        self.driver._pyroClaimOwnership()
        self.driver.sweep_wavelength(start=wl_start,
                                     stop=wl_stop,
                                     duration=duration,
                                     number=number)

    def sweep_set_mode(self,
                       continuous: bool = True,
                       twoway: bool = True,
                       trigger: bool = False,
                       const_freq_step: bool = False) -> None:
        """
        Sets the sweep mode.

        Parameters
        ----------
        continuous : bool
            Continuous (``True``, default) or stepwise (``False``).
        twoway : bool
            Two-way (``True``, default) or one-directional with reset
            (``False``).
        trigger : bool
            Start on external trigger (defaults to ``False``).
        const_freq_step : bool
            Constant frequency interval, requires stepwise mode (defaults to
            ``False``).
        """
        self.driver._pyroClaimOwnership()
        self.driver.sweep_set_mode(
            continuous=continuous,
            twoway=twoway,
            trigger=trigger,
            const_freq_step=const_freq_step,
        )

    def set_trigger(self, mode: str, step: float) -> None:
        """
        Enables trigger output.

        The output trigger can be set to fire at the start of a wavelength
        sweep, at the end of a sweep, or at a fixed step. Valid step range is
        0.004 - 160 nm with a minimum step of 0.0001 nm.

        Parameters
        ----------
        mode : str
            The trigger mode. One of: “None”, “Stop”, “Start”, “Step”.
        step : float
            The trigger step size, in nanometers.
        """
        self.driver._pyroClaimOwnership()
        self.driver.trigger_enable_output()
        triggerMode = self.driver.trigger_set_mode(mode)
        triggerStep = self.driver.trigger_step(step)
        return triggerMode, triggerStep

    def wavelength_logging(self) -> None:
        """
        Downloads the wavelength log.

        Returns
        -------
        list
            The last wavelength log.
        """
        self.driver._pyroClaimOwnership()
        return self.driver.wavelength_logging()
Esempio n. 14
0
# -*- coding: utf-8 -*-
#
# Copyright © PyroLab Project Contributors
# Licensed under the terms of the GNU GPLv3+ License
# (see pyrolab/__init__.py for details)
"""
Kinesis KCube Driver Example
============================

This example demonstrates the use of the Thorlabs KCube DC Servo controlling a 
Z825B translational stage using PyroLab. 
"""

from pyrolab.api import NameServerConfiguration, Proxy, locate_ns

nscfg = NameServerConfiguration(host="yourdomain.com")
nscfg.update_pyro_config()

# Be considerate; don't stay connected to the nameserver too long.
with locate_ns() as ns:
    motor = Proxy(ns.lookup("Z825B_PyroName"))

motor.autoconnect()
print(motor.get_position())
motor.close()
Esempio n. 15
0
"""
Using a lockable service
------------------------


"""

from pyrolab.api import locate_ns, Proxy

ns = locate_ns(host="localhost")
uri = ns.lookup("test.SampleService")

# Note that proxies are not connected until the first method call is made.
# This means that the following two lines set up the proxies without actually
# connecting to the remote objects.
service1 = Proxy(uri)
service2 = Proxy(uri)

resp = service1.echo("Hello, server!")
print(type(resp), resp)

resp = service1.delayed_echo("This response will be delayed by 2 seconds.", 2)
print(type(resp), resp)

resp = service1.multiply(4, 5, 100)
print(type(resp), resp)

# If two Proxies connect before an object is locked, both have access.
# Locking an object only blocks *subsequent* connection requests.

service1.lock()