dimanche 5 août 2018

OTZ_Auto : finally some automatic observations !

For the last 12 nights, I have been working on a script under PRISM v10 to automate my observations.

First, I groupes together my starting sequence and add some lines to handle the GemBird Power Manager USB and LAN multiple plugs. I have been able to automate completely the sequence except telescope equipment connexion (for some reason, it doesn't work but I haven't spend too much time on this yet), the Power Manager USB connexion (it fails very often) and the telescope resynch at the beginning.
Then I added a way to point to a target with some trick to take care of my strong DEC backlash of my Losmandy Titan mount.




Last, I added the end of night code to close all the equipment and switch off the Power Managers plugs.

Of course it doesn't run always as I wanted, mostly because my coding is "quick & dirty" but I have been able to acquire around 60 spectra (Halpha alone) during 12 nights. I have been able to reach 6-7 targets per night while previous method (run a sequence, go to sleep, wake up, change target, etc...) was running 3 targets usually per night!



What a pleasure to read "DONE" when I wake up, with telescope & cameras stopped and dome closed. I can quickly check with TeamViewer that the script went okay...


I can also quickly look at the guiding image fields (to check the target is the right one) and then reduce all spectra in ISIS and post them on BeSS. I completed the script with a DOS batch to clean up all the temporary files and sort my raw/reduced data in proper directories at the end.

So the script is now at its first version and works fine for me even if some steps at the beginning are manual and I sometimes have trouble with the first autoguiding. It is based on brightest star in the field and tere are LOT of improvement to be added: include a true scheduler, handle weather management, star hopping GoTo for large telescope movements, astrometry, etc... But it does the job for now.

Here is the code for those wanting to play with it, it is delivered "as is" of course.

/////////////////////////////////////////////////////////////////////////////////
//                                                                                                                                                                             //
//                                   OTZ_Auto - Script to observe automatically (c) Olivier Thizy                              //
//                                                                                                                                                                             //
/////////////////////////////////////////////////////////////////////////////////
//
// Some specificities to equipment used:
// -Losmandy Titan mount with strong backlash in Delta
// -echelle spectrograph with Velmann board to control calibration lamps
// -observing bright Be star as primary focus
// -Atik 460ex for spectra acquisition
// -Atik Titan for guiding
// -Dome (controled by Dome TRacker)
// -RoboFocus
//
// BUGS / ROBUSTNESS
// ------------------
// -if object$ is not recognize: skip target
// -end of night, dome disconnected?
// -improve how brighteststar works + error management
// -replace USB by LN gembird
// -pb with telescope connexion (hardware?)
// -sometimes fails at first autoguiding, root cause not found yet
//
// WEATHER MANAGEMENT
// -------------------
// -calibrate Sentinel cloud sensor
// -wait for good weather
// -check weather: pause
// -multiple pause: close equipment
// -rain detection -> wiring to dome tracker
// -sentinel relay script activation
//
// IMPROVEMENTS
// -------------
// -create at the end a clean list at the end of targets acquired + Exp Time + Nb of exposures + Max(kADU) + Elevation (copy/paste in Excel ObsLog)
// -automatic guiding exposure based on Vmag
// -catalog of Be stars with Vmag, ra, dec, HD #, exposure time & nbExposures
// -automatic scheduling based on priority & time allocation
// -catalog of bright isolated stars
// -goto with star hopping
// -improve simulator mode to estimate the total time of a session
// -add management of star to Synch at the end of a session to "park" scope
// -stop telescope tracking while waiting for next target
// -use external text file for the list of targets, read it every loop to allow change during the night/session
//
// REVISION HISTORY
// ----------------
// -05/08/2018: first "stable version", target list inside script, some bugs (telescope connexion, USB Gembird, first autoguiding).
//    Lack weather management, good target catalog, star hopping method for large GoTo, etc... some comments in french.
//    Based on brightest star in the field, very specific to my own equipment. 60 Be stars spectra (Halpha) acquired so far with the script.
//
/////////////////////////////////////////////////////////////////////////////////

print "OTZ_Auto: automatic observation script (c) Olivier Thizy"
print "Version of 05/08/2018"

// Key debug/temporary parameters to control manual interventions...
//     OpenDomeManually: Set to 1 if you want to open dome manually (to wait for better sky conditions for exemple)
//     RequestManualInitialSynch: set to 1 if you want to manually synch telescope to first star
//     CheckIfPowerManagerIsOK: set to 1 to make a double check of the Power Manager as USB isn't always working properly
//     ConnectTelescopeManually: set to 1 if you want to connect manually telescope/equipment in prism
//   Simulation: set to 1 to estimate the ability to run the night with the given targets
// Note: for full automated observations all parameters should be to 0
OpenDomeManually=1
CheckIfPowerManagerIsOK=0
ConnectTelescopeManually=1
RequestManualInitialSynch=1
Simulation=0

//
// General parameters
//
// do not point telescope past meridian
AngleHorMin=0
// do not observe below... (in °)
HauteurMin=40
// fiber position
GuidePosX=291.0
GuidePosY=213.0
// For Atik 460ex camera, cooling in 15 minutes to -10°C (winter) or 0°C (summer) seems enough
minutestogodowntotemp=20
Detectortemperature=0.0
// Elevation of the sun at which we start the instrumentation (degrees converted to radians)
// I usually start equipment when Sun is below 0°, start calibration when below 4° in order to start observing when below -8°
elevsunstartinitnight_Deg=-1.0
elevsunstartbegnight_Deg=-4.0
elevsunstartobservations_Deg=-7.0
elevsunstopobservations_Deg=-7.0
// CCD numbers
GuidingCamNumber=1
AcqCamNumber=2
// difference between local time and UT
deltaUT=-1
// time (in milliseconds) to wait after GoTo so dome can be synch' with telescope
WaitForDomeTime=60000
// Sentinel weather station parameters
LimitTempCiel=-100.0
LimitMagnitudeCiel=-100.0
ValMinBelleMeteo=5
// for simulation purposes
TotalExpTimeForSession=0


if Simulation=0 then
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Starting Calibration sequence"

//    GoSub Start_and_Calib:

    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Calibration sequence done"
endif



// Just to test it...
//GoSub BoucleAttendBeauTemp:

if Simulation=0 then
    // Resynch telescope on delta Her
    if RequestManualInitialSynch=1 then
        Input "TEST: ensure telescope is synch (& focused ?) near to first target - then press ENTER" Dummy$
    else
    goto SkipThisSynch:
        // Synch sequence for the beginning of the bight
        // bet Oph
        objet$="hd161096"
        GExpTime=0.1
        GoSub StarHopping:
        // zet Aql
        objet$="hd177724"
        GExpTime=0.1
        GoSub StarHopping:
        // nu Oph
        objet$="hd163917"
        GExpTime=0.1
        GoSub StarHopping:
        // eta Ser
        objet$="hd68723"
        GExpTime=0.1
        GoSub StarHopping:
    SkipThisSynch:
    endif
endif

Target[1]$="QRVul"
Target[2]$="lamCyg"
Target[3]$="omiAnd"
Target[4]$="V442And"
Target[5]$="phiAnd"
Target[6]$="V549Per"
NbTargets=6

for NumeroObject=1 to NbTargets
    Object$=Target[NumeroObject]$
    if Simulation=0 then
        GoSub TakeObject:
    else
        GoSub LookUpObject:
        TotalExpTimeForSession=TotalExpTimeForSession+ExpSec*NbExposure
    endif
next NumeroObject


if Simulation=1 then
    str TotalExpTimeForSession TotalExpTimeForSession$
    TotalExpTimeForSessionMin=(TotalExpTimeForSession/60)
    round TotalExpTimeForSessionMin TotalExpTimeForSessionMin
    str TotalExpTimeForSessionMin TotalExpTimeForSessionMin$
    TotalExpTimeForSessionHours=(TotalExpTimeForSession/3660)
    round TotalExpTimeForSessionHours TotalExpTimeForSessionHours
    str TotalExpTimeForSessionHours TotalExpTimeForSessionHours$
    print "Total Exposure should be: " TotalExpTimeForSession$ " sec., " TotalExpTimeForSessionMin$ " min., " TotalExpTimeForSessionHours$ " hours."
    end
endif

GoTo FinishScriptHere:

EndOfSession:
// END OF SESSION
print "-----------------------------------------------------------"
EquipmentClosed=0
// Synch on bet And first
GoSub IsSunStillBelow:
if SunStillBelow=1 then
    objet$="hd6860"
    GExpTime=0.1
    GoSub StarHopping:
else
    GoSub endnight:
    GoTo EndOfMainSequence:
endif
// Synch on eta Psc then
GoSub IsSunStillBelow:
if SunStillBelow=1 then
    objet$="hd9270"
    GExpTime=0.1
    GoSub StarHopping:
else
    GoSub endnight:
    GoTo EndOfMainSequence:
endif


FinishScriptHere:
GoSub endnight:

EndOfMainSequence:

// Et message de fin...
Now Date
Datetostr Date Date$
print "[" Date$ "] That's all folks..."

sOutput$=" "
Print sOutput$

sOutput$="DDD     OOO  N    N EEEEE"
Print sOutput$
sOutput$="D  D   O   O N N  N E    "
Print sOutput$
sOutput$="D   D  O   O N  N N EEE  "
Print sOutput$
sOutput$="D  D   O   O N   NN E    "
Print sOutput$
sOutput$="DDD     OOO  N    N EEEEE"
Print sOutput$

sOutput$=" "
Print sOutput$


END



/////////////////////////////////////////////////////////////////////////////////
//
// Goto a target, center object, run autoguiding and acquire spectra
//
/////////////////////////////////////////////////////////////////////////////////
GoToTargetAndAcquisition:


print "-----------------------------------------------------------"

REM Coordonnées équatoriales de l'objet en radians
GETOBJECTCOORD objet$ alpha delta

if alpha=-100
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] L'objet " objet$ " n'est pas reconnu par PRISM !"
  return
endif

str alpha alphaRad$
str delta deltaRad$
RAD_TO_RA  alpha alpha$
RAD_TO_DEC delta delta$

Now Date
Datetostr Date Date$
PRINT "[" Date$ "] " Object$ " (" objet$ ") is at coordinates :"
PRINT "[" Date$ "] RA  : " alpha$ " (" alphaRad$ " radians)"
PRINT "[" Date$ "] DEC : " delta$ " (" deltaRad$ " radians)"

//Longitude du lieu = celle du site par défaut
GETSTDRLONGITUDE Longitude
// Latitude du lieu
GETSTDRLATITUDE Latitude
// Loop to wait for the target to reach proper altitude in the sky
LoopWaitHauteur:
// Date du moment :
NOW Date
// Hauteur de l'objet en radian :
GETHEIGHT alpha delta Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   stoptelescope
   DelayBlock 60000
   Goto LoopWaitHauteur:
endif


// Look for telescope position at the end of acquisition to check if not past meridian+limit / give 50% margin to allow half exposure...
// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL alpha AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI
AngleHorEndOfExposure=AngleHor+((ExpSec*NbExposure)/3600.0)/2.0

AngleHorLimit=0.0
// si DEC<45°: 10min supplémentaires
if delta<(45.0/180.*3.1415) then
    AngleHorLimit=10.0/60.0
endif
// si DEC<30°: 20min supplémentaires
if delta<(30.0/180.*3.1415) then
    AngleHorLimit=20.0/60.0
endif
// si DEC<25°: 1h10 supplémentaires
if delta<(25.0/180.*3.1415) then
    AngleHorLimit=70.0/60.0
endif
// si DEC<6°: 1h45 supplémentaires
if delta>(6.0/180.*3.1415) then
    AngleHorLimit=105.0/60.0
endif

if AngleHorEndOfExposure>AngleHorLimit
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target at the end of the sequence will be at hour angle: " AngleHorEndOfExposure " so target skipped"
   return
endif


// Pointage ou non ?
If AngleHor<AngleHorMin then
    If Hauteur>HauteurMin then
        str Hauteur Hauteur$
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] GoTo Target at Elevation : " Hauteur$ "°"
        MoveTelescope alpha delta
        WaitForEndMoveTelescope
        DelayBlock 20000
        deltaplus=delta+0.003
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        DelayBlock 10000
        // Je pointe un peu en dessous de la fibre pour toujours arriver par ce côté pour le centrage/guidage
        deltaplus=delta+0.00015
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        DelayBlock 10000
    Else
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Target too low"
        return
    EndIf
Else
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Target too close to meridian"
    return
EndIf

Now Date
Datetostr Date Date$
print "[" Date$ "] Telescope at target position now"


// Wait for the dome
Now Date
Datetostr Date Date$
print "[" Date$ "] Waiting for the dome"
DelayBlock WaitForDomeTime
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome should be at telescope position now"


REM *** calculating night's date

NOW year month day hour minute second MS

lengthmonth[1]=31
REM bissextile years
yearfrac=year/4
frac yearfrac bissextile
if bissextile=0 then
   lengthmonth[2]=29
else
   lengthmonth[2]=28
endif
lengthmonth[3]=31
lengthmonth[4]=30
lengthmonth[5]=31
lengthmonth[6]=30
lengthmonth[7]=31
lengthmonth[8]=31
lengthmonth[9]=30
lengthmonth[10]=31
lengthmonth[11]=30
lengthmonth[12]=31

if hour<12 then
   if day=1 then
      if month=1 then
         year=year-1
         month=12
         day=31
      else
         month=month-1
      endif
      day=lengthmonth[month]
   else
      day=day-1
   endif
endif

str year year$

str month month$
if month<10 then
   month$="0"+month$
endif

str day day$
if day<10 then
   day$="0"+day$
endif

CurrentDate$=year$+month$+day$

// set directory to save file and copy CALIB files in
sDirSave$="C:\Users\ObsBE\Documents\Acquisitions\"+CurrentDate$+"_eShel101_Atik460-1x1_38420_Revel\"


// Centrage étoile la plus brillante sur la consigne
GExpTimeMilSec=GExpTime*1000
GExpTimeChamp=GExpTimeMilSec*10
StartExposure_EX 1 GExpTimeMilSec
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChampToCenter
sFullPath$=sDirSave$+"ATIK HS "+Object$+"_center.fits"
SAVEFIT ImgChampToCenter sFullPath$
MinDynamiqueAutoguidage=500
MaxDynamique=55000
MaxOmC=900
PSFMin=3
DemLargFenCentro=32
ZoneRecherche=26
BRIGHTEST_STAR ImgChampToCenter MinDynamiqueAutoguidage MaxDynamique MaxOmC PSFMin DemLargFenCentro ZoneRecherche XGuideCentro YGuideCentro
if XGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
if YGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
str XGuideCentro XStar$
str YGuideCentro YStar$
Now Date
Datetostr Date Date$
print "[" Date$ "] Star found at position " XStar$ ", " YStar$
// Je centre un peu en dessous de la fente pour que l'autoguidage fonctionne toujours dans ce sens (tube à l'Ouest)
GuidePosYDecale=GuidePosY-5
str GuidePosX GuidePosX$
str GuidePosY GuidePosY$
str GuidePosYDecale GuidePosYDecale$
Now Date
Datetostr Date Date$
print "[" Date$ "] Centering at position " GuidePosX$ ", " GuidePosYDecale$ "; Fiber at " GuidePosX$ ", " GuidePosY$
OFFSET_TELESCOPE ImgChampToCenter XGuideCentro YGuideCentro GuidePosX GuidePosYDecale
WAITFORENDMOVETELESCOPE
DelayBlock 2000
CLOSE ImgChampToCenter

GExpTimeChamp=GExpTimeMilSec*40
StartExposure_EX 1 GExpTimeChamp
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChamp


// Sauvegarde de l'image de guidage surexposée (FITS et JPG)
sFullPath$=sDirSave$+"ATIK HS "+Object$+".fits"
SAVEFIT ImgChamp sFullPath$
sFullPath$=sDirSave$+"ATIK HS "+Object$+".jpg"
SAVEJPG ImgChamp sFullPath$
CLOSE ImgChamp

DelayBlock 5000
   

// Run autoguiding
NumCam=1
CCDNum=1
DelayACQSec=5
WindowSize=200
CentroSize=25
StarThresADU=200
RaMin=5.0
RaMax=210
DecMin=5.0
DecMax=210
Backlash=0
CurrentDEC=0
AlarmEnabled=0
GuidePosX=291.0
GuidePosY=213.0
DeltaMoveFashion=0
SaveImagettes=0
DirSaveImg$="c:\ccd"
AllFrame=1
AgressRA=0.4
AgressDEC=0.4
WindowAllFrame=400

Now Date
Datetostr Date Date$
print "[" Date$ "] Autoguidage ON"
STARTGUIDECONSIGNE NumCam CCDNum GExpTime DelayACQSec WindowSize CentroSize StarThresADU AgressRA AgressDEC RaMin RaMax DecMin DecMax Backlash CurrentDEC AlarmEnabled DeltaMoveFashion GuidePosX GuidePosY SaveImagettes DirSaveImg$ AllFrame WindowAllFrame Valid message$

DelayBlock 5000

str Valid Valid$
Now Date
Datetostr Date Date$
print "[" Date$ "] Valid: " Valid$ " / Status: " message$

/////////////////////
// Acquiring Target
/////////////////////
ExpTime=ExpSec*1000


REM StatWindow Img  X1  Y1  X2  Y2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
HaX1=864
HaY1=1710
HaX2=984
HaY2=1722
ContX1=1543
ContY1=1640
ContX2=1588
ContY2=1189

WinPosX=500
WinPosY=100
WinSizeX=1000
WinSizeY=1000



str ExpSec ExpSec$
str NbExposure NbExposure$

sOutput$="Starting sequence for Target: "+Object$+" ("+NbExposure$+" x "+ExpSec$+" seconds)"
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] " sOutput$
sOutput$="Target filename: "+Object$
Now Date
Datetostr Date Date$
print "[" Date$ "] " sOutput$

GetStdrLongitude Longitude
GetStdrLatitude Latitude
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
GET_TELESCOPE_POSITION Alpha2000 Delta2000 Hauteur Azimuth AngleHor
Hauteur=Hauteur*TODEG
AngleHor=AngleHor*TODEG/15.0
round Hauteur Hauteur
AngleHor=AngleHor*10.0
round AngleHor AngleHor
AngleHor=AngleHor/10.0
str Hauteur Hauteur$
str AngleHor AngleHor$
print "[" Date$ "] Sun at " ElevationS$ "°, Telescope at " Hauteur$ "° & Hour Angle: " AngleHor "h"

MaxHaAvg=0
MaxContAvg=0
NbMeasures=0

For i=1 NbExposure
  // Ensure proper Dome tracking - just to make sure...
  DOME_SET_CONTROL 1 1

  GoSub CanIContontinueToObserve:

  if ContinueObservations=0 then
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Sun too high, stopping observations"
    GoTo EndOfGoToTargetAndAcquisition:
  endif
 
  StartExposure_EX 2 ExpTime
  WaitForEndExposure_EX 2
  GetLastImageExposure_EX 2 img

  STR i i$
  sFullPath$=sDirSave$+Object$+"-"+i$+".fits"
  SAVEFIT img sFullPath$


  StatWindow Img  HaX1  HaY1  HaX2  HaY2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
  MaxHa=Max-Min
  MaxHaAvg=MaxHaAvg+MaxHa
  NbMeasures=NbMeasures+1
  str MaxHa MaxHa$
  StatWindow Img  ContX1  ContY1  ContX2  ContY2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
  MaxCont=Max-Min
  MaxContAvg=MaxContAvg+MaxCont
  str MaxCont MaxCont$
  sOutput$=">>> "+i$+" <<< : Max. Ha="+MaxHa$+" / Continuum="+MaxCont$
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] " sOutput$
  GetStdrLongitude Longitude
  GetStdrLatitude Latitude
  Now Date
  GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
  Datetostr Date Date$
  RAD_TO_DEC sunelevation ElevationS$
  GET_TELESCOPE_POSITION Alpha2000 Delta2000 Hauteur Azimuth AngleHor
  Hauteur=Hauteur*TODEG
  AngleHor=AngleHor*TODEG/15.0
  round Hauteur Hauteur
  AngleHor=AngleHor*10.0
  round AngleHor AngleHor
  AngleHor=AngleHor/10.0
  str Hauteur Hauteur$
  str AngleHor AngleHor$
  print "[" Date$ "] Sun at " ElevationS$ "°, Telescope at " Hauteur$ "° & Hour Angle: " AngleHor "h"

  SetWindowPos img WinPosX WinPosY
  SizeWindowX img WinSizeX
  SizeWindowY img WinSizeY

  Close img
  DelayBlock 3000

Next i

EndOfGoToTargetAndAcquisition:

if NbMeasures>0 then
  MaxHaAvg=MaxHaAvg/NbMeasures
  round MaxHaAvg MaxHaAvg
  MaxContAvg=MaxContAvg/NbMeasures 
  round MaxContAvg MaxContAvg
  str MaxHaAvg MaxHaAvg$
  str MaxContAvg MaxContAvg$
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] STATISTICS: Halpha at " MaxHaAvg$ ", continuum at: " MaxContAvg$
endif

Now Date
Datetostr Date Date$
print "[" Date$ "] Stopping autoguiding"
StopGuide_Ex 1 1

// Synchronise télescope sur la cible pointée (car ça a bougé pendant l'autoguidage)
Now Date
Datetostr Date Date$
print "[" Date$ "] Resynch telescope on position"
CALIBRATE_TELESCOPE alpha delta


return


/////////////////////////////////////////////////////////////////////////////////
//
// Start_and_Calib - Routine to beign the night: connecting equipment, spectral calibration, opening dome...
//
/////////////////////////////////////////////////////////////////////////////////

Start_and_Calib:


// Switch ON Gembird USB & LAN multiplug
if CheckIfPowerManagerIsOK=1 then
    Input "Please check Power Manager is ON, OK and connect to USB socket - then press ENTER" Dummy$
else
    ExecExternal "C:\Program Files\Power Manager\pm.exe" ""
    delayBlock 3000
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Power Manager started"
endif

REM Switch ON the power for the mount, dome & focuser
Now Date
Datetostr Date Date$
print "[" Date$ "] Switching mount, dome & robofocus ON"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -Mount"
delayBlock 1000
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -DomeTracker"
delayBlock 1000
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -RoboFocus"
if ConnectTelescopeManually=1 then
    Input "Please connect Telescope/Dome/Focuser in PRISM... and press ENTER" Dummy$
else
    delayBlock 15000
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Connecting to Telescope/Dome/Focuser"
    CONNECT_OBSERVATORY Valid
    delayBlock 30000
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Stopping the sidereal tracking"
stoptelescope
Now Date
Datetostr Date Date$
print "[" Date$ "] Set dome moving on telescope tracking & GoTo"
DOME_SET_CONTROL 1 1
delayBlock 3000


REM *** calculating night's date

NOW year month day hour minute second MS

lengthmonth[1]=31
REM bissextile years
yearfrac=year/4
frac yearfrac bissextile
if bissextile=0 then
   lengthmonth[2]=29
else
   lengthmonth[2]=28
endif
lengthmonth[3]=31
lengthmonth[4]=30
lengthmonth[5]=31
lengthmonth[6]=30
lengthmonth[7]=31
lengthmonth[8]=31
lengthmonth[9]=30
lengthmonth[10]=31
lengthmonth[11]=30
lengthmonth[12]=31

if hour<12 then
   if day=1 then
      if month=1 then
         year=year-1
         month=12
         day=31
      else
         month=month-1
      endif
      day=lengthmonth[month]
   else
      day=day-1
   endif
endif

str year year$

str month month$
if month<10 then
   month$="0"+month$
endif

str day day$
if day<10 then
   day$="0"+day$
endif

CurrentDate$=year$+month$+day$


REM *** set directory to save file and copy CALIB files in
sDirSave$="C:\Users\ObsBE\Documents\Acquisitions\"+CurrentDate$+"_eShel101_Atik460-1x1_38420_Revel\"
createdir sDirSave$
createdir sDirSave$+"CALIB"
ExecExternal "C:\Users\ObsBE\Documents\Acquisitions\CALIB\CopyDirs.bat" sDirSave$+"CALIB"
createdir sDirSave$+"Poubelle"
createdir sDirSave$+"Raw"
createdir sDirSave$+"Resultats"
Now Date
Datetostr Date Date$
print "[" Date$ "] Tonight directory is: "+sDirSave$




REM *** Waiting for the Sun to be below "elevsunstartinitnight" to start initialising CCD
GetStdrLongitude Longitude
GetStdrLatitude Latitude
REM print "Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG

elevsunstartinitnight=elevsunstartinitnight_Deg/TODEG

beginnighttime:
Now Date
Datetostr Date Date$
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartinitnight_Deg "°)"
if sunelevation>elevsunstartinitnight
   delayBlock 60000
   goto beginnighttime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting up camera and mount"


REM Switch ON Gembird LAN multiplug: calibration unit & Atik460 CCD camera
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -GemBirdLAN -Atik460"
Now Date
Datetostr Date Date$
print "[" Date$ "] Atik 460 camera power ON now"

delayBlock 10000
  

REM *** Initialisations CCDs
Now Date
Datetostr Date Date$
print "[" Date$ "] Connect/Initialise guiding (#1) & acquisition (#2) cameras; cooling the main one"
GoSub init_camera:


elevsunstartbegnight=elevsunstartbegnight_Deg/TODEG

REM *** Waiting for the sun to be below "elevsunstartbegnight", then start telescope & open dome
waittillstarttime:
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartbegnight_Deg "°)"
if sunelevation>elevsunstartbegnight
   delayBlock 60000
   goto waittillstarttime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting the observations"


REM echelle calibration
REM Switch ON Gembird LAN multiplug: calibration unit
Now Date
Datetostr Date Date$
print "[" Date$ "] Switch calibration unit ON & start spectral calibration"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -GemBirdLAN -Calib"

delayBlock 3000
GoSub AcquireCalibration:

REM Switch OFF Gembird LAN multiplug: calibration unit
delayBlock 3000
Now Date
Datetostr Date Date$
print "[" Date$ "] Switch calibration unit OFF"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Calib"


REM *** Waiting for the Sun to be below "elevsunstartobservations" to start observations
GetStdrLongitude Longitude
GetStdrLatitude Latitude
REM print "Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG

elevsunstartobservations=elevsunstartobservations_Deg/TODEG

beginobservationtime:
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartobservations_Deg "°)"
if sunelevation>elevsunstartobservations
   delayBlock 60000
   goto beginobservationtime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting up observations"


// Open DOME and start observations !


if OpenDomeManually=1 then
    Input "Please open Dome when ready - then press ENTER" Dummy$
else
    Open_Dome
    DelayBlock 30000
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome is now open"


Now Date
Datetostr Date Date$
print "[" Date$ "] Starting observing sequence..."


return




/////////////////////////////////////////////////////////////////////////////////
//
// Subroutine to initialize the camera, contains informations and settings of the camera
//
/////////////////////////////////////////////////////////////////////////////////

init_camera:

Now Date
Datetostr Date Date$
print "[" Date$ "] Connecting the Atik Titan guiding camera (1)"
cameraerror$=""
INIT_CCD_CAMERA_EX  GuidingCamNumber Valid  cameraerror$
if Valid=2 then
   nbinning=1
   SetBinningX_Ex GuidingCamNumber nBinning
   SetBinningY_Ex GuidingCamNumber nBinning
else
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] ERREUR initialisation camera 1: Atik Titan"
   print cameraerror$
   EXIT
endif  

REM We start the camera
Now Date
Datetostr Date Date$
print "[" Date$ "] Connecting the Atik 460ex camera (2)"
Detector_number=2
CameraChannel=1
cameraerror$=""
INIT_CCD_CAMERA_EX  AcqCamNumber Valid  cameraerror$
if Valid=2 then
   nbinning=1
   SetBinningX_Ex AcqCamNumber nBinning
   SetBinningY_Ex AcqCamNumber nBinning
   for i=1 to minutestogodowntotemp
      GetCCDTemperature_Ex  AcqCamNumber CameraChannel Starttemperature
      deltaT=Detectortemperature-Starttemperature
      deltaTperminute=deltaT/minutestogodowntotemp
      Now Date
      Datetostr Date Date$
      print "[" Date$ "] Going from " Starttemperature " to " Detectortemperature " we need to cool " deltaTperminute " degrees per minute"
      Currenttemperature=Starttemperature+(deltaTperminute*i)
      round Currenttemperature Currenttemperature
      if Currenttemperature<Detectortemperature+0.2 then
         goto endcooling1:
      else
      SetCCDTemperature_Ex AcqCamNumber CameraChannel Currenttemperature
      Now Date
      Datetostr Date Date$
      print "[" Date$ "] " i " minute, CCD going down to " Currenttemperature " degrees"
      delayBlock 60000
      endif
   next i
else
   REM The camera didn't initialize correctly
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] ERREUR initialisation camera 2: Atik 460ex"
   print cameraerror$
   EXIT
endif  

endcooling1:
Now Date
Datetostr Date Date$
print "[" Date$ "] END COOLING"
SetCCDTemperature_Ex AcqCamNumber CameraChannel Detectortemperature  
return


/////////////////////////////////////////////////////////////////////////////////
//
// Initializing the telescope / NOT USED...
//
/////////////////////////////////////////////////////////////////////////////////
init_telescope:
print "Connecting to the telescope"
OPEN_TELESCOPE_DEVICES 0 0
print "Connected"
print "stopping the sidereal tracking..."
stoptelescope
return



/////////////////////////////////////////////////////////////////////////////////
//
// End of night, closing telescope, camera, etc...
//
/////////////////////////////////////////////////////////////////////////////////
endnight:
REM We have to see how to bring the camera back to ambient temperature before closing it.
Now Date
Datetostr Date Date$
print "[" Date$ "] Observing is finished, so closing the telescope..."



REM Closing the telescope
//CLOSE_TELESCOPE_DEVICES
close_dome
delayBlock 20000
stoptelescope
delayBlock 4000
CLOSE_TELESCOPE_DEVICES
Now Date
Datetostr Date Date$
print "[" Date$ "] Telescope tracking stopped & dome closed, equipment closed"

REM Switch OFF the power for the mount, dome & focuser
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -Mount"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -DomeTracker"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -RoboFocus"
delayBlock 3000

Now Date
Datetostr Date Date$
print "[" Date$ "] Setting main camera temperature to positive (10°C) & wait 5 minutes"
Currenttemperature=20
CameraChannel=1
SetCCDTemperature_Ex AcqCamNumber CameraChannel Currenttemperature
delayBlock 300000

Now Date
Datetostr Date Date$
print "[" Date$ "] Closing cameras connexion"
CLOSE_CCD_CAMERA_EX 1
CLOSE_CCD_CAMERA_EX 2

Now Date
Datetostr Date Date$
print "[" Date$ "] Switching OFF mount, dome, robofocus and CCD cameras"

REM Switch OFF Gembird LAN multiplug: calibration unit & Atik460 CCD camera
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Calib"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Atik460"
delayBlock 3000

Now Date
Datetostr Date Date$
print "[" Date$ "] End of night sequence done"

return


/////////////////////////////////////////////////////////////////////////////////
//
// Acquire calibration for the echelle spectrograph
//
/////////////////////////////////////////////////////////////////////////////////

AcquireCalibration:
REM Penser à enlever la sauvegarde automatique dans PRISM avant de lancer le script!

Object$="ref"

PoseThAr=60000
PoseTung=2800
PoseLEDs=2800
ON=1
OFF=0
Port1=1
Port2=2
Port3=3
Port4=4


Switchdesired=1
// Recupere l'etat des swiches d'un coup dans une table
GETSWITCH Switchdesired nbSwitches ArrayName ArrayState

sOutput$="Dir: "+sDirSave$
Now Date
Datetostr Date Date$
print "[" Date$ "]" sOutput$
sOutput$="Object: "+Object$
print "[" Date$ "]" sOutput$


REM =================
REM Miroir + Tungsten
REM =================
SETSWITCH Port1 ON
DelayBlock 1000
SETSWITCH Port4 ON
DelayBlock 1000

For i=1 33
  STR i i$
  StartExposure_EX AcqCamNumber PoseTung
  sFullPath$=sDirSave$+Object$+"_tung-"+i$+".fits"
  sOutput$="Tungsten: "+Object$+"_tung-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  GetLastImageExposure_EX AcqCamNumber img
  SAVEFIT img sFullPath$
  Close img
Next i


REM =================
REM LEDs + Tungsten
REM =================
SETSWITCH Port2 ON
DelayBlock 1000

For i=1 3
  STR i i$
  StartExposure_EX AcqCamNumber PoseLEDs
  sFullPath$=sDirSave$+Object$+"_led-"+i$+".fits"
  sOutput$="Flat: "+Object$+"_led-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  GetLastImageExposure_EX AcqCamNumber img
  SAVEFIT img sFullPath$
  Close img
Next i

DelayBlock 2000

SETSWITCH Port2 OFF
DelayBlock 2000

SETSWITCH Port4 OFF
DelayBlock 2000


REM =================
REM ThAr
REM =================
SETSWITCH Port3 ON
DelayBlock 3000

For i=1 3
  STR i i$
  StartExposure_EX AcqCamNumber PoseThAr
  sFullPath$=sDirSave$+Object$+"_thor-"+i$+".fits"
  sOutput$="ThAr: "+Object$+"_thor-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  DelayBlock 1000
  GetLastImageExposure_EX AcqCamNumber img
  DelayBlock 1000
  SAVEFIT img sFullPath$
  Close img
  DelayBlock 1000
Next i

DelayBlock 3000

SETSWITCH Port3 OFF
DelayBlock 1000

SETSWITCH Port1 OFF
DelayBlock 1000

REM sOutput$="That's all folks"
REM Print sOutput$

return


/////////////////////////////////////////////////////////////////////////////////
//
// Star Hopping: Goto a target, center object, resynch telescope
//
/////////////////////////////////////////////////////////////////////////////////
StarHopping:

REM Coordonnées équatoriales de l'objet en radians
GETOBJECTCOORD objet$ alpha delta

if alpha=-100
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] L'étoile " objet$ " n'est pas reconnu par PRISM !"
  return
endif

str alpha alphaRad$
str delta deltaRad$
RAD_TO_RA  alpha alpha$
RAD_TO_DEC delta delta$

Now Date
Datetostr Date Date$
PRINT "[" Date$ "] Utilisation de l'étoile " objet$ " pour du 'star hopping'"
PRINT "[" Date$ "] RA  : " alpha$ " (" alphaRad$ " radians)"
PRINT "[" Date$ "] DEC : " delta$ " (" deltaRad$ " radians)"

//Longitude du lieu = celle du site par défaut
GETSTDRLONGITUDE Longitude
// Latitude du lieu
GETSTDRLATITUDE Latitude
// Loop to wait for the target to reach proper altitude in the sky
LoopWaitHauteur:
// Date du moment :
NOW Date
// Hauteur de l'objet en radian :
GETHEIGHT alpha delta Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   stoptelescope
   DelayBlock 60000
   Goto LoopWaitHauteur:
endif

// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL alpha AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI

// Pointage ou non ?
If AngleHor<AngleHorMin then
    If Hauteur>HauteurMin then
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Ca pointe !"
        MoveTelescope alpha delta
        str Hauteur Hauteur$
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Hauteur cible : " Hauteur$ "°"
        WaitForEndMoveTelescope
        Delay 10000
        WaitForEndDelay
        deltaplus=delta+0.003
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        Delay 5000
        WaitForEndDelay
        // Je pointe un peu en dessous de la fibre pour toujours arriver par ce côté pour le centrage/guidage
        deltaplus=delta+0.00015
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
    Else
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Hauteur cible trop basse"
        return
    EndIf
Else
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Angle Horaire cible trop proche du méridien"
    return
EndIf

Now Date
Datetostr Date Date$
print "[" Date$ "] Pointage fini"


// Wait for the dome
Now Date
Datetostr Date Date$
print "[" Date$ "] Waiting for the dome"
Delay 60000
WaitForEndDelay
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome should be at telescope position now"


// Centrage étoile la plus brillante sur la consigne
//OPEN ImgChamp "C:\Users\ObsBE\Documents\Acquisitions\20180719_eShel101_Atik460-1x1_38420_Revel\ATIK HS V442 And.fits"
GExpTimeMilSec=GExpTime*1000
GExpTimeChamp=GExpTimeMilSec*1
StartExposure_EX 1 GExpTimeMilSec
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChamp
MinDynamiqueAutoguidage=500
MaxDynamique=55000
MaxOmC=900
PSFMin=3
DemLargFenCentro=32
ZoneRecherche=26
BRIGHTEST_STAR ImgChamp MinDynamiqueAutoguidage MaxDynamique MaxOmC PSFMin DemLargFenCentro ZoneRecherche XGuideCentro YGuideCentro
if XGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
if YGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
str XGuideCentro XStar$
str YGuideCentro YStar$
Now Date
Datetostr Date Date$
print "[" Date$ "] Star found at position " XStar$ ", " YStar$
// Je centre un peu en dessous de la fente pour que l'autoguidage fonctionne toujours dans ce sens (tube à l'Ouest)
GuidePosYDecale=GuidePosY-5
str GuidePosX GuidePosX$
str GuidePosY GuidePosY$
str GuidePosYDecale GuidePosYDecale$
Now Date
Datetostr Date Date$
print "[" Date$ "] Centering at position " GuidePosX$ ", " GuidePosYDecale$ "; Fiber at " GuidePosX$ ", " GuidePosY$
OFFSET_TELESCOPE ImgChamp XGuideCentro YGuideCentro GuidePosX GuidePosYDecale
WAITFORENDMOVETELESCOPE
Delay 2000
WaitForEndDelay
CLOSE ImgChamp

Now Date
Datetostr Date Date$
print "[" Date$ "] Resynch telescope on position"
CALIBRATE_TELESCOPE alpha delta

return


/////////////////////////////////////////////////////////////////////////////////
//
// Check if I can continue to observe another 20min based on Sun position & telescope Vs meridian
//
/////////////////////////////////////////////////////////////////////////////////
CanIContontinueToObserve:
NOW Date
GET_TELESCOPE_POSITION RA2000 DEC2000 Haut Azi AHor
GETSTDRLONGITUDE Longitude
GETSTDRLATITUDE Latitude
GETHEIGHT RA2000 DEC2000 Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target too low"
   ContinueObservations=0
   return
endif

// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL RA2000 AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI

AngleHorLimit=0.0
// si DEC<45°: 10min supplémentaires
if DEC2000<0.75 then
    AngleHorLimit=0.2
endif
// si DEC<30°: 20min supplémentaires
if DEC2000<0.5 then
    AngleHorLimit=0.4
endif
// si DEC<25°: 1h10 supplémentaires
if DEC2000<0.44 then
    AngleHorLimit=1.2
endif
// si DEC<6°: 1h45 supplémentaires
if DEC2000>0.1 then
    AngleHorLimit=1.75
endif

if AngleHor>AngleHorLimit
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target too close to meridian (telescope too close to pier)"
   ContinueObservations=0
   return
endif

// Check Sun elevation
GetStdrLongitude Longitude
GetStdrLatitude Latitude

elevsunstopobservations=elevsunstopobservations_Deg/TODEG

Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>elevsunstopobservations
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Sun too high to continue observing"
   ContinueObservations=0
   return
endif

ContinueObservations=1

return


/////////////////////////////////////////////////////////////////////////////////
//
// Check if Sun is still below horizon limit, check if observations can continu...
//
/////////////////////////////////////////////////////////////////////////////////
IsSunStillBelow:

// Check Sun elevation
GetStdrLongitude Longitude
GetStdrLatitude Latitude

elevsunstopobservations=elevsunstopobservations_Deg/TODEG

Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>elevsunstopobservations
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Sun too high to continue observing"
   SunStillBelow=1
   ContinueObservations=0
   return
endif

SunStillBelow=1
ContinueObservations=1

return



/////////////////////////////////////////////////////////////////////////////////
//
// Wait several minutes (for long waiting time)...
//
/////////////////////////////////////////////////////////////////////////////////
WaitForMinutes:
//MinutesToWait=5

str MinutesToWait MinutesToWait$

Now Date
Datetostr Date Date$
print "[" Date$ "] Start waiting for " MinutesToWait$ " minutes"

Now DateBegin

WaitForMinutesLoop:
Now Date
Ecart=(Date-DateBegin)*24.0*60.0
if Ecart<MinutesToWait then
goto WaitForMinutesLoop:
endif

Now Date
Datetostr Date Date$

print "[" Date$ "] Fin (MinutesToWait=" MinutesToWait ")"

return

/////////////////////////////////////////////////////////////////////////////////
//
// Look up for Object$ parameters in terms of single exposure time, Nb of exposures...
//
/////////////////////////////////////////////////////////////////////////////////
LookUpObject:

if Object$="64Ser" then
    objet$="hd175869"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="QTSer" then
    objet$="hd170783"
    GExpTime=0.4
    ExpSec=1200
    NbExposure=3
endif

//iot Lyr / hd178475 / Mag 5.1
if Object$="iotLyr" then
    objet$="hd178475"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

//V558 Lyr / hd183362 / Mag 6.4
if Object$="V558Lyr" then
    objet$="hd183362"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=4
endif

//11 Cyg / hd185037 / Mag 5.9
if Object$="11Cyg" then
    objet$="hd185037"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=3
endif

if Object$="12Vul" then
    objet$="hd187811"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=3
endif

//25 Cyg / hd189687 / Mag 5.2
if Object$="25Cyg" then
    objet$="hd189687"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="28Cyg" then
    objet$="hd191610"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="QRVul" then
    objet$="hd192685"
    GExpTime=0.5
    ExpSec=1200
    NbExposure=3
endif

if Object$="lamCyg" then
    objet$="hd198183"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//ups Cyg / hd202904 / Mag 4.4
if Object$="upsCyg" then
    objet$="hd202904"
    GExpTime=0.1
    ExpSec=600
    NbExposure=3
endif

if Object$="16Peg" then
    objet$="hd208057"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

//31Peg / hd212076 / Mag4.9
if Object$="31Peg" then
    objet$="hd212076"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//14 Lac / hd216200 / Mag 5.8
if Object$="14Lac" then
    objet$="hd216200"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//18 And / hd222304 / Mag 5.3
if Object$="18And" then
    objet$="hd222304"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="omiAnd" then
    objet$="hd217675"
    GExpTime=0.1
    ExpSec=900
    NbExposure=3
endif

//omi Cas / hd4180 / mag 4.5
if Object$="omiCas" then
    objet$="hd4180"
    GExpTime=0.1
    ExpSec=600
    NbExposure=5
endif

if Object$="V442And" then
    objet$="hd6226"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=4
endif

//phi And / hd6811 / mag 4.3
if Object$="phiAnd" then
    objet$="hd6811"
    GExpTime=0.1
    ExpSec=600
    NbExposure=3
endif

if Object$="V764Cas" then
    objet$="hd7636"
    GExpTime=0.3
    ExpSec=1200
    NbExposure=4
endif
//hd9709 / mag 7.4
if Object$="hd9709" then
    objet$="hd9709"
    GExpTime=0.4
    ExpSec=1200
    NbExposure=4
endif

if Object$="phiPer" then
    objet$="hd10516"
    GExpTime=0.1
    ExpSec=900
    NbExposure=3
endif

if Object$="V549Per" then
    objet$="hd3661"
    GExpTime=1.0
    ExpSec=1200
    NbExposure=6
endif

if Object$="hd13867" then
    objet$="hd13867"
    GExpTime=0.3
    ExpSec=1200
    NbExposure=4
endif

return

/////////////////////////////////////////////////////////////////////////////////
//
// TakeObject: acquire spectra of Object$
//
/////////////////////////////////////////////////////////////////////////////////
TakeObject:

GoSub LookUpObject:

GoSub GoToTargetAndAcquisition:
GoSub IsSunStillBelow:
if SunStillBelow=0 then
    if StarToSynchForObject$="" then
        //objet$="hd886"
        //GExpTime=0.1
        //GoSub StarHopping:
    endif
    GoTo EndOfSession:
endif


return


/////////////////////////////////////////////////////////////////////////////////
//
// Meteo.pgm: gestion station Sentinel (T.Lemoult)
//
/////////////////////////////////////////////////////////////////////////////////
// lecture des parametres de la station meteo Sentinel
ReadMeteo:

//Print "Donnees de la station meteo Sentinel:"
pathSentinel$="C:\Users\ObsBE\Documents\Sentinel\Datas\infodata.txt"
Open_FileTxt_For_Read fichier pathSentinel$

for i=1 7
    ReadFileTXT fichier ligneDummy$
next i

ReadFileTXT fichier ligneTempExt$
CUTSTR ligneTempExt$ "=" 2 out$
val out$ TempExt

ReadFileTXT fichier ligneHumidity$
CUTSTR ligneHumidity$ "=" 2 out$
val out$ Humidity
//print "Humidity=" out$

ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$

ReadFileTXT fichier ligneTempSkyIR$
CUTSTR  ligneTempSkyIR$  "="  2  out$
val out$ TempskyIR
//print "TempskyIR=" out$

ReadFileTXT fichier ligneTempDetectorIR$
CUTSTR ligneTempDetectorIR$ "=" 2 out$
val out$ TempDetectorIR
//print "TempDetectorIR=" out$

ReadFileTXT fichier ligneRainFall$
CUTSTR ligneRainFall$ "=" 2 out$
if Out$="No" then
        RainFall=0
        RainFall$="N"
ELSE
        RainFall=1
        RainFall$="Y"
ENDIF
//print "RainFall=" out$

ReadFileTXT fichier ligneWindSpeedGust$
CUTSTR ligneWindSpeedGust$ "=" 2 out$
val out$ WindSpeedGust
//print "WindSpeedGust=" out$

ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$

ReadFileTXT fichier ligneLightLevel$
CUTSTR ligneLightLevel$ "=" 2 out$
val out$ LightLevel
//print "LightLevel=" out$

tempCiel=TempSkyIR-TempExt
STR tempCiel tempCiel$
//print "calcul temperature ciel =" tempCiel$

////////////////////////
if (tempCiel<LimitTempCiel) then
    if RainFall=0 then
        if LightLevel>LimitMagnitudeCiel
            BeauTemp=1
        ELSE
            BeauTemp=0
        ENDIF
    ELSE
        BeauTemp=0
    ENDIF
ELSE
    BeauTemp=0
ENDIF   

// Beautemp est obtenus en regardant que la derniere valeur du  Sentinel.
if BeauTemp=1 then
    CompteurBeauTemp=CompteurBeauTemp+1
ELSE
    CompteurBeauTemp=0
ENDIF

// MeteoOK donne un résultat filtree..
if CompteurBeauTemp>ValMinBelleMeteo then
//    Print "Il fait beau depuis un moment.. On va pouvoir observer"
    MeteoOK=1
else
    MeteoOK=0
    IF (BeauTemp=1) then
//        Print "Si le beau temps se maintien, on pourra observer"
    ELSE
//        Print "Il ne fait pas assez beau pour observer"
    ENDIF
ENDIF

CLOSEFILETXT  fichier
return

BoucleAttendBeauTemp:
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Waiting for good weather. Sky temp=" tempCiel$ " (" LimitTempCiel "), Rain=" RainFall$

    GOSUB ReadMeteo:
    DELAYBLOCK 60000
    if MeteoOK=0 THEN
        GOTO BoucleAttendBeauTemp:
    ENDIF

return


/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//                                                                             END OF SCRIPT                                                                     //
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////



1 commentaire:

  1. Hi Olivier,

    Very interested in your efforts to automate your observatory for spectral recording, as it has motivated me to again try to do the same (first tried 10 years ago with limited success). I am starting afresh with a new mount (EQ8) and Prism Pro and like you I will probably only use my eShel, not the Lhires III. I have a lot of learning and testing to do so do not be surprised if I ask for your help and advice.


    Cheers, Bernard

    RépondreSupprimer