如何在javascript函数中调用对象?

时间:2019-02-07 19:23:20

标签: javascript electron

这是我的代码:

function getIPAddress(url) {
    var v4 = '[\\d]{1-3}';
    var v4d = '\\.';
    var v4complete = v4+v4d+v4+v4d+v4+v4d+v4
    var v6 = '[\\da-fA-F]{0-4}';
    var v6d = ':';
    var v6complete = v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6;
    var regex = new RegExp('(' + v4complete + '(\\:\d+){0,1}|'
                            + '::|::1|'
                            + '\\[::\\]:\\d+|\\[::1\\]|'
                            + v6complete + '|'
                            + '\\[' + v6complete + '\\]' + ')', 'g');
    return url.match(regex);
}

var HOSTNAME = getIPAddress(localStorage.getItem('ipaddress')),
PORT = 80,
USERNAME = localStorage.getItem('ipusername'),
PASSWORD = localStorage.getItem('ippassword'),
STOP_DELAY_MS = 50;

var Cam = require('./lib/onvif').Cam;
var keypress = require('keypress');

var camera = new Cam({
    hostname : HOSTNAME,
    username : USERNAME,
    password : PASSWORD,
    port : PORT,
    timeout : 10000
}, this.CamFunc = function (err) {
    if (err) {
        console.log(err);
        return;
    }

    var cam_obj = this;
    var preset_names = [];
    var preset_tokens = [];

    cam_obj.getStreamUri({
        protocol : 'RTSP'
    },  // Completion callback function
        // This callback is executed once we have a StreamUri
        function (err, stream, xml) {
            if (err) {
                console.log(err);
                return;
            } else {
                console.log('------------------------------');
                console.log('Host: ' + HOSTNAME + ' Port: ' + PORT);
                console.log('Stream: = ' + stream.uri);
                console.log('------------------------------');

                // start processing the keyboard
                read_and_process_keyboard();
            }
        }
    );

    cam_obj.getPresets({}, // use 'default' profileToken
        // Completion callback function
        // This callback is executed once we have a list of presets
        function (err, stream, xml) {
            if (err) {
                console.log("GetPreset Error "+err);
                return;
            } else {
                // loop over the presets and populate the arrays
                // Do this for the first 9 presets
                console.log("GetPreset Reply");
                var count = 1;
                for(var item in stream) {
                    var name = item;          //key
                    var token = stream[item]; //value
                    // It is possible to have a preset with a blank name so generate a name
                    if (name.length == 0) name='no name ('+token+')';
                    preset_names.push(name);
                    preset_tokens.push(token);

                    // Show first 9 preset names to user
                    if (count < 9) {
                        console.log('Press key '+count+ ' for preset "' + name + '"');
                    count++;
                    }
                }
            }
        }
    );
});

var stop_timer;
var ignore_keypress = false;

function read_and_process_keyboard() {
    // listen for the "keypress" events
    keypress(process.stdin);
    process.stdin.setRawMode(true);
    process.stdin.resume();

    console.log('');
    console.log('Use Cursor Keys to move camera. + and - to zoom. q to quit');

    // keypress handler
    process.stdin.on('keypress', function (ch, key) {

        /* Exit on 'q' or 'Q' or 'CTRL C' */
        if ((key && key.ctrl && key.name == 'c')
             || (key && key.name == 'q')) {
            process.exit();
        }

        if (ignore_keypress) {
            return;
        }

        if (key) {
            console.log('got "keypress"',key.name);
        } else {
            if (ch)console.log('got "keypress character"',ch);
        }


        if      (key && key.name == 'up')    move(0,1,0,'up');
        else if (key && key.name == 'down')  move(0,-1,0,'down');
        else if (key && key.name == 'left')  move(-1,0,0,'left');
        else if (key && key.name == 'right') move(1,0,0,'right');
        else if (ch  && ch       == '-')     move(0,0,-1,'zoom out');
        else if (ch  && ch       == '+')     move(0,0,1,'zoom in');
        // On English keyboards '+' is "Shift and = key"
        // Accept the "=" key as zoom in
        else if (ch  && ch       == '=')     move(0,0,1,'zoom in');
        else if (ch  && ch>='1' && ch <='9') goto_preset(ch);
    });
}


function goto_preset(number) {
    if (number > preset_names.length) {
        console.log ("No preset " + number);
        return;
    }

    console.log('sending goto preset command '+preset_names[number-1]);
    camera.CamFunc().cam_obj.gotoPreset({ preset : preset_tokens[number-1] } ,
        // completion callback function
        function (err, stream, xml) {
            if (err) {
                console.log(err);
            } else {
                console.log('goto preset command sent ');
            }
        });
}

function move(x_speed, y_speed, zoom_speed, msg) {
    // Step 1 - Turn off the keyboard processing (so keypresses do not buffer up)
    // Step 2 - Clear any existing 'stop' timeouts. We will re-schedule a new 'stop' command in this function 
    // Step 3 - Send the Pan/Tilt/Zoom 'move' command.
    // Step 4 - In the callback from the PTZ 'move' command we schedule the ONVIF Stop command to be executed after a short delay and re-enable the keyboard

    // Pause keyboard processing
    ignore_keypress = true;

    // Clear any pending 'stop' commands
    if (stop_timer) clearTimeout(stop_timer);

    // Move the camera
    console.log('sending move command ' + msg);
    camera.cam_obj.continuousMove({x : x_speed,
                y : y_speed,
                zoom : zoom_speed } ,
            // completion callback function
            function (err, stream, xml) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('move command sent '+ msg);
                    // schedule a Stop command to run in the future 
                    stop_timer = setTimeout(stop,STOP_DELAY_MS);
                }
                // Resume keyboard processing
                ignore_keypress = false;
            });
    }


function stop() {
    // send a stop command, stopping Pan/Tilt and stopping zoom
    console.log('sending stop command');
    camera.cam_obj.stop({panTilt: true, zoom: true},
        function (err,stream, xml){
            if (err) {
                console.log(err);
            } else {
                console.log('stop command sent');
            }
        });
}

function PanRight() {
    move(1,0,0,'right');
}

function PanLeft() {
    move(-1,0,0,'left');
}

function TiltUp() {
    move(0,1,0,'up');
}

function TiltDown() {
    move(0,-1,0,'down');
}

function AdjustSpeed(speed){
    x_speed = speed;
    y_speed = speed;
}

function PanFront() {
    goto_preset(1);
}

function PanBack() {
    goto_preset(8);
}

function TiltCenter() {
    goto_preset(1);
}

function Stop() {
    stop();
}

// exported methods for the script.js and other scripts
module.exports = {
    // flashlight: Flashlight,
    // laser: Laser,
    panright: PanRight,
    panleft : PanLeft,
    tiltup: TiltUp,
    tiltdown: TiltDown,
    panfront: PanFront,
    panback: PanBack,
    adjustspeed: AdjustSpeed,
    tiltcenter: TiltCenter,
    stop: Stop
}

问题是我正在尝试从相机对象内部的功能CamFunc中访问cam_obj。我什至无法弄清楚为什么即使尝试了几次更改才能使我无法访问CamFunc方法。

谁能告诉我如何访问属于对象的函数内部的对象?我对javascript比较陌生

2 个答案:

答案 0 :(得分:0)

在var相机的构造中,您似乎正在设置this.CamFunc参数通常会到达的位置。也许尝试不设置this.CamFunc而直接传递函数?或者也许在照相机对象之外设置this.CamFunc并将函数传递进来?不确定相机对象如何处理自身内部的功能

答案 1 :(得分:0)

天哪,我知道了。这是最终的解决方案:

function getIPAddress(url) {
    var regex = /[0-9]{1,3}(.[0-9]{1,3})(.[0-9]{1,3})(.[0-9]{1,3})/g;
    return url.match(regex);
}

var HOSTNAME = getIPAddress(localStorage.getItem('ipaddress'))[0],
PORT = 80,
USERNAME = localStorage.getItem('ipusername'),
PASSWORD = localStorage.getItem('ippassword'),
STOP_DELAY_MS = 50;

var Cam = require('./lib/onvif').Cam;
var keypress = require('keypress');
var cam_obj;

new Cam({
    hostname : HOSTNAME,
    username : USERNAME,
    password : PASSWORD,
    port : PORT,
    timeout : 10000
}, function CamFunc(err) {
    if (err) {
        console.log(err);
        return;
    }

    cam_obj = this;

    cam_obj.getStreamUri({
        protocol : 'RTSP'
    },  // Completion callback function
        // This callback is executed once we have a StreamUri
        function (err, stream, xml) {
            if (err) {
                console.log(err);
                return;
            } else {
                console.log('------------------------------');
                console.log('Host: ' + HOSTNAME + ' Port: ' + PORT);
                console.log('Stream: = ' + stream.uri);
                console.log('------------------------------');

                // start processing the keyboard
                read_and_process_keyboard();
            }
        }
    );

    cam_obj.getPresets({}, // use 'default' profileToken
        // Completion callback function
        // This callback is executed once we have a list of presets
        function (err, stream, xml) {
            if (err) {
                console.log("GetPreset Error "+err);
                return;
            } else {
                // loop over the presets and populate the arrays
                // Do this for the first 9 presets
                console.log("GetPreset Reply");
                var count = 1;
                for(var item in stream) {
                    var name = item;          //key
                    var token = stream[item]; //value
                    // It is possible to have a preset with a blank name so generate a name
                    if (name.length == 0) name='no name ('+token+')';
                    preset_names.push(name);
                    preset_tokens.push(token);

                    // Show first 9 preset names to user
                    if (count < 9) {
                        console.log('Press key '+count+ ' for preset "' + name + '"');
                    count++;
                    }
                }
            }
        }
    );
});

var stop_timer;
    var ignore_keypress = false;
    var preset_names = [];
    var preset_tokens = [];

    function read_and_process_keyboard() {
        // listen for the "keypress" events
        keypress(process.stdin);
        process.stdin.setRawMode(true);
        process.stdin.resume();

        console.log('');
        console.log('Use Cursor Keys to move camera. + and - to zoom. q to quit');

        // keypress handler
        process.stdin.on('keypress', function (ch, key) {

            /* Exit on 'q' or 'Q' or 'CTRL C' */
            if ((key && key.ctrl && key.name == 'c')
                 || (key && key.name == 'q')) {
                process.exit();
            }

            if (ignore_keypress) {
                return;
            }

            if (key) {
                console.log('got "keypress"',key.name);
            } else {
                if (ch)console.log('got "keypress character"',ch);
            }


            if      (key && key.name == 'up')    move(0,1,0,'up');
            else if (key && key.name == 'down')  move(0,-1,0,'down');
            else if (key && key.name == 'left')  move(-1,0,0,'left');
            else if (key && key.name == 'right') move(1,0,0,'right');
            else if (ch  && ch       == '-')     move(0,0,-1,'zoom out');
            else if (ch  && ch       == '+')     move(0,0,1,'zoom in');
            // On English keyboards '+' is "Shift and = key"
            // Accept the "=" key as zoom in
            else if (ch  && ch       == '=')     move(0,0,1,'zoom in');
            else if (ch  && ch>='1' && ch <='9') goto_preset(ch);
        });
    }


    function move(x_speed, y_speed, zoom_speed, msg) {
        // Step 1 - Turn off the keyboard processing (so keypresses do not buffer up)
        // Step 2 - Clear any existing 'stop' timeouts. We will re-schedule a new 'stop' command in this function 
        // Step 3 - Send the Pan/Tilt/Zoom 'move' command.
        // Step 4 - In the callback from the PTZ 'move' command we schedule the ONVIF Stop command to be executed after a short delay and re-enable the keyboard

        // Pause keyboard processing
        ignore_keypress = true;

        // Clear any pending 'stop' commands
        if (stop_timer) clearTimeout(stop_timer);

        // Move the camera
        console.log('sending move command ' + msg);
        cam_obj.continuousMove({x : x_speed,
                    y : y_speed,
                    zoom : zoom_speed } ,
                // completion callback function
                function (err, stream, xml) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('move command sent '+ msg);
                        // schedule a Stop command to run in the future 
                        stop_timer = setTimeout(stop,STOP_DELAY_MS);
                    }
                    // Resume keyboard processing
                    ignore_keypress = false;
                });
        }


    function stop() {
        // send a stop command, stopping Pan/Tilt and stopping zoom
        console.log('sending stop command');
        cam_obj.stop({panTilt: true, zoom: true},
            function (err,stream, xml){
                if (err) {
                    console.log(err);
                } else {
                    console.log('stop command sent');
                }
            });
    }


    function goto_preset(number) {
        if (number > preset_names.length) {
            console.log ("No preset " + number);
            return;
        }

        console.log('sending goto preset command '+preset_names[number-1]);
        cam_obj.gotoPreset({ preset : preset_tokens[number-1] } ,
            // completion callback function
            function (err, stream, xml) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('goto preset command sent ');
                }
            });
    }

function PanRight() {
    move(1,0,0,'right');
}

function PanLeft() {
    move(-1,0,0,'left');
}

function TiltUp() {
    move(0,1,0,'up');
}

function TiltDown() {
    move(0,-1,0,'down');
}

function AdjustSpeed(speed){
    x_speed = speed;
    y_speed = speed;
}

function PanFront() {
    goto_preset(1);
}

function PanBack() {
    goto_preset(8);
}

function TiltCenter() {
    goto_preset(1);
}

function Stop() {
    stop();
}

// exported methods for the script.js and other scripts
module.exports = {
    // flashlight: Flashlight,
    // laser: Laser,
    panright: PanRight,
    panleft : PanLeft,
    tiltup: TiltUp,
    tiltdown: TiltDown,
    panfront: PanFront,
    panback: PanBack,
    adjustspeed: AdjustSpeed,
    tiltcenter: TiltCenter,
    stop: Stop
}

感谢您的帮助!

相关问题