test_01.php 52.7 KB
Newer Older
1
<?php
2
require_once('PolynomialApproximation.php');
3 4 5
$motosat_ip= "192.168.1.250";
$motosat_url= "http://".$motosat_ip."/motor.xml";
$modem_ip = "192.168.0.1";
Andrey Filippov's avatar
Andrey Filippov committed
6 7
//$modem_ip = "http://localhost/motosat/attic";
//$modem_strengt_url = $modem_ip."/sqf/sqfdisp/index.html";
8 9 10
//$modem_strengt_url_good = "http://localhost/motosat/attic/sqf/sqfdisp/index.html";
//$modem_strengt_url_bad = "http://localhost/motosat/attic/sqf/sqfdisp/index.html1";
//$modem_strengt_url = "http://192.168.0.1/sqf/sqfdisp/index.html";
Andrey Filippov's avatar
Andrey Filippov committed
11
$modem_strengt_url = "http://".$modem_ip."/sqf/sqfdisp/index.html";
12 13 14 15 16 17 18 19 20
$AZ_CPD = 12.74445;
$EL_CPD = 75.78567;
$SK_CPD = 8.34;
$AZ_0 =  0.0;    // degrees
$EL_0 =  0.0;    // degrees
$SK_0 = 55.7554; // degrees
$AZ_CMAX =  4790;
$EL_CMAX = 10979;
$SK_CMAX =   931;
Andrey Filippov's avatar
Andrey Filippov committed
21
$MODEM_THRESHOLD = 20.0; // consider something if modem strength is above
22
$OVERSHOOT = 2; // 1; // final steps absolute error
Andrey Filippov's avatar
Andrey Filippov committed
23
$LATE_STOP_AZ = 0; // 30; // steps
24 25 26

// Rescan azimuth after noticed a satellite during area scan
$AZ_PLAY = 1.0;         // Hysteresis caused by mechanical play (degrees)
Andrey Filippov's avatar
Andrey Filippov committed
27
$AZ_RESCAN = 10; // 8;         // (degrees) around expected center
28 29 30 31 32 33
$AZ_RESCAN_STEP = 0.5; // (degrees)

$EL_PLAY = 1.0;         // Hysteresis caused by mechanical play (degrees)
$EL_RESCAN = 8;         // (degrees) around expected center
$EL_RESCAN_STEP = 0.5; // (degrees)

Andrey Filippov's avatar
Andrey Filippov committed
34 35 36 37 38
$AZ_2D_RANGE = 2.0;     // degrees 2D peaking scan azimuth (full range)
$EL_2D_RANGE = 3.0;     // degrees 2D peaking scan alevation (full range)
$AZ_2D_STEP  = 0.25;    // degrees
$EL_2D_STEP  = 0.4;     // degrees
$ADJUST_2D =   1;       // 1 - adjust 2D, 0 - skip (only separate azimuth and elevation
39 40 41
$USABLE_FRACT =   0.6;  // use ony samples not less than this fraction of maximal
$USABLE_POW =     1.0;  // transform (maxstrengh - strengh) by applying pow - 1.2 ...1.3 may have marginal improvements
$ARGMAX_OURSIDE = 0.2;  // Allow  argmax outside of the measured range by this fraction 
Andrey Filippov's avatar
Andrey Filippov committed
42
$ARGMAX_OURSIDE_2D = 0.0;  // Allow  argmax outside of the measured range by this fraction during 2D peaking
Andrey Filippov's avatar
Andrey Filippov committed
43 44 45
// Modem never allows wrong satellite to have signal strength above 29, and tries to maintain 30 for the correct one when the signal falls below.
// So these values can not be used for peaking(maybe only remove 30 if the signal is going down?)
$HUGHES_BAD_STRENGTHS = array(29,30);
46
$HUGHES_THRESHOLD = 30;  // if less - wrong satellite
Andrey Filippov's avatar
Andrey Filippov committed
47
$GUARD_AZIMUTH    = 3.0; // (degrees) do not look for satellites closer than this to alerady found
48 49 50 51
$GUARD_STEP       = 1.0; // (degrees) If will peak on the same satellite, increase guard range on that side
$AZ_TOL           = 0.7; // (degrees) If satellites azimuths differ by less than this - they are the same
$MAX_ARC_TILT     = 0.2; // maximal local satellite arc tilt near a known satellite
$SAT_AZ_STEP      = 0.5; // (degrees) mark found satellites with this resolution
Andrey Filippov's avatar
Andrey Filippov committed
52 53 54



55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/*
http://192.168.1.250/motor.xml?Action=ElUp&Distance=0.5&Units=1 0.5 degree up

http://192.168.1.250/motor.xml?Action=ElUp&Distance=1&Units=0 1 step up
http://192.168.1.250/motor.xml?Action=ElDn&Distance=1&Units=0 1 step down
http://192.168.1.250/motor.xml?Action=AzUp&Distance=1&Units=0 1 sep az +
http://192.168.1.250/motor.xml?Action=AzDn&Distance=1&Units=0 1 sep az -

SK0 = 465 steps
http://192.168.1.250/motor.xml?Action=SkUp&Distance=1&Units=0 1 step sk +
http://192.168.1.250/motor.xml?Action=SkDn&Distance=1&Units=0 1 step sk -
http://192.168.1.250/motor.xml?Action=Stop&Distance=100&Units=1 - stop 

*/

//php > var_dump($DishAngle);
//array(3) {[0]=> float(9.97), [1]=> float(0), [2]=> float(0)}
Andrey Filippov's avatar
Andrey Filippov committed
72
$dbg_file = fopen("/home/eyesis/git/motosat/attic/logs/test09.log","w");
73 74
fprintf($dbg_file,"test log\n");

Andrey Filippov's avatar
Andrey Filippov committed
75
if (false) {
Andrey Filippov's avatar
Andrey Filippov committed
76 77
    $arr = Array(5,6,7,9,9,10,11,11,12,12,11,11,10,10,10,36,40,45,47,51,51,51,49,48,43,38,30,30,30,10,10,10,10);
    $rslt = findMax1d($arr, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE);
78 79
    print_r($rslt);
    print("\n");
Andrey Filippov's avatar
Andrey Filippov committed
80 81 82 83 84 85 86
    // Try 2D:
    $arr2d = array();
    $rows = sizeof($arr);
    $cols = $rows;
    for ($i= 0; $i < $rows; $i++){
        $line = $arr;
        for ($j= 0; $j < $cols; $j++){
Andrey Filippov's avatar
Andrey Filippov committed
87 88
            $i1 = ($i + 10) % $rows;
            $line[$j] *= $arr[$i1]/51;
Andrey Filippov's avatar
Andrey Filippov committed
89 90 91 92 93 94 95 96 97 98 99
            $line[$j] += rand(-10,10);
            if ($line[$j] <1){
                $line[$j] = 1;
            }
        }
        $arr2d [] = $line;
    }
   
//    $rslt = findMax2d($arr2d, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE);
    $rslt = findMax2d($arr2d, 0.55, $USABLE_POW, $ARGMAX_OURSIDE);
    var_dump($rslt);    
100 101 102
    exit (0);
}

Andrey Filippov's avatar
Andrey Filippov committed
103 104 105 106 107 108 109 110 111 112
if (false) {
    print("<p>".date('l jS \of F Y h:i:s A')."</p>");
    $modem_strength= getModemStrength();
    for ($i=0;$i<10;$i++){
        //$modem_strength= getModemStrength();
        $xml_state = simplexml_load_file($motosat_url); // 0.29 sec
    }
    print("<p>modem_strength=".$modem_strength." file=".$modem_strengt_url."</p>");
    print("<p>".date('l jS \of F Y h:i:s A')."</p>");
    exit (0);
Andrey Filippov's avatar
Andrey Filippov committed
113
}
114 115


116 117 118
$xml_state = simplexml_load_file($motosat_url); // use current as default gor HTTP GET
//$DishCount = getDishCounts (xml_state);
$DishAngle = getDishAngles ($xml_state);
119

Andrey Filippov's avatar
Andrey Filippov committed
120 121 122 123 124 125
$dbg =    false; // true;
$multi=   true; // false;
$wnd_az = 0;
$wnd_el = 0;
$scan_step = 1.0;
$min_strength = $MODEM_THRESHOLD;
126
$full_search = 0;
Andrey Filippov's avatar
Andrey Filippov committed
127 128 129 130 131 132 133 134 135 136
if (isset($_GET["dbg"]))          { $dbg=myval($_GET["dbg"]);}
if (isset($_GET["multi"]))        { $multi=myval($_GET["multi"]);}
if (isset($_GET["az"]))           { $DishAngle[0] = myfval($_GET["az"]);}
if (isset($_GET["el"]))           { $DishAngle[1] = myfval($_GET["el"]);}
if (isset($_GET["sk"]))           { $DishAngle[2] = myfval($_GET["sk"]);}

if (isset($_GET["wnd_az"]))       { $wnd_az =       myfval($_GET["wnd_az"]);}
if (isset($_GET["wnd_el"]))       { $wnd_el =       myfval($_GET["wnd_el"]);}
if (isset($_GET["scan_step"]))    { $scan_step =    myfval($_GET["scan_step"]);}
if (isset($_GET["min_strength"])) { $min_strength = myfval($_GET["min_strength"]);}
137
if (isset($_GET["full_search"]))  { $full_search = 1;}
Andrey Filippov's avatar
Andrey Filippov committed
138
$scan_mode = ($wnd_az > 0) || ($wnd_el > 0);
139 140 141 142 143
if (!$scan_mode){
    $full_search = 0;
}

if ($full_search){
144 145 146 147 148 149 150
    $rslt_sat = lockToSatellite($min_strength, $DishAngle, $wnd_az, $wnd_el, $scan_step);
    
    if ($dbg_file !== null) {
        fprintf($dbg_file, "lockToSatellite --> %s\n", print_r($rslt_sat,1));
    }
    
    
151
    $xml = new SimpleXMLElement("<?xml version='1.0'?><motosat/>");
152
    $State =          $xml_state->State+0; // 1 - Ready, 2 - Busy, 3 - Stow! (turned to stow by no reason?)
153 154 155 156 157 158 159
    $busy = ($State & 2) != 0;
    $SignalQuality = myfval(explode(",",$xml_state->SignalQuality)[0]);
    $xml->addChild ('SignalQuality',(string) $SignalQuality );
    $xml->addChild ('DishAngle',$xml_state->DishAngle );
    $xml->addChild ('DishCount',$xml_state->DishCountt );
    $xml->addChild ('busy',(string) $busy );
    $xml->addChild ('State',(string) $State );
160
    $xml->addChild ('Result',(string) print_r($rslt_sat,1));
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    
    $rslt=$xml->asXML();
    header("Content-Type: text/xml");
    header("Content-Length: ".strlen($rslt)."\n");
    header("Pragma: no-cache\n");
    // allow CORS: needed for multicam controls
    header('Access-Control-Allow-Origin: *');
    printf($rslt);
    
    
    
    exit (0);

}

Andrey Filippov's avatar
Andrey Filippov committed
176 177 178

if ($scan_mode){
    $xml_state = scan_window($min_strength, $DishAngle, $wnd_az, $wnd_el, $scan_step);
179 180 181
    $Success =       $xml_state->Success;
    
    if (intval ($Success)){
182 183
        $rslt = peakAzimuthOrElevation($xml_state, 0, $AZ_PLAY,$AZ_RESCAN, $AZ_RESCAN_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE);
        $Success = ($rslt === 1)? 1 : 0;
184
        $xml_state = simplexml_load_file($motosat_url);
185
        if (intval ($Success)){
186 187
            $rslt = peakAzimuthOrElevation($xml_state, 1, $EL_PLAY,$EL_RESCAN, $EL_RESCAN_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE);
            $Success = ($rslt === 1)? 1 : 0;
188
            $xml_state = simplexml_load_file($motosat_url);
Andrey Filippov's avatar
Andrey Filippov committed
189 190 191 192 193 194 195 196
            $DishAngle1D = $xml_state->DishAngle;
            if (intval ($Success) && $ADJUST_2D){
                $Success = peak2D($xml_state, $AZ_PLAY, $EL_PLAY, $AZ_2D_RANGE, $EL_2D_RANGE, $AZ_2D_STEP, $EL_2D_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE_2D);
                $xml_state = simplexml_load_file($motosat_url);
                if ($Success){
                    $DishAngle2D = $xml_state->DishAngle;
                }
            }
197
        }
198 199
    }
    
Andrey Filippov's avatar
Andrey Filippov committed
200 201 202
    $xml = new SimpleXMLElement("<?xml version='1.0'?><motosat/>");
    $State =          $xml_state->State+0; // 1 - Ready, 2 - Busy
    $busy = ($State & 2) != 0;
Andrey Filippov's avatar
Andrey Filippov committed
203
    $SignalQuality = myfval(explode(",",$xml_state->SignalQuality)[0]);
Andrey Filippov's avatar
Andrey Filippov committed
204 205 206
    
    $xml->addChild ('Success',(string) $Success );
    $xml->addChild ('SignalQuality',(string) $SignalQuality );
Andrey Filippov's avatar
Andrey Filippov committed
207
    if (isset($DishAngle1D)){
Andrey Filippov's avatar
Andrey Filippov committed
208
        $xml->addChild ('DishAngle1D',$DishAngle1D );
Andrey Filippov's avatar
Andrey Filippov committed
209 210
    }
    if (isset($DishAngle2D)){
Andrey Filippov's avatar
Andrey Filippov committed
211
        $xml->addChild ('DishAngle2D',$DishAngle2D );
Andrey Filippov's avatar
Andrey Filippov committed
212
    }
213 214
    $xml->addChild ('DishAngle',$xml_state->DishAngle );
    $xml->addChild ('DishCount',$xml_state->DishCountt );
Andrey Filippov's avatar
Andrey Filippov committed
215 216 217 218 219 220 221 222 223 224 225 226
    $xml->addChild ('busy',(string) $busy );
    $xml->addChild ('State',(string) $State );

    $rslt=$xml->asXML();
    header("Content-Type: text/xml");
    header("Content-Length: ".strlen($rslt)."\n");
    header("Pragma: no-cache\n");
    // allow CORS: needed for multicam controls
    header('Access-Control-Allow-Origin: *');
    printf($rslt);
    exit (0);
}
227

Andrey Filippov's avatar
Andrey Filippov committed
228
// Just move where requested
229
$total_cycles = 0;
Andrey Filippov's avatar
Andrey Filippov committed
230
$total_cycles = moveElAzSk_degrees($DishAngle, $multi);
231 232 233 234 235 236 237 238 239 240 241
$xml = new SimpleXMLElement("<?xml version='1.0'?><motosat/>");
$xml->addChild ('cycles',(string) $total_cycles );
$rslt=$xml->asXML();
header("Content-Type: text/xml");
header("Content-Length: ".strlen($rslt)."\n");
header("Pragma: no-cache\n");
// allow CORS: needed for multicam controls
header('Access-Control-Allow-Origin: *');
printf($rslt);
exit (0);

242 243 244 245 246 247 248 249 250 251 252
function lockToSatellite($min_strength, $DishAngle, $wnd_az, $wnd_el, $scan_step)
{
    global $motosat_url, $dbg_file, $SAT_AZ_STEP, $GUARD_AZIMUTH, $GUARD_STEP, $AZ_TOL, $MAX_ARC_TILT;
    global $AZ_PLAY, $AZ_RESCAN, $AZ_RESCAN_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE;
    global $EL_PLAY,$EL_RESCAN, $EL_RESCAN_STEP, $HUGHES_THRESHOLD, $ADJUST_2D;
    global $AZ_2D_RANGE, $EL_2D_RANGE, $AZ_2D_STEP, $EL_2D_STEP, $ARGMAX_OURSIDE_2D;
    $xml_state = simplexml_load_file($motosat_url);
    $DishAngleCenter =  getDishAngles ($xml_state); // will go there if failed
    $DishAngleCenter[0] = $DishAngle[0];
    $DishAngleCenter[1] = $DishAngle[1]; 
    $empty_az = array(); // array of pairs: ('low'=>min, "high"=>max) for scanned empoty azimuths in degrees
253
    $satellites =array();// array of ('az'=>az, "el"=> el, 'strength'-> strength, 'guard_low', 'guard_high') in degrees for each found satellite
254 255
    $num_az_steps =  (int) ceil ($wnd_az/$SAT_AZ_STEP);
    $az_min = $DishAngle[0] - $wnd_az/2;
256 257 258 259 260
    if ($dbg_file !== null) {
        fprintf($dbg_file, "+++++ lockToSatellite( %f, %s, %f,  %f, %f\n",
            $min_strength, print_r($DishAngle,1), $wnd_az, $wnd_el, $scan_step);
    }
    
261 262 263 264 265 266 267 268 269 270 271 272 273 274
//    $az_max = $az_min + ($num_az_steps)* $SAT_AZ_STEP;
    while (true) { // loop until found correct satellite, or failed
        $az_array = array_fill(0, $num_az_steps + 1, 0);
        // mark already scanned emty ranges
        foreach ($empty_az as $range){
            $i_min = (int) ceil (($range['low'] - $az_min)/$SAT_AZ_STEP);
            $i_max = (int) floor(($range['high'] - $az_min)/$SAT_AZ_STEP);
            if ($i_min < 0) $i_min = 0;
            if ($i_max > $num_az_steps) $i_max = $num_az_steps;
            for ($i = $i_min; $i <= $i_max; $i++){
                $az_array[$i] = -1;
            }
            
        }
275 276 277 278
        if ($dbg_file !== null) {
            fprintf($dbg_file, "0. az_array= %s\n", str_replace("\n"," ",print_r($az_array,1))."\n");
        }
        
279 280
        // Exclude each satellite with its guard range
        foreach ($satellites as $indx => $azels){
281 282 283 284 285 286
            $i_min = (int) round (($azels['az'] - $az_min - $azels['guard_low'])/$SAT_AZ_STEP);
            $i_max = (int) round (($azels['az'] - $az_min + $azels['guard_high'])/$SAT_AZ_STEP);
            if ($dbg_file !== null) {
                fprintf($dbg_file, "i_min = %d, i_max= %d\n", $i_min, $i_max);
            }
            
287 288 289 290
            if ($i_min < 0) $i_min = 0;
            if ($i_max > $num_az_steps) $i_max = $num_az_steps;
            for ($i = $i_min; $i <= $i_max; $i++){
                $az_array[$i] = $indx +1; // number of satellite, starting from 1
291 292 293 294
                if ($dbg_file !== null) {
                    fprintf($dbg_file, "%d: %d\n", $i,$az_array[$i]);
                }
                
295 296
            }
        }
297 298 299 300 301
        if ($dbg_file !== null) {
            fprintf($dbg_file, "1. az_array= %s\n", str_replace("\n"," ",print_r($az_array,1))."\n");
        }
        
        
302
        // Find azimuth range to scan
303
        for ($i_low = 0; ($i_low <= $num_az_steps) && ($az_array[$i_low] != 0); $i_low++ );
304
        if ($i_low > $num_az_steps) { // all searched, no luck
305
            // Here is te exit from the loop on failure!
306 307 308 309 310 311 312 313 314 315 316
            return array ('satellite' => null, 'satellites' => $satellites, 'empty' => $empty_az);
        }
        for ($i_high = $i_low; ($i_high < $num_az_steps) && ($az_array[$i_high+1] == 0); $i_high++);
        
        // setup new scan range
        $az_low =  $az_min + $i_low  * $SAT_AZ_STEP;
        $az_high = $az_min + $i_high * $SAT_AZ_STEP;
        $low_end_sat  =  ($i_low > 0)?              $az_array[$i_low - 1] : -1;
        $high_end_sat  = ($i_high < $num_az_steps)? $az_array[$i_high + 1] : -1;
        $az_range = $az_high - $az_low;
        $az_center = ($az_high + $az_low) / 2;
317 318 319 320 321 322 323
        if ($dbg_file !== null) {
            fprintf($dbg_file, "DishAngleCenter=".str_replace("\n"," ",print_r($DishAngleCenter,1))."\n");
            fprintf($dbg_file, "low_end_sat = %d, high_end_sat= %d\n",$low_end_sat,$high_end_sat);
            fprintf($dbg_file, "Satellites=".str_replace("\n"," ",print_r($satellites,1))."\n");
            
        }
        
324 325 326 327
        if ($low_end_sat < 0){
            if ($high_end_sat < 0) { // both ends unknown
                $el_center = $DishAngleCenter[1];
                $el_range  = $wnd_el;
328 329 330 331
                if ($dbg_file !== null) {
                    fprintf($dbg_file, "1: el_center = %f, el_range= %f\n",$el_center,$el_range);
                }
                
332 333 334
            } else { // satellite on the right only 
                $el_center = $satellites[$high_end_sat -1]['el'];
                $el_range  = $MAX_ARC_TILT * $az_range;
335 336 337
                if ($dbg_file !== null) {
                    fprintf($dbg_file, "2: el_center = %f, el_range= %f\n",$el_center,$el_range);
                }
338 339 340 341 342
            }
        } else {
            if ($high_end_sat < 0) {// satellite on the left only 
                $el_center = $satellites[$low_end_sat -1]['el'];
                $el_range =  $MAX_ARC_TILT * $az_range;
343 344 345
                if ($dbg_file !== null) {
                    fprintf($dbg_file, "3: el_center = %f, el_range= %f\n",$el_center,$el_range);
                }
346 347 348
            } else { // both ends have satellites
                $el_center = ($satellites[$high_end_sat -1]['el'] + $satellites[$low_end_sat -1]['el']) / 2 ;
                $el_range =  abs($satellites[$high_end_sat -1]['el'] - $satellites[$low_end_sat -1]['el']);
349 350 351
                if ($dbg_file !== null) {
                    fprintf($dbg_file, "4: el_center = %f, el_range= %f\n",$el_center,$el_range);
                }
352 353
            }
        }
354 355 356
        if ($el_center < 50){
            return array ('satellite' => null, 'satellites' => $satellites, 'empty' => $empty_az);
        }
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        // Do scanning of the range
        if ($dbg_file !== null) {
            fprintf($dbg_file, "==== Scanning sky window : center (az:%f7.3 el:%f7.3) az_range=%f7.3, el_range = %f7.3 ====\n",
               $az_center, $el_center, $az_range, $el_range);
        }
        
        $xml_state = simplexml_load_file($motosat_url);
        $DishAnglesScan =  getDishAngles ($xml_state); // will go there if failed
        $DishAnglesScan[0] = $az_center;
        $DishAnglesScan[1] = $el_center;
        $xml_state = scan_window($min_strength, $DishAnglesScan, $az_range, $el_range, $scan_step);
        $success =   intval ($xml_state->Success);
        if (!$success) {
            //    $empty_az = array(); // array of pairs: ('low'=>min, "high"=>max) for scanned empoty azimuths in degrees
            $empty_az[] = array('low'=> $az_low, 'high' => $az_high);
            if ($dbg_file !== null) {
                fprintf($dbg_file, ">>>>> Failed to find any satellites in the window : center (az:%f7.3 el:%f7.3) az_range=%f7.3, el_range = %f7.3 >>>>>\n",
                    $az_center, $el_center, $az_range, $el_range);
            }
            continue; // to next azimuth range
        }
        // Did found some satellite - peak azimuth
        // peakAzimuthOrElevation - limit range to scan range, do not allow max to be outside of the scan range!
        $minmax = array($az_low, $az_high);
381 382 383
        if ($dbg_file !== null) {
            fprintf($dbg_file, "Starting peakAzimuthOrElevation(...(%f, %f))\n",$az_low,$az_high);
        }
384
        $rslt_az = peakAzimuthOrElevation($xml_state, 0, $AZ_PLAY, $AZ_RESCAN, $AZ_RESCAN_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE, $minmax);
385 386 387 388 389
        if ($dbg_file !== null) {
            fprintf($dbg_file, "peakAzimuthOrElevation(...(%f, %f)) returned: %s\n",$az_low,$az_high, (string) $rslt_az);
        }
        
        
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        $success_az = ($rslt_az ===1) ? 1 : 0;
        
        $xml_state = simplexml_load_file($motosat_url);
        $DishAnglesPeakAz =  getDishAngles ($xml_state); // after peaking azimuth
        $az_sat = $DishAnglesPeakAz[0];
        if (!$success_az){ // what could be wrong here? tried to peak on existing satellite but was prohibited to go outside of the range?
            if ($dbg_file !== null) {
                fprintf($dbg_file, "**** Failed peaking azimuth - assuming that the peak was outside of the scan range, belonging to other satellite\n");
                fprintf($dbg_file, "Peaking error: %s\n", $rslt_az);
//                fprintf($dbg_file, "For now will only try to recover if the end of scan range was a satellite found before\n");
            }
            if (($low_end_sat > 0) && (($rslt_az == 'first element') || ($rslt_az == 'too low'))){
                $sat = $satellites[$low_end_sat - 1];
                if (($az_sat - $sat['az']) < $AZ_TOL + $AZ_RESCAN_STEP){ // accepting larger tolerance
                    $satellites[$indx]['guard_high'] += $GUARD_STEP; // search range was on the right, increasing high guard range for the satellite
                    if ($dbg_file !== null) {
406
                        fprintf($dbg_file, "**** Increasing high guard range of the satellite :\n".print_r($satellites[$indx],1));
407 408 409 410 411 412 413 414 415 416
                    }
                    continue;
                }
            }

            if ((high_end_sat > 0) && (($rslt_az == 'last element') || ($rslt_az == 'too high'))){
                $sat = $satellites[$high_end_sat - 1];
                if (($sat['az'] - $az_sat) < $AZ_TOL + $AZ_RESCAN_STEP){ // accepting larger tolerance
                    $satellites[$indx]['guard_low'] += $GUARD_STEP; // search range was on the left, increasing low guard range for the satellite
                    if ($dbg_file !== null) {
417
                        fprintf($dbg_file, "**** Increasing low guard range of the satellite :\n".print_r($satellites[$indx],1));
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
                    }
                    continue;
                }
            }
            // other errors - for now discarding that range completely
            if ($dbg_file !== null) {
                fprintf($dbg_file, "**** Other azimuth peaking errors(%s), discarding last search range %f7.3 < %f7.3\n",
                    $rslt_az, $az_low, $az_high);
            }
            $empty_az[] = array($az_low, $az_high);
            continue;
        }
        
        // compare azimuth to already known satellites
        foreach ($satellites as $indx => $sat){
            if (abs($az_sat - $sat['az']) < $AZ_TOL){ // it is the same satellite as already found
                if ($az_center < $sat['az']) {
                    $satellites[$indx]['guard_low'] += $GUARD_STEP; // search range was on the left, increasing low guard range for the satellite
                    if ($dbg_file !== null) {
437
                        fprintf($dbg_file, "**** Increasing low guard range of the satellite:\n".print_r($satellites[$indx],1));
438 439 440 441 442
                    }
                    
                } else {
                    $satellites[$indx]['guard_high'] += $GUARD_STEP;// search range was on the right, increasing high guard range for the satellite
                    if ($dbg_file !== null) {
443
                        fprintf($dbg_file, "**** Increasing high guard range of the satellite:\n".print_r($satellites[$indx],1));
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                    }
                }
                continue; // recalculate azimuth range, try again
            }
        }
        // got new satellite, peak elevation
        $rslt_el = peakAzimuthOrElevation($xml_state, 1, $EL_PLAY,$EL_RESCAN, $EL_RESCAN_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE);
        $Success_el = ($rslt_el === 1)? 1 : 0;
        if ($dbg_file !== null) {
            fprintf($dbg_file, "**** Peak elevation success = %d\n",$Success_el);
            if (!$Success_el){
                fprintf($dbg_file, "**** Peak elevation error: %s\n",$rslt_el);
            }
        }
        $modem_strength = getModemStrength();
        $xml_state = simplexml_load_file($motosat_url);
460
        $DishAngleSat = getDishAngles($xml_state); // ->DishAngle;
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
        $satellite = array(
            'az' => $DishAngleSat[0],
            "el" => $DishAngleSat[1],
            'strength' => $modem_strength,
            'guard_low' => $GUARD_AZIMUTH,
            'guard_high' => $GUARD_AZIMUTH
        );
        if ($dbg_file !== null) {
            fprintf($dbg_file, "**** Got a satellite\n".print_r($satellite, 1));
        }
        // See if it is Hughes modem
        if ($modem_strength < $HUGHES_THRESHOLD){
            if ($dbg_file !== null) {
                fprintf($dbg_file, "**** Satellite modem strength is too low (%f < %f) not a target satellite, continuing search\n",$modem_strength, $HUGHES_THRESHOLD);
            }
            $satellites[] = $satellite;
            continue;
        }
        if ($dbg_file !== null) {
            fprintf($dbg_file, "**** Found target satellite, modem strength is %f >= %f\n",$modem_strength, $HUGHES_THRESHOLD);
        }
        
        if ($ADJUST_2D){
            if ($dbg_file !== null) {
                fprintf($dbg_file, "**** 2D peaking requested, performing it\n");
            }
            $rslt_2d = peak2D($xml_state, $AZ_PLAY, $EL_PLAY, $AZ_2D_RANGE, $EL_2D_RANGE, $AZ_2D_STEP, $EL_2D_STEP, $USABLE_FRACT, $USABLE_POW, $ARGMAX_OURSIDE_2D);
            $Success_2d = $rslt_2d;
            $xml_state = simplexml_load_file($motosat_url);
            
            if ($dbg_file !== null) {
                fprintf($dbg_file, "**** 2D peaking returned: ".$rslt_2d."\n");
            }
            
            if ($Success_2d){
                $modem_strength = getModemStrength();
                $xml_state = simplexml_load_file($motosat_url);
498
                $DishAngleSat = getDishAngles($xml_state); // ->DishAngle;
499 500 501 502 503 504 505 506 507 508 509 510 511 512
                $satellite = array(
                    'az' => $DishAngleSat[0],
                    "el" => $DishAngleSat[1],
                    'strength' => $modem_strength,
                    'guard_low' => $GUARD_AZIMUTH,
                    'guard_high' => $GUARD_AZIMUTH
                );
            }
            $satellites[] = $satellite;
            return array ('satellite' => $satellite, 'satellites' => $satellites, 'empty' => $empty_az);
        }
    }
}

Andrey Filippov's avatar
Andrey Filippov committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
function peak2D($xml_state, $az_play, $el_play, $az_range, $el_range, $az_step, $el_step, $fract, $pow = 1.0, $argmax_outside=0.0){
    global $motosat_url, $dbg_file;
    if ($xml_state === null){
        $xml_state = simplexml_load_file($motosat_url);
    }
    $DishAngle =  getDishAngles ($xml_state);
    
    $azel_start_center = $DishAngle;
    //move to sart rescan azimuth minus mechanical play
    $DishAngle[0] = $azel_start_center[0] - $az_play - $az_range/2;
    $DishAngle[1] = $azel_start_center[1] - $el_play - $el_range/2;
    moveElAzSk_degrees($DishAngle);
    $scan_strengths = Array();
    for ($el = $azel_start_center[1] - $el_range / 2; $el < ($azel_start_center[1] + $el_range / 2 + $el_step); $el += $el_step) {
        $scan_strengths_line = Array();
        $DishAngle[1] = $el;
Andrey Filippov's avatar
Andrey Filippov committed
529 530 531 532 533 534 535
        $DishAngle[0] = $azel_start_center[0] - $az_play - $az_range/2;
        if ($dbg_file !== null) {
            fprintf($dbg_file, "==== 2D scan line, elevation = %f ====\n",$el);
//            fprintf($dbg_file, print_r($scan_strengths, 1));
        }
        moveElAzSk_degrees($DishAngle);
        
Andrey Filippov's avatar
Andrey Filippov committed
536 537 538 539 540 541 542 543 544 545
        for ($az = $azel_start_center[0] - $az_range / 2; $az < ($azel_start_center[0] + $az_range / 2 + $az_step); $az += $az_step) {
            $DishAngle[0] = $az;
            moveElAzSk_degrees($DishAngle); // to be on the safe side re-read xml
            $modem_strength = getModemStrength();
            $scan_strengths_line[] = $modem_strength;
        }
        $scan_strengths[] = $scan_strengths_line;
    }

    if ($dbg_file !== null) {
546 547
        fprintf($dbg_file, "==== 2D scan strengths (will be printed in findMax2d() ): ====\n");
//        fprintf($dbg_file, print_r($scan_strengths, 1));
Andrey Filippov's avatar
Andrey Filippov committed
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    }
    
//    $rel_argmax = findMax1d($scan_strengths, $fract, $pow, $argmax_outside);
    $rel_argmax = findMax2d($scan_strengths, $fract, $pow, $argmax_outside); // $pow not yet used
        
    
    $azel_argmax = $azel_start_center;
    $success = 0;
    if ($rel_argmax !== null) {
        $azel_argmax = array(
            $azel_start_center[0] - $az_range / 2 + $az_step * $rel_argmax[0],
            $azel_start_center[1] - $el_range / 2 + $el_step * $rel_argmax[1]
        );
        $success = 1;
    } else {
        if ($dbg_file !== null) {
            fprintf($dbg_file, "****** Failed to find maximum for 2d peaking, going to known position.\n");
        }
    }
    if ($dbg_file !== null) {
568 569
        fprintf($dbg_file, "relative argmax = [az=%f, el=%f]\n", $rel_argmax[0], $rel_argmax[1]);
        fprintf($dbg_file, "         argmax = [az=%f, el=%f] (was [az=%f, el=%f])\n", $azel_argmax[0], $azel_argmax[1], $azel_start_center[0], $azel_start_center[1]);
Andrey Filippov's avatar
Andrey Filippov committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    }
    $DishAngle[0] = $azel_argmax[0] - $az_play;
    $DishAngle[1] = $azel_argmax[1] - $el_play;
    if ($dbg_file !== null) {
        fprintf($dbg_file, "====== Moving to compensate az/el motors play to [az=%f, el=%f]\n", $DishAngle[0], $DishAngle[1]);
    }

    moveElAzSk_degrees($DishAngle);
    $DishAngle[0] = $azel_argmax[0];
    $DishAngle[1] = $azel_argmax[1];
    if ($dbg_file !== null) {
        fprintf($dbg_file, "====== Moving to argmax position =  [az=%f, el=%f]\n", $DishAngle[0], $DishAngle[1]);
    }
    moveElAzSk_degrees($DishAngle);
    return $success; // success
}


588 589 590
// return ===1 if OK, else error text string from findMax1D
function peakAzimuthOrElevation($xml_state, $el_not_az, $azel_play, $azel_range, $azel_step, $fract, $pow = 1.0, $argmax_outside = 0.2, $minmax=null)
{
591
    global $motosat_url, $dbg_file;
592
    if ($xml_state === null) {
593 594
        $xml_state = simplexml_load_file($motosat_url);
    }
595 596
    $DishAngle = getDishAngles($xml_state);
    $motor = $el_not_az ? 1 : 0;
597
    $direction = $el_not_az ? "ELEVATION" : "AZIMUTH";
598

599
    $azel_start_center = $DishAngle[$motor];
600 601
    // move to sart rescan azimuth minus mechanical play
    $DishAngle[$motor] = $azel_start_center - $azel_play - $azel_range / 2;
602 603
    moveElAzSk_degrees($DishAngle);
    $scan_strengths = Array();
604 605 606 607 608
    $azel_min = $azel_start_center - $azel_range / 2;
    $azel_max = $azel_start_center + $azel_range / 2 + $azel_step;
    if ($minmax !== null) {
        if ($azel_min < $minmax[0]){
            $azel_min = $minmax[0];
609
        }
610
        if ($azel_max > $minmax[1]){
611 612 613
            $azel_max = $minmax[1];
        }
    }
614 615 616 617 618 619
    
    if ($dbg_file !== null) {
        fprintf($dbg_file, "Peaking %s\n",$direction);
    }
    
    
620
    if (($azel_max - $azel_min) < $azel_step){
621
        if ($dbg_file !== null) {
622
            fprintf($dbg_file, "==== $direction scan range to small min = %f, max = %f: ====\n", $azel_min, $azel_max);
623
        }
624 625 626 627
        return 'small range';
    }
    if (($azel_max - $azel_min) < 2.01 * $azel_step){
        $azel_step = ($azel_max - $azel_min) / 2.01; // at least 3 samples
628
        if ($dbg_file !== null) {
629
            fprintf($dbg_file, "==== $direction scan range to small min = %f, max = %f new step = %f: ====\n", $azel_min, $azel_step);
630
        }
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    }
        
    
    for ($azel = $azel_min; $azel < $azel_max; $azel += $azel_step) {
        $DishAngle[$motor] = $azel;
        moveElAzSk_degrees($DishAngle); // to be on the safe side re-read xml
        $modem_strength = getModemStrength();
        $scan_strengths[] = $modem_strength;
    }
    if ($dbg_file !== null) {
        fprintf($dbg_file, "==== $direction scan strengths: ====\n");
        fprintf($dbg_file, print_r($scan_strengths, 1));
    }
    // $rel_argmax = findMax1d($scan_strengths, $fract, $pow, $argmax_outside);
    $rslt = findMax1d($scan_strengths, $fract, $pow, $argmax_outside);
    $rel_argmax = $rslt['argmax'];
    if (isset($rslt['err'])){
648
        if ($dbg_file !== null) {
649
            fprintf($dbg_file, "****** Failed to find maximum for $direction, going to known position.\n");
650 651
        }
    }
652 653 654

    $azel_argmax = $azel_min + $azel_step * $rel_argmax;
    if ($dbg_file !== null) {
655
        fprintf($dbg_file, "relative argmax = %f\n", $rel_argmax);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
        fprintf($dbg_file, "$direction argmax = %f (was %f)\n", $azel_argmax, $azel_start_center);
    }
    $DishAngle[$motor] = $azel_argmax - $azel_play;
    if ($dbg_file !== null) {
        fprintf($dbg_file, "====== Moving $direction to compensate motor play to = %f\n", $DishAngle[$motor]);
    }
    
    moveElAzSk_degrees($DishAngle);
    $DishAngle[$motor] = $azel_argmax;
    if ($dbg_file !== null) {
        fprintf($dbg_file, "====== Moving $direction to argmax position = %f\n", $DishAngle[$motor]);
    }
    moveElAzSk_degrees($DishAngle);
    if (isset($rslt['err'])){
        return $rslt['err'];
    }
    return 1; // success
673 674
}

Andrey Filippov's avatar
Andrey Filippov committed
675
function findMax2d($data, $fract, $pow, $frac_outside = 0.2){ // $pow not yet used
Andrey Filippov's avatar
Andrey Filippov committed
676
    global $HUGHES_BAD_STRENGTHS, $dbg_file;
Andrey Filippov's avatar
Andrey Filippov committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    $min= $data[0][0];
    $max = $data[0][0];
    $rows = sizeof($data);
    $cols = sizeof($data[0]); // should be rectangular
    $argmax = array(0.0, 0.0);
    foreach ($data as $row => $line) {
        foreach ($line as $col => $v) {
            if ($v > $max) {
                $max = $v;
                $argmax = array($col, $row,);
            } else if ($v < $min)
                $min = $v;
        }
    }
    $threshold = $min + ($max-$min)*$fract;
    // Find a 2D cluster around $argmax exceeding $threshold
    $cluster = $data;
    for ($i = 0; $i < $rows; $i++){
        for ($j = 0; $j < $cols; $j++){
            $cluster[$i][$j] = false;
        }
    }
    // Wve method (1 directions)
    $poly_data = array();
    $queue = array();
    $xy = $argmax; // x,y pair
                   // put a cell into a queue, in $poly_data and mark a cell as used
    $queue[] = $xy;
Andrey Filippov's avatar
Andrey Filippov committed
705 706 707 708 709 710 711 712 713 714 715
    if (! in_array($data[$xy[1]][$xy[0]], $HUGHES_BAD_STRENGTHS)) {
        $poly_data[] = array(
            array(
                0.0,
                0.0
            ), // $xy,
            array(
                $data[$xy[1]][$xy[0]]
            )
        );
    }
Andrey Filippov's avatar
Andrey Filippov committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
    $cluster[$xy[1]][$xy[0]] = true;
    
    while (sizeof($queue) > 0) {
        $xy0 = $queue[0];
        $queue = array_slice($queue, 1);
//        print("<=" . print_r($xy0, 1));
        for ($dir = 0; $dir < 4; $dir ++) {
            $xy = $xy0;
            switch ($dir) {
                case 0:
                    $xy[0] ++;
                    if ($xy[0] >= $cols) {
                        continue;
                    }
//                    print($dir . ":" . print_r($xy, 1));
                    break;
                case 1:
                    $xy[1] ++;
                    if ($xy[1] >= $rows) {
                        continue;
                    }
//                    print($dir . ":" . print_r($xy, 1));
                    break;
                case 2:
                    $xy[0] --;
                    if ($xy[0] < 0) {
                        continue;
                    }
//                    print($dir . ":" . print_r($xy, 1));
                    break;
                case 3:
                    $xy[1] --;
                    if ($xy[1] < 0) {
                        continue;
                    }
//                    print($dir . ":" . print_r($xy, 1));
                    break;
            }
            if ($cluster[$xy[1]][$xy[0]])
                continue; // already used
                if ($data[$xy[1]][$xy[0]] < $threshold) // signal too weak
                continue; // already used
            $queue[] = $xy;
            $cluster[$xy[1]][$xy[0]] = true;
Andrey Filippov's avatar
Andrey Filippov committed
760 761 762 763 764 765 766 767 768 769 770
            if (! in_array($data[$xy[1]][$xy[0]], $HUGHES_BAD_STRENGTHS)) { // use for the wave, but do not use for polynimial maximum
                $poly_data[] = array(
                    array(
                        $xy[0] - $argmax[0],
                        $xy[1] - $argmax[1]
                    ),
                    array(
                        $data[$xy[1]][$xy[0]]
                    )
                );
            }
Andrey Filippov's avatar
Andrey Filippov committed
771 772
        }
    }
Andrey Filippov's avatar
Andrey Filippov committed
773 774 775 776 777 778 779
    if ($dbg_file !== null) {
        fprintf($dbg_file, "*** sizeof(poly_data)=".sizeof($poly_data)."\n");
    }
    
//    print ("*** sizeof(poly_data)=".sizeof($poly_data)."\n");
    if ($dbg_file !== null) {
        fprintf($dbg_file,"argmax= (x=%d ,y=%d), max = %f, threshold = %f\n",
Andrey Filippov's avatar
Andrey Filippov committed
780 781 782 783 784
            $argmax[0], $argmax[1], $max, $threshold);
        
        for ($i = 0; $i < $rows; $i ++) {
            for ($j = 0; $j < $cols; $j ++) {
                if (($i==$argmax[1]) && ($j==$argmax[0])) {
Andrey Filippov's avatar
Andrey Filippov committed
785
                    fprintf($dbg_file,"[%02d]", $data[$i][$j]);
Andrey Filippov's avatar
Andrey Filippov committed
786
                } else if ($cluster[$i][$j] > 0) {
Andrey Filippov's avatar
Andrey Filippov committed
787
                    fprintf($dbg_file,"<%02d>", $data[$i][$j]);
Andrey Filippov's avatar
Andrey Filippov committed
788
                } else {
Andrey Filippov's avatar
Andrey Filippov committed
789
                    fprintf($dbg_file," %02d ", $data[$i][$j]);
Andrey Filippov's avatar
Andrey Filippov committed
790 791
                }
            }
Andrey Filippov's avatar
Andrey Filippov committed
792
            fprintf($dbg_file,"\n");
Andrey Filippov's avatar
Andrey Filippov committed
793 794 795 796 797 798 799 800 801 802 803 804
        }
    }
    
    $pa = new PolynomialApproximation();
    $pa->debugLevel = 1;
    $pa->debugFile = $dbg_file;
    
    
    $rslt = $pa->quadraticMax2d($poly_data);
    if ($rslt == null){
        return null;
    }
Andrey Filippov's avatar
Andrey Filippov committed
805
    $rslt_dbg =$rslt;
Andrey Filippov's avatar
Andrey Filippov committed
806 807 808 809 810
    $rslt[0] += $argmax[0];
    $rslt[1] += $argmax[1];
    
    
    if ($dbg_file) {
Andrey Filippov's avatar
Andrey Filippov committed
811 812
        fprintf($dbg_file, "argmax= (x=%d ,y=%d), max = %f, threshold = %f, rslt_dbg=(x=%f, y=%f), rslt=(x=%f, y=%f)\n",
            $argmax[0], $argmax[1], $max, $threshold,$rslt_dbg[0],$rslt_dbg[1],$rslt[0],$rslt[1]);
Andrey Filippov's avatar
Andrey Filippov committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
        fprintf($dbg_file, print_r($rslt,1));
    }
    
    if (is_nan($rslt[0]) || is_nan($rslt[1])){
        if ($dbg_file) {
            fprintf($dbg_file, "Could not find maximum (NaN): coeff = \n".print_r($rslt,1)."\n");
        }
        return null; // no maximum
    }
    
    if ($rslt[0] < -($frac_outside * $cols)){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax[0] is too low = %f, range=%d\n",$rslt[0],$cols );
        }
        return null; // az too low
    }
    if ($rslt[0] > ((1.0 + $frac_outside) * $cols)){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax[0] is too high = %f, range=%d\n",$rslt[0],$cols );
        }
        return null; // too low
    }
    if ($rslt[1] < -($frac_outside * $rows)){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax[1] is too low = %f, range=%d\n",$rslt[1],$rows );
        }
        return null; // az too low
    }
    if ($rslt[1] > ((1.0 + $frac_outside) * $rows)){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax[1] is too high = %f, range=%d\n",$rslt[1],$cols );
        }
        return null; // too low
    }
    return $rslt; // $rslt;
}
849 850


851
function findMax1d($data, $fract, $pow, $frac_outside = 0.2){
Andrey Filippov's avatar
Andrey Filippov committed
852
    global $HUGHES_BAD_STRENGTHS, $dbg_file;
853 854 855
    $min= $data[0];
    $max = $data[0];
    $argmax = 0;
856 857 858 859 860 861 862 863 864
    foreach ($data as $k => $v) {
        if (! in_array($v, $HUGHES_BAD_STRENGTHS)) {
            if ($v > $max) {
                $max = $v;
                $argmax = $k;
            } else if ($v < $min) {
                $min = $v;
            }
        }
865
    }
866 867 868 869 870 871 872 873 874
    
    if ($argmax == 0){
        return array('argmax'=>$argmax,'err'=>'first element');
    }

    if ($argmax >= (sizeof($data) -1)){
        return array('argmax'=>$argmax,'err'=>'last element');
    }
    
875
    // ignoring bad strengths (==30) - they will be filtered later
876
    $threshold = $min + ($max-$min) * $fract;
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    $k_min = $argmax;
    while (($k_min > 0) && ($data[$k_min - 1] >= $threshold)){
        $k_min--;
    }
    $k_max = $argmax;
    $last = sizeof($data) - 1;
    while (($k_max < $last) && ($data[$k_max + 1] >= $threshold)){
        $k_max++;
    }
    $datap =  array_fill(0, sizeof($data),0);
    for ($k = $k_min; $k <= $k_max; $k++){
        $datap[$k] = $max - pow($max - $data[$k], $pow);
    }
    
    $poly_data = Array();
    for ($k = $k_min; $k <= $k_max; $k++){
Andrey Filippov's avatar
Andrey Filippov committed
893 894 895 896 897 898
        if (! in_array($datap[$k], $HUGHES_BAD_STRENGTHS)) { // skip samples with "bad" strengths (see explanation in the $HUGHES_BAD_STRENGTHS declaration
            $poly_data[] = Array(
                $k - $argmax,
                $datap[$k]
            );
        }
899 900 901
    }
    
    $pa = new PolynomialApproximation();
Andrey Filippov's avatar
Andrey Filippov committed
902
    $pa->debugLevel = 1;
903
    $pa->debugFile = $dbg_file;
904 905
    $rslt = $pa->polynomialApproximation1d($poly_data, 2);
    
906
    
907
    if ($dbg_file) {
908
        
909 910
        fprintf($dbg_file, "argmax= %d , k_min= %d, k_max = %d, max = %f, threshold = %f, rslt:\n",
            $argmax, $k_min, $k_max, $max, $threshold);
911 912 913 914 915 916 917 918 919 920 921 922 923 924
        fprintf($dbg_file, print_r($rslt,1));
        $pre = array_fill(0, sizeof($data),0);
        $diff= array_fill(0, sizeof($data),0);
        for ($k = $k_min; $k <= $k_max; $k++){
            $x = $k-$argmax;
            $pre[$k]=$rslt[0]+$rslt[1]*$x+$rslt[2]*$x*$x;
            $diff[$k]=$pre[$k]-$datap[$k];
        }
        
        for ($k = $k_min; $k <= $k_max; $k++){
            fprintf($dbg_file, "[%02d]: %8.3f %8.3f %8.3f %8.3f\n", $k, $data[$k], $datap[$k], $pre[$k], $diff[$k]);
        }
        fprintf($dbg_file, "poly_data= \n".print_r($poly_data,1)."\n");
        
925 926
    }
    
927 928 929 930
    if (is_nan($rslt[0]) || is_nan($rslt[1]) || is_nan($rslt[2])){
        if ($dbg_file) {
            fprintf($dbg_file, "Could not find maximum (NaN): coeff = \n".print_r($rslt,1)."\n");
        }
931
        return array('argmax'=>$argmax,'err'=>'NaN coefficients');
932 933 934
    }
    
    
935 936
    if ($rslt[2] >= 0){
        if ($dbg_file) {
937
            fprintf($dbg_file, "Could not find maximum coeff = \n".print_r($rslt,1)."\n");
938
        }
939
        return array('argmax'=>$argmax,'err'=>'a2 >= 0');
940 941 942 943 944 945 946
    }
    $rel_argmax = $argmax - $rslt[1] / (2 * $rslt[2]);
    if ($rel_argmax < -($frac_outside * sizeof($data))){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax is too low = %f, range=%d\n",$rel_argmax,sizeof($data) );
        }
        
947
        return array('argmax'=>$rel_argmax,'err'=>'too low');
948 949 950 951 952
    }
    if ($rel_argmax > ((1.0 + $frac_outside) * sizeof($data))){
        if ($dbg_file) {
            fprintf($dbg_file, "argmax is too high = %f, range=%d\n",$rel_argmax,sizeof($data) );
        }
953
        return array('argmax'=>$rel_argmax,'err'=>'too high');
954
    }
955
    return array('argmax'=>$rel_argmax,'err'=>null); // $rslt;
956
}
957

Andrey Filippov's avatar
Andrey Filippov committed
958 959 960 961 962 963 964 965 966 967 968
/**
 * Scan rectangular AZ/EL window arownd expected satellite position, alternating 
 * azimuth directions and increasing elevation offset.
 * Start with expected elevation and low az margin, scan azimuth to high margin,
 * then alternatively increase/decrease elevation
 * @param  $threshold - minimal modem signal strength
 * @param  $DishAngleCenter - array of (elevation, azimuth, skew) in degrees,
 *                            corresponding to the center of the scan window
 * @param  $wnd_az - full range of azimuth scan in degrees
 * @param  $wnd_el - full range of elevation scan in degrees
 * @param  $scan_step - elevation scan step
969 970
 * @param  $dir - 0: start scanning from right to left, 1 : first scan from left to right,
 *                    null - determine direction automatically from the current azimuth 
Andrey Filippov's avatar
Andrey Filippov committed
971
 * @return SimpleXMLElement - 
972
 */
973
function scan_window($threshold, $DishAngleCenter, $wnd_az, $wnd_el, $scan_step, $dir = null){
Andrey Filippov's avatar
Andrey Filippov committed
974
    global $motosat_url,$LATE_STOP_AZ,$dbg_file;
975 976 977 978 979 980
    if ($dir === null) {
        $xml_state = simplexml_load_file($motosat_url);
        $DishAnglesNow = getDishAngles($xml_state); // will go there if failed
        $dir = ($DishAnglesNow[0] < $DishAngleCenter[0]) ? 1 : 0;
    }
    
Andrey Filippov's avatar
Andrey Filippov committed
981
    $DishAngle = Array($DishAngleCenter[0],$DishAngleCenter[1],$DishAngleCenter[2]);
Andrey Filippov's avatar
Andrey Filippov committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995
    for ($delta_el = 0.0; $delta_el < $wnd_el/2; $delta_el += $scan_step) {
        $passes = ($delta_el > 0.0)? 2 : 1;
        for ($pass = 0; $pass < $passes; $pass++) {
//        for ($dir = 0; $dir < 2; $dir++) {
            if ($dir > 0){
                $DishAngle[1] = $DishAngleCenter[1] + $delta_el;
                $az_start =     $DishAngleCenter[0] + $wnd_az/2;
                $az_end =       $DishAngleCenter[0] - $wnd_az/2;
            } else {
                $DishAngle[1] = $DishAngleCenter[1] - $delta_el;
                $az_start =     $DishAngleCenter[0] - $wnd_az/2;
                $az_end =       $DishAngleCenter[0] + $wnd_az/2;
            }
            
Andrey Filippov's avatar
Andrey Filippov committed
996
             $DishAngle[0] = $az_start;
Andrey Filippov's avatar
Andrey Filippov committed
997 998
             
             if ($dbg_file) {
Andrey Filippov's avatar
Andrey Filippov committed
999
                 fprintf($dbg_file, "\ndir=%d:\n",$dir);
Andrey Filippov's avatar
Andrey Filippov committed
1000 1001 1002 1003 1004
                 fprintf($dbg_file, "wnd_az=%f:\n",$wnd_az);
                 fprintf($dbg_file, "wnd_el=%f:\n",$wnd_el);
                 fprintf($dbg_file, "threshold=%f:\n",$threshold);
                 fprintf($dbg_file, "scan_step=%f:\n",$scan_step);
                 fprintf($dbg_file, "DishAngle - start:\n");
1005
                 fprintf($dbg_file, str_replace("\n"," ",print_r($DishAngle,1))."\n");
Andrey Filippov's avatar
Andrey Filippov committed
1006
                 fprintf($dbg_file, "DishAngleCenter - start:\n");
1007
                 fprintf($dbg_file, str_replace("\n"," ",print_r($DishAngleCenter,1))."\n");
Andrey Filippov's avatar
Andrey Filippov committed
1008
             }
1009 1010
//             while (null !==moveElAzSk_degrees($DishAngle)); // returns number of steps
             moveElAzSk_degrees($DishAngle); // returns number of steps
Andrey Filippov's avatar
Andrey Filippov committed
1011
             $DishAngle[0] = $az_end;
Andrey Filippov's avatar
Andrey Filippov committed
1012 1013 1014
             
             if ($dbg_file) {
                 fprintf($dbg_file, "\nDishAngle - end:\n");
1015
                 fprintf($dbg_file, str_replace("\n"," ",print_r($DishAngle,1))."\n");
Andrey Filippov's avatar
Andrey Filippov committed
1016 1017
             }
             
Andrey Filippov's avatar
Andrey Filippov committed
1018 1019
             moveElAzSk_start_degrees($DishAngle);
             $scan_rslt = waitMotorsReady($threshold);
Andrey Filippov's avatar
Andrey Filippov committed
1020 1021 1022
             if ($dbg_file) {
                 fprintf($dbg_file, "-----scan_rslt=%d:\n",$scan_rslt);
             }
Andrey Filippov's avatar
Andrey Filippov committed
1023 1024
             if ($scan_rslt < 0) {
                 $xml_state = simplexml_load_file($motosat_url);
Andrey Filippov's avatar
Andrey Filippov committed
1025
                 if ($dbg_file) {
1026
                     $DishAngle = getDishAngles ($xml_state);
1027 1028
                     fprintf($dbg_file, "\n***** DishAngle - after hitting/stopped:\n");
                     fprintf($dbg_file, str_replace("\n"," ",print_r($DishAngle,1))."\n");
Andrey Filippov's avatar
Andrey Filippov committed
1029 1030 1031 1032
                 }
                 
                 //,$LATE_STOP_AZ
                 //move az back to compensate for late stop
1033
                 $DishCount =  getDishCounts($xml_state);
Andrey Filippov's avatar
Andrey Filippov committed
1034
                 if ($dir > 0){
Andrey Filippov's avatar
Andrey Filippov committed
1035 1036 1037 1038 1039 1040 1041
                     $DishCount[0] += $LATE_STOP_AZ;
                 } else {
                     $DishCount[0] -= $LATE_STOP_AZ;
                 }
                 moveElAzSk_counts($DishCount);
                 if ($dbg_file) {
                     $xml_state = simplexml_load_file($motosat_url);
1042
                     $DishAngle = getDishAngles ($xml_state);
Andrey Filippov's avatar
Andrey Filippov committed
1043
                     fprintf($dbg_file, "\nDishAngle - after backing:\n");
1044
                     fprintf($dbg_file, str_replace("\n"," ",print_r($DishAngle,1))."\n");
Andrey Filippov's avatar
Andrey Filippov committed
1045
                 }
1046
                 $xml_state->addChild ('Success',(string) 1 );
Andrey Filippov's avatar
Andrey Filippov committed
1047 1048
                 return $xml_state;
             }
Andrey Filippov's avatar
Andrey Filippov committed
1049
        }
1050
        $dir = 1 - $dir;
Andrey Filippov's avatar
Andrey Filippov committed
1051 1052
    }
    moveElAzSk_degrees($DishAngleCenter);
1053 1054
//    while (null !==moveElAzSk_degrees($DishAngleCenter));
    moveElAzSk_degrees($DishAngleCenter);
Andrey Filippov's avatar
Andrey Filippov committed
1055
    $xml_state = simplexml_load_file($motosat_url);
1056
    $xml_state->addChild ('Success',(string) 0 );
Andrey Filippov's avatar
Andrey Filippov committed
1057 1058
    return $xml_state;
}
1059 1060
//<b>49</b>
//<b><font color=red>9</font></b>
Andrey Filippov's avatar
Andrey Filippov committed
1061
function getModemStrength(){ //0.2sec
1062
    global $modem_strengt_url,$dbg_file;
1063 1064 1065
    $modem_page=file_get_contents($modem_strengt_url);
//    $pstr="@<b>([^<]*)</b>@i";
    $pstr="@<b>(<font[^>]*>)?([^<]*)</@i";
1066
    $matches=null; // just define
1067 1068 1069
    preg_match($pstr,$modem_page, $matches);
//    return myfval($matches[1]);
    return myfval($matches[2]);
1070 1071 1072
}

function moveElAzSk_start_counts($new_azelsk_count) {
Andrey Filippov's avatar
Andrey Filippov committed
1073
    global $motosat_url, $AZ_CMAX, $EL_CMAX, $SK_CMAX,$OVERSHOOT,$dbg,$dbg_file;
1074
    $xml_state = simplexml_load_file($motosat_url);
1075
    $DishCount =  getDishCounts($xml_state);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    if ($DishCount[0] < 0) $DishCount[0] = 0;
    if ($DishCount[1] < 0) $DishCount[1] = 0;
    if ($DishCount[2] < 0) $DishCount[2] = 0;

    if ($DishCount[0] > $AZ_CMAX) $DishCount[0] = $AZ_CMAX;
    if ($DishCount[1] > $EL_CMAX) $DishCount[1] = $EL_CMAX;
    if ($DishCount[2] > $SK_CMAX) $DishCount[2] = $SK_CMAX;
    
    $dist_el = $new_azelsk_count[1] - $DishCount[1];
    $dist_sk = $new_azelsk_count[2] - $DishCount[2];
    $dist_az = $new_azelsk_count[0] - $DishCount[0];
Andrey Filippov's avatar
Andrey Filippov committed
1087 1088 1089
    if (abs ($dist_el) <= $OVERSHOOT) $dist_el = 0;
    if (abs ($dist_sk) <= $OVERSHOOT) $dist_sk = 0;
    if (abs ($dist_az) <= $OVERSHOOT) $dist_az = 0;
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    $dir =  "Up";
    $dist = 0;

    /*
     * $dist_el > 0 do it first, $dist_el < 0 - do it last 
     */    
    
    
//  if ($dist_el != 0){
    if ($dist_el > 0){
        // moving elevation up first
        $mode = "El";
        $dist = $dist_el;
        
    } else if ($dist_sk != 0){
        // moving skew second
        $mode = "Sk";
        $dist = $dist_sk;
    } else if ($dist_az != 0){
        // moving azimuth third
        $mode = "Az";
        $dist = $dist_az;
    } else if ($dist_el < 0){
        // moving elevation down last
        $mode = "El";
        $dist = $dist_el;
    }
    if ($dist != 0){
        if ($dist > 0){
            $dir =  "Up";
        } else {
            $dir =  "Dn";
        }
        $dist = abs($dist);
        $url = $motosat_url."?Action=".$mode.$dir.'&Distance='.$dist."&Units=0";
1125 1126 1127
        if ($dbg_file) {
            fprintf($dbg_file, "moveElAzSk_start_counts(): url = %s:\n",$url);
        }
Andrey Filippov's avatar
Andrey Filippov committed
1128
        if (false && $dbg_file) {
1129
                fprintf($dbg_file, "new_azelsk_count:\n");
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
            fprintf($dbg_file, print_r($new_azelsk_count,1));
            fprintf($dbg_file, "DishCount:\n");
            fprintf($dbg_file, print_r($DishCount,1));
        }
        if ($dbg) {
            echo "<!--";
            var_dump($new_azelsk_count);
            var_dump($DishCount);
            var_dump($url);
            $url = $motosat_url;
            echo "-->";
        }
        $xml_state = simplexml_load_file($url);
        return $xml_state;
    }
    return; // return null - no rotation is needed
}

function moveElAzSk_start_degrees($new_azelsk_degree) {
    global $AZ_0, $EL_0, $SK_0, $AZ_CPD, $EL_CPD, $SK_CPD,$dbg,$dbg_file;
    $new_azelsk_count = Array (
        (int) round(($new_azelsk_degree[0] + $AZ_0)*$AZ_CPD),
        (int) round(($new_azelsk_degree[1] + $EL_0)*$EL_CPD),
        (int) round(($new_azelsk_degree[2] + $SK_0)*$SK_CPD));

    if ($dbg_file) {
        $new_azelsk_count_dbg = Array (
            ($new_azelsk_degree[0] + $AZ_0)*$AZ_CPD,
            ($new_azelsk_degree[1] + $EL_0)*$EL_CPD,
            ($new_azelsk_degree[2] + $SK_0)*$SK_CPD);
1160 1161 1162
        fprintf($dbg_file, ".... moveElAzSk_start_degrees(): new_azelsk_degree: ");
        fprintf($dbg_file, str_replace("\n"," ",print_r($new_azelsk_degree,1))."\n");
 //       fprintf($dbg_file, "new_azelsk_count_dbg:\n"); 
Andrey Filippov's avatar
Andrey Filippov committed
1163 1164 1165
 //       fprintf($dbg_file, print_r($new_azelsk_count_dbg,1));
 //       fprintf($dbg_file, "new_azelsk_count:\n");
 //       fprintf($dbg_file, print_r($new_azelsk_count,1));
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    }
    if ($dbg) {
        $new_azelsk_count_dbg = Array (
        ($new_azelsk_degree[0] + $AZ_0)*$AZ_CPD,
        ($new_azelsk_degree[1] + $EL_0)*$EL_CPD,
        ($new_azelsk_degree[2] + $SK_0)*$SK_CPD);
        echo "<!--";
        var_dump($new_azelsk_degree);
        var_dump($new_azelsk_count_dbg);
        var_dump($new_azelsk_count);
        echo "-->";
    }
    return moveElAzSk_start_counts($new_azelsk_count);
}

Andrey Filippov's avatar
Andrey Filippov committed
1181 1182 1183 1184
/**
 * Wait motors stopped and optionally modem strength > threshold
 * Can be improved slightly by curl-multi:  reading modem - 0.2s, controller - 0.29s
 * @param $modem_threshold - if >0, stop on modem strength above threshold
Andrey Filippov's avatar
Andrey Filippov committed
1185
 * @return: 0: no movement needed, >0 - number of status requests, <0 - -SignalQuality
Andrey Filippov's avatar
Andrey Filippov committed
1186 1187
 */
function waitMotorsReady($modem_threshold = 0.0){ //
Andrey Filippov's avatar
Andrey Filippov committed
1188
    global $motosat_url,$dbg_file;
1189 1190 1191 1192 1193 1194
    $busy = true;
    $try = 0;
    while ($busy) {
        $xml_state = simplexml_load_file($motosat_url);
        $State =          $xml_state->State+0; // 1 - Ready, 2 - Busy
        $busy = ($State & 2) != 0;
Andrey Filippov's avatar
Andrey Filippov committed
1195
        if ($modem_threshold > 0){
Andrey Filippov's avatar
Andrey Filippov committed
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
            $SignalQuality = myfval(explode(",",$xml_state->SignalQuality)[0]);
            if ($SignalQuality > $modem_threshold) {
                $url = $motosat_url."?Action=Stop&Distance=0&Units=0";
                $xml_state1 = simplexml_load_file($url);
                if ($dbg_file) {
                    fprintf($dbg_file, "SignalQuality= %f:\n",$SignalQuality);
                }
                
                while ($busy) {
                    $xml_state1 = simplexml_load_file($motosat_url);
                    $State =          $xml_state1->State+0; // 1 - Ready, 2 - Busy
                    $busy = ($State & 2) != 0;
                    if ($dbg_file) {
                        fprintf($dbg_file,$busy); 
                        fprintf($dbg_file, " %03d State= %d:\n",$try,$State);
                    }
                    
                }
                // Now move back to where good signal strength was detected
1215
                $DishCountGood =  getDishCounts($xml_state);
Andrey Filippov's avatar
Andrey Filippov committed
1216 1217 1218 1219 1220 1221 1222 1223
                moveElAzSk_counts($DishCountGood);
                
                if ($dbg_file) {
                    fprintf($dbg_file, "SignalQuality= %f:\n",$SignalQuality);
                }
                
                return -$SignalQuality;
            }
Andrey Filippov's avatar
Andrey Filippov committed
1224
        }
1225
        $try++;
Andrey Filippov's avatar
Andrey Filippov committed
1226 1227 1228 1229
        if ($dbg_file) {
            fprintf($dbg_file, "%03d State= %d:\n",$try,$State);
        }
        
Andrey Filippov's avatar
Andrey Filippov committed
1230
        //?Action=Stop&Distance=0&Units=0 
1231 1232 1233 1234
    }
    return $try;
}

Andrey Filippov's avatar
Andrey Filippov committed
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
function moveElAzSk_counts($new_azelsk_count, $multi = true)
{
    $total_cycles = 0;
    while (true) {
        $xml_state = moveElAzSk_start_counts($new_azelsk_count);
        if (isset($xml_state)) {
            $cycles = waitMotorsReady();
            $total_cycles += $cycles;
            if (!$multi)
                return $total_cycles;
        } else
            return $total_cycles; // did not move last time
1247 1248 1249
    }
}

Andrey Filippov's avatar
Andrey Filippov committed
1250 1251
function moveElAzSk_degrees($new_azelsk_degree, $multi = true)
{
1252
    global $dbg_file;
Andrey Filippov's avatar
Andrey Filippov committed
1253 1254 1255 1256 1257 1258
    $total_cycles = 0;
    while (true) {
        $xml_state = moveElAzSk_start_degrees($new_azelsk_degree);
        if (isset($xml_state)) {
            $cycles = waitMotorsReady();
            $total_cycles += $cycles;
1259 1260 1261 1262
            if (! $multi) {
                if ($dbg_file) {
                    fprintf($dbg_file, "moveElAzSk_degrees(), multi=" . $multi . ", total_cycles=" . $total_cycles . "\n");
                }
Andrey Filippov's avatar
Andrey Filippov committed
1263
                return $total_cycles;
1264 1265 1266 1267 1268 1269
            }
        } else {
            if ($dbg_file) {
                fprintf($dbg_file, "moveElAzSk_degrees(), multi=" . $multi . ", total_cycles=" . $total_cycles . ", xml_state is NOT set\n");
                // fprintf($dbg_file, print_r(debug_backtrace(),1));
            }
Andrey Filippov's avatar
Andrey Filippov committed
1270
            return $total_cycles; // did not move last time
1271
        }
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    }
}

function myval ($s) {
    $s=trim($s,"\" ");
    if (strtoupper(substr($s,0,2))=="0X")   return intval(hexdec($s));
    else return intval($s);
}

function myfval ($s) {
    $s=trim($s,"\" ");
    return floatval($s);
}
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
/**
 * Get 3 dish angles (az/el/sk) in degrees from the XML data received from controller
 * @param $xml_state : XML data from the controller
 * @return: array of 3 angles (degrees): azimuth, elevation, skew
 */
function getDishAngles($xml_state){
    $DishAngles =     explode(",",$xml_state->DishAngle);
    foreach ($DishAngles as $key => $value){
        $DishAngles[$key] = floatval($value);
    }
    return $DishAngles;
}

/**
 * Get 3 dish angles (az/el/sk) in counts from the XML data received from controller
 * @param $xml_state : XML data from the controller
 * @return: array of 3 angles (counts): azimuth, elevation, skew
 */
function getDishCounts($xml_state){
    $DishCounts =     explode(",",$xml_state->DishCount);
    foreach ($DishCounts as $key => $value){
        $DishCounts[$key] = floatval($value);
    }
    return $DishCounts;
}



1313 1314


Andrey Filippov's avatar
Andrey Filippov committed
1315
?>