在不同的Express函数之间调用新的对象函数?

时间:2014-04-28 22:28:04

标签: node.js class oop express raspberry-pi

我正在使用Raspberry Pi和Raspberry Pi相机模块构建延时相机Web应用程序。到目前为止,我已经构建了一个Web应用程序(使用NodeJS,Express,AngularJS和BootStrap 3),可以使用开源NodeJS模块(https://www.npmjs.org/package/raspicam)与Raspberry Camera Module进行交互。

我有一个名为"设置"的全局变量。每当用户更改相机设置时,它将始终更改:

var setting = {
    mode: "timelapse",
    output: "public/images/image%d.jpg", // image1, image2, image3, etc...
    encoding: "jpg",
    timelapse: 3000, // take a picture every 3 seconds
    timeout: 12000 // take a total of 4 pictures over 12 seconds
}

我在Express中有三个功能可以:

设置相机设置

exports.setCamera = function(req, res) {
    setting = {
        mode: req.body.mode,
        output: req.body.output,
        encoding: req.body.encoding,
        timelapse: req.body.timelapse,
        timeout: req.body.timeout
    }
    res.json(setting, 200);
    console.log('SET CAMERA - ' + JSON.stringify(setting));
}

启动相机

exports.startCamera = function(req, res) {
    camera = new RaspiCam(setting);
    camera.on("start", function( err, timestamp ){
      console.log("timelapse started at " + timestamp);
    });

    camera.on("read", function( err, timestamp, filename ){
      console.log("timelapse image captured with filename: " + filename);
    });

    camera.on("exit", function( timestamp ){
      console.log("timelapse child process has exited");
      res.json(setting, 200);
    });

    camera.on("stop", function( err, timestamp ){
      console.log("timelapse child process has been stopped at " + timestamp);
    });

    camera.start();

    setTimeout(function(){
      camera.stop();
    }, setting.timeout + 1000);

    console.log('START CAMERA - ' + JSON.stringify(setting));
}

停止相机

exports.stopCamera = function(req, res) {
    camera.stop();
    res.json(setting, 200);
    console.log('STOP CAMERA - ' + JSON.stringify(setting));
}

正如您在" startCamera"中看到的那样函数,我正在创建一个名为" camera"的新RaspiCam对象。传入全局变量"设置" (总是可以改变)。创建相机对象时,我也创建"开始","读","存在","停止"它的功能。问题是因为我没有将相机对象设置为全局变量,所以当用户决定在会话期间中途点击停止时," stopCamera"函数被调用,但它不知道camera.stop()是什么,并说它是未定义的。有没有办法我可以允许" stopCamera"函数知道camera.stop()是什么(在" startCamera"函数中创建的)?

很抱歉,如果这令人困惑,我也不知道如何描述我的问题...... :(

1 个答案:

答案 0 :(得分:0)

我认为你的架构有问题,但问题的简单解决方法是检查相机对象是否已初始化。

exports.stopCamera = function(req, res) {
    if(camera && typeof(camera.stop) == "function") {
        camera.stop();
        console.log('STOP CAMERA - ' + JSON.stringify(setting));    
    }

    res.json(setting, 200); 
}
相关问题