简体   繁体   中英

How do I call an object within a function in javascript?

Here's my code:

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
}

The problem is that I'm trying to access cam_obj from within the function CamFunc from within the camera object. I can't quite figure out why it won't let me access the CamFunc method even after attempting several changes to get it to work.

Can anyone tell me how to access a object inside of a function that belongs to an object? I'm relatively new to javascript

It looks like in the construction of var camera, you are setting this.CamFunc where a parameter would normally go. maybe try just passing the function in without setting this.CamFunc? Or maybe setting this.CamFunc outside of the camera object and passing the function in? Not sure on how the camera object handles the function inside of itself

Omg I got it working. Here's the final solution:

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
}

Thanks for your help guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM