#!/usr/bin/perl -w
#  $Id: probe 19769 2010-08-26 21:10:02Z atsibulnik $
# -----------------------------------------------------------------------------
#  Purpose:
#    - probe the camera
#    - pre-tune camera befor for retriever (RC and Audio)
# -----------------------------------------------------------------------------
#  Call:
#    probe DEVID=123   
#    probe DEVID=123 PROBE=FAST  
#    probe DEVID=123 DEVIP=192.168.17.177 [ ... ]
#    probe DEVIP=192.168.17.177 USRNAME=admin PASSWD=pass PROBE=DEFINE
# -----------------------------------------------------------------------------
#  Does:
#   0. can be called without DEVID argument. 
#      In this case DEVIP,USRNAME,PASSWD should be provided in command line
#   1. load $APL_CONF/<DEVID>/conf if DEVID is provided
#   2. combine conf and args into one hash
#   3. connect to camera over http and read MODELID and FIRMWARE
#   4. report MODELID|FIRMWARE|STATUS to $APL_CONF/<DEVID>/conf.probe and stdout
#   5. if PROBE=DEFINE then get
#         IMAGESIZE_LIST,MEDIA_FORMAT_LIST
#         AUDIO_LIST,AUDIO_FORMAT_LIST
#         SNAPSHOT (picture)
#   6. set RC camera attributes    if mpeg4 | h264
#   7. set AUDIO camera attributes if AUDIO is on 
#   8. example output:
#       AUDIO_SET=OK
#       FIRMWARE=5.02
#       MODELID=Q1755
#       RC_SET=OK
#       STATUS=OK
#       -------------
#       AUDIO_SET=NONE
#       FIRMWARE=5.02
#       MODELID=Q1755
#       RC_SET=NONE
#       STATUS=OK
#       SNAPSHOT=/tmp/probe/192.168.17.177-12367576123.jpg
#       IMAGESIZE_LIST=640x480,480x360,320x240,240x180,176x144,160x120
#       MEDIA_FORMAT_LIST=mjpeg,h264
#       AUDIO_LIST=off,on
#       AUDIO_FORMAT_LIST=g711,g726,aac
#   9. sample errors: 
#       STATUS=ERROR: PCE-0001 [101] configuration is not found
#       STATUS=ERROR: PCE-0002 [101] USRNAME and PASSWD should provided
#       STATUS=ERROR: PCE-0003 [101] DEVIP is not defined
#       STATUS=ERROR: PCE-0500 [101] Device does not respond (http://207.107.163.123:80)
#       STATUS=ERROR: PCE-0401 [101] Authorization error 
#       STATUS=ERROR: PCE-0403 [101] Forbidden 
#       STATUS=ERROR: PCE-0030 [101] Cannot get MODELID
#       note: [101] is DEVID
#  10. warnings:
#       STATUS=WARNING: PCW-0001 [101] MODELID does not match configuration
#       STATUS=WARNING: PCW-0002 [101] FIRMWARE does not match configuration
#       STATUS=WARNING: PCW-0009 [101] PROBE=RESET is not supported
#       
# -----------------------------------------------------------------------------
#  Note:
#   1. CAMERAMODEL file is obsolite. ptz_axisv2.pl & ptz_udp.pl has to be modified
#   2. Script mast be in the directory .../camera/<BRAND>/bin/
# -----------------------------------------------------------------------------
#  Author: teetov, 03/22/10
#  Edited by:
#  QA by:
#  Copyright: videoNEXT Network Solutions, Inc, 2010
# -----------------------------------------------------------------------------
#
use strict;
#use Socket qw(:DEFAULT);
#use Errno 'EADDRINUSE';
#use HTML::Parser;
#use Node::Conf;
#use SKM::DB;
use Device::Conf ":all";
use Data::Dumper;
#use URI::Escape "uri_unescape";
# cons -------------------------------------------------------------------------
# no code for Unicast

# vars -------------------------------------------------------------------------

my $conf=ProbeInit();  # uses <BRAND> from path and ARGV
#ProbeErr("PCE-0001","configuration is not found") if not defined $conf->{DEVID}; 
#ProbeErr("PCE-0003","DEVIP is not defined")       if not defined $conf->{DEVIP};
#ProbeErr("PCE-0002","USRNAME and PASSWD should be provided") 
#                 if not defined $conf->{USRNAME} or not defined $conf->{PASSWD};
ProbeWarn("PCW-0009","PROBE=RESET is not supported")         if $conf->{PROBE} eq 'RESET';
#------------------------------------------------------------------------------
# Probe camera MODELID & FIRMWARE 
#------------------------------------------------------------------------------
my %result=(STATUS=>'OK',RC_SET=>'NONE');

# Model
#if($respond!~ /^HTTP ERROR/) {
#  ProbeErr("PCE-0500","Device does not respond",$respond) if $err=~/^5\d\d/;
#}
my $rsp;
$rsp = ProbeRequest("/info.bwt?type=version&display=text");
if( $rsp =~ /^HTTP ERROR \[(\d+)\]/ ) {
    my $err = $1;
    if( $err=~/^5\d\d/ ) {
        ProbeErr("PCE-0500", "Device does not respond", $rsp);
    } else {
        ProbeErr("PCE-0000", "Device busy or isn't CiscoVSMS", $rsp);
    }
}
if( $rsp =~ /Cisco VSMS Server Version ([\d\.]+) Build (.*)$/ ) {
    $result{MODELID} = $1;
} else {
    $result{MODELID} = 'unknown';
}

$rsp = ProbeRequest("/info.bwt?type=proxy&display=text");
if( $rsp =~ /^HTTP ERROR \[(\d+)\]/ ) {
    my $err = $1;
    if( $err=~/^5\d\d/ ) {
        ProbeErr("PCE-0500", "Device does not respond", $rsp);
    } else {
        ProbeErr("PCE-0000", "Device busy or isn't CiscoVSMS", $rsp);
    }
}
my @proxiesl = split "\n", $rsp;
my %proxy;
my @lst_name = split /\s+/, $proxiesl[0];
for( my $i = 1; $i < scalar @proxiesl; $i++ ) {
    my @lst = split /\s+/, $proxiesl[$i];
    my $r;
    for( my $n = 0; $n < scalar @lst_name; $n++ ) {
        $r->{$lst_name[$n]} = $lst[$n];
    }
    $proxy{$r->{name}} = $r;
}

if ($conf->{PROBE} eq 'DEFINE') {
    $result{CAMERA_LIST} = EscapeList( map { ($_, $_) } keys %proxy );
#    $result{MEDIA_FORMAT_LIST} = EscapeList( map {  } keys %proxy );
#------------------------------------------------------------------------------
# get Sample picture 
#------------------------------------------------------------------------------
    $result{SNAPSHOT_LIST} = ProbeSnapshotList( keys %proxy );
}

#------------------------------------------------------------------------------
# get video and audio properties
#------------------------------------------------------------------------------

# no code for Unicast

#------------------------------------------------------------------------------
# interim report & exit 
#------------------------------------------------------------------------------
ProbeResult(\%result)  if $conf->{PROBE} =~ /^(DEFINE|FAST)$/;
#ProbeResult(\%result)  if $conf->{DEVID}==0;

#------------------------------------------------------------------------------
# set RC (rate control) parameters + quality + imagesize
#------------------------------------------------------------------------------

if( exists $proxy{ $conf->{CAMERA} } ) {
    my %vsms2stratus_mf = ( 'jpeg' => 'mjpg', 'h264-v' => 'h264' );
    $result{MEDIA_FORMAT} = $vsms2stratus_mf{ $proxy{$conf->{CAMERA}}->{mediatype} } || $proxy{$conf->{CAMERA}}->{mediatype};
    $result{IMAGESIZE} = uc($proxy{$conf->{CAMERA}}->{res}) . '(' . $proxy{$conf->{CAMERA}}->{width} . 'x' . $proxy{$conf->{CAMERA}}->{height} . ')';
}

# Use direct DB call instead of PHP API (unless got trusted IP support)
require SKM::DB;
SKM::DB->import();
my $dbm;
eval {
   $dbm = DBMaster({PrintError=>0,RaiseError=>1,AutoCommit=>0});
   $dbm->do("update _obj_attr set val=? where obj=? and attr='MEDIA_FORMAT'",
       undef,$result{MEDIA_FORMAT},$conf->{DEVID}
    );
#     $dbm->do("update _obj_attr set val=? where obj=? and attr='POSITIONCTL'",
#         undef,$positionctl,$conf->{DEVID}
#     );
    $dbm->do("update _objs set rtime=null where obj=?",undef,$conf->{DEVID});
    $dbm->commit;
};
if ($@) {
    $result{RC_SET} = "ERROR\n#DB error";
    eval { $dbm->rollback } if $dbm;
}
else {
    $result{RC_SET} = "OK";
}
eval { $dbm->disconnect } if $dbm;

#------------------------------------------------------------------------------
# set AudioParams
#------------------------------------------------------------------------------
# no code for Unicast
# final report-----------------------------------------------------------------------
ProbeResult(\%result);
