Ejemplo n.º 1
0
    def take_picture(xpid):
        """
        Take the picture.

        static method, only needs the experiment ID, parameters are stored in experiment
        description json file

        :param xpid: Ecperiment ID
        :type event: string

        :returns: boolean
        :rtype: boolean
        """

        rpi = RpiModule()
        rpi.logger.info(
            'taking picture for task : %s. RpiModule obj ref : %s' %
            (xpid, rpi))
        light = rpi.light
        exp = Experiment(directory=os.path.join(Config.WORKING_DIR, xpid))

        cameras = exp.cameras
        params = exp.img_params

        #test the multiplexer
        if not rpi.selector.self_check():
            rpi.logger.error('Multiplexer failure')
            #put info in json file ..
            exp.state = "FAILED"
            exp.message = "Multiplexer error fatal error"
            exp.dump()
            return False

        #camera is used -> Experiment in progress ?
        ## wait a while ...
        retries = 0
        while retries < Config.CAM_RETRIES:
            retries += 1
            try:
                with rpi.lock.acquire():
                    rpi.logger.info('lock acquired')
                    #TURN THE LIGHTS
                    if exp.ir:
                        rpi.logger.info('turning lights ON')
                        light.state = Light.ON
                    else:
                        rpi.logger.info('turning lights OFF')
                        light.state = Light.OFF

                    rpi.logger.info('rpimodule requested cams list : %s' %
                                    cameras)

                    step = []
                    for camera in cameras:
                        rpi.logger.debug('Started image capture on cam %s.' %
                                         camera)
                        if camera in Config.CAMS:
                            instant_date = arrow.now().format(
                                'YYYY-MM-DD_HH-mm-ss')
                            #create cam folder & add cam_folder path to imagepath
                            camdir = os.path.join(exp.workdir, "%s" % camera)
                            rpi.logger.debug('# # # # # # new path %s' %
                                             camdir)
                            if not os.path.isdir(camdir):
                                os.mkdir(camdir)

                            imagepath = os.path.join(
                                camdir, '%s_%s.png' % (instant_date, camera))
                            ##CAPTURE IMAGE
                            if rpi.selector.capture(camera, imagepath, params):
                                step.append((instant_date, camera, imagepath))
                            else:
                                exp.message = "Camera %s was buissy. Skipped step" % camera
                        else:
                            rpi.logger.info(
                                'Requested camera (%s) is not present in config file. Please check config.py file.'
                                % (camera))

                    if light.state:
                        rpi.logger.info('turning lights OFF')
                        light.state = Light.OFF
                    if len(step) > 0:
                        exp.new_step(tuple(step))
                        exp.message = "OK"
                    exp.dump()
                    return True
            except Timeout:
                print(
                    "Another instance of this application currently holds the lock."
                )
            finally:
                if rpi.lock.is_locked:
                    rpi.lock.release()
                    rpi.logger.info('lock release forced')
                rpi.logger.info('lock is now free for other experiments')
        rpi.logger.error('Could not acquire cameras after %s retries.' %
                         Config.CAM_RETRIES)
        return False
Ejemplo n.º 2
0
class TestExperimentMethods(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        #expid = str(uuid.uuid1())
        now = arrow.now()

        _scheduler = getattr(self.app, 'scheduler', None)
        if _scheduler is None:
            _scheduler = BackgroundScheduler()
            self.app.scheduler = _scheduler
        if not _scheduler.running:
            _scheduler.start()

        self.tmpfolder = tempfile.mkdtemp()
        exp = {
            "desc": "Fake test XP",
            "status": "Setup",
            "ir": False,
            "cameras": [1, 2, 3, 4],
            "message": 'msg',
        }
        self.newExp = Experiment(app=self.app)
        self.newExp.from_dict(exp)
        self.newExp.workdir = os.path.join(self.tmpfolder, self.newExp.xp_id())

    def tearDown(self):
        import shutil
        shutil.rmtree(self.tmpfolder)

    def test_dump_and_load(self):
        """Dump an XP, load it. The two has to be equal
        """

        self.newExp.dump()
        otherExp = Experiment(app=self.app, directory=self.newExp.workdir)
        import shutil
        shutil.rmtree(otherExp.workdir)
        self.assertEqual(self.newExp, otherExp)

    def test_time_point_setter(self):
        """
        """
        somepath = "/tmp/%s" % self.newExp.expid
        self.newExp.new_step(4, somepath)
        #print(self.newExp.to_dict())
        self.assertEqual((4, somepath, 1),
                         (self.newExp.steps[0][1], self.newExp.steps[0][2],
                          self.newExp.steps_nb))

    def test_insert_in_scheduler(self):
        inserted = False
        now = arrow.now()
        self.newExp.start = now.format('YYYY-MM-DD HH:mm:ssZ')
        self.newExp.interval = 5
        self.newExp.end = now.shift(hours=+1).format('YYYY-MM-DD HH:mm:ssZ')

        jobid = self.newExp.insert_in_scheduler()
        myjob = self.app.scheduler.get_job(jobid)
        next_run_time = myjob.next_run_time
        if next_run_time is not None and self.newExp.expid == myjob.id:
            inserted = True

        self.assertTrue(inserted)

    def test_remove_from_scheduler(self):
        """Insert a job in schendular and remove it
        """
        now = arrow.now()
        wasin = False
        self.newExp.start = now.format('YYYY-MM-DD HH:mm:ssZ')
        self.newExp.interval = 5
        self.newExp.end = now.shift(hours=+1).format('YYYY-MM-DD HH:mm:ssZ')

        jobid = self.newExp.insert_in_scheduler()
        myjob = self.app.scheduler.get_job(jobid)

        if myjob.id in (job.id for job in self.app.scheduler.get_jobs()):
            wasin = True

        self.newExp.remove_from_scheduler()

        if myjob.id in (job.id for job in self.app.scheduler.get_jobs()):
            stillin = True
        else:
            stillin = False

        self.assertTrue(wasin and not stillin)

    def test_delete(self):
        """Test XP files remooval
        """
        deleted = False
        hadworkdir = False
        self.newExp.dump()
        if os.path.exists(self.newExp.workdir):
            hadworkdir = True

        self.newExp.delete()

        if not os.path.exists(self.newExp.workdir):
            deleted = True

        self.assertTrue(hadworkdir and deleted)