Changeset 504 for BAORadio


Ignore:
Timestamp:
Jun 28, 2011, 12:31:47 PM (13 years ago)
Author:
frichard
Message:

-Version 0.8 de libini
-Formule de Marc
-Nouvelles fonctionnalités (goto nom-de l'objet etc...)

Location:
BAORadio/libindi/libindi
Files:
30 added
3 deleted
43 edited
1 moved

Legend:

Unmodified
Added
Removed
  • BAORadio/libindi/libindi/BAOControl/.directory

    r502 r504  
    11[Dolphin]
    2 Timestamp=2010,11,5,22,3,10
     2Timestamp=2010,11,8,3,1,35
     3
     4[Settings]
     5ShowDotFiles=false
  • BAORadio/libindi/libindi/BAOControl/Makefile

    r502 r504  
    22#
    33
    4 CC=g++
     4CC = g++
     5#CFLAGS = -g
     6#CXXFLAGS = -g
    57
    6 BAOControl_objects =  baocontrol.o ClientSocket.o Socket.o filetools.o exception.o astro.o
     8BAOcontrol_objects =  main.o baocontrol.o ClientSocket.o Socket.o filetools.o exception.o ../drivers/telescope/astro.o
    79
    810
    9 all : BAOControl
     11all : BAOcontrol
    1012
    1113
    12 BAOControl: $(BAOControl_objects)
    13         g++ -o BAOControl $(BAOControl_objects) -lpthread -lX11
     14BAOcontrol: $(BAOcontrol_objects)
     15        g++  -o BAOcontrol $(BAOcontrol_objects) -lpthread -lX11
    1416
    15 Socket: Socket.cpp
     17Socket:  Socket.cpp
    1618ClientSocket: ClientSocket.cpp
    17 Astro: astro.cpp
     19Astro: ../drivers/telescope/astro.cpp
    1820baocontrol: baocontrol.cpp
     21main: main.cpp
    1922
    2023clean:
    21         rm -f *.o *.cpp~ *.c~ *.h~ BAOControl
     24        rm -f *.o *.cpp~ *.c~ *.h~ BAOcontrol
     25
     26install:
     27        cp BAOcontrol /usr/bin
  • BAORadio/libindi/libindi/BAOControl/Socket.cpp

    r502 r504  
    4242   //  TIME_WAIT - argh
    4343    int on = 1;
    44 
    45     if ( setsockopt ( m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 ) return false;
    46 
    47     if (setsockopt(m_sock, SOL_TCP, TCP_NODELAY, (const char*) &on, sizeof(on)) <0) return false;
    48 
     44 
     45    if ( setsockopt( m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 ) return false;
     46 
     47    if ( setsockopt(m_sock, SOL_TCP, TCP_NODELAY, (const char*) &on, sizeof(on)) <0) return false;
     48   
     49   
    4950    return true;
    5051}
     
    8081
    8182    if ( bind_return == -1 ) return false;
    82    
     83 
    8384    return true;
    8485}
  • BAORadio/libindi/libindi/BAOControl/Socket.h

    r502 r504  
    1313#include <arpa/inet.h>
    1414#include <iostream>
     15#include "stdio.h"
    1516
    1617
    17 const int MAXHOSTNAME = 200;
     18const int MAXHOSTNAME = 1000;
    1819const int MAXCONNECTIONS = 5;
    1920const int MAXRECV = 5000;
  • BAORadio/libindi/libindi/BAOControl/baocontrol.cpp

    r502 r504  
    1 /********************/
    2 /* BAOCONTROL       */
    3 /*                  */
    4 /********************/
     1/******************************/
     2/* BAOCONTROL                 */
     3/*                            */
     4/* Franck RICHARD             */
     5/* franckrichard033@gmail.com */
     6/* Juin 2011                  */
     7/******************************/
    58
    69
     
    811
    912
    10 /* Affiche à l'écran (si AfficheEcran==true) et sauvegarde dans le fichier
    11    BAOControl.log le message contenu dans la variable chaine */
    12 void Affiche(std::string chaine, bool AfficheEcran)
     13
     14/**************************************************************************************
     15**Constructeur
     16***************************************************************************************/
     17
     18BAOcontrol::BAOcontrol()
     19{
     20    float a1, a2, a3;
     21
     22    // Le choix de la couleur des caractÚres est adapté pour une fenêtre de terminal
     23    // ayant un fond blanc. pour un fond noir, mettre couleurs=2 dans le fichier params
     24
     25    ChoixCouleurs=1;
     26
     27
     28    Affiche("\n\n\n\n\n \
     29 ******************************************\n \
     30 *             BAORadio Control           *\n \
     31 * Laboratoire de l'Accélérateur Linéaire *\n \
     32 *                                        *\n \
     33 *             v0.2  20/06/2011           *\n \
     34 *        franckrichard033@gmail.com      *\n \
     35 ******************************************\n\n\n", true);
     36
     37    //Initialisation des variables globales et des pointeurs
     38
     39
     40    delaitransit  = 0;
     41    delaitracking = 0;
     42    lognum        = 0;
     43    numAntenne    = 0;
     44    numobjets     = 0;
     45    runnum        = 1;
     46
     47    Pression      = 1013.0;
     48    Temperature   = 10.0;
     49
     50    NoExit        = true;
     51    Transit       = false;
     52    run           = false;
     53    exitrun       = false;
     54
     55    fd            = NULL;
     56    client_socket = NULL;
     57
     58    // chaines de caractÚres et tableaux
     59
     60    LatitudeChar  = "";
     61    LongitudeChar = "";
     62    Serveur       = "";
     63    Port          = "";
     64
     65    Antennes      = new DefAntenne[MAXANTENNES];
     66    objets        = new DefObjets[MAXOBJETS];
     67
     68    //on initalise aussi les tableaux
     69
     70    for (int i=0; i<MAXANTENNES; i++)
     71    {
     72        Antennes[i].ok=0;
     73        Antennes[i].ip=0;
     74    }
     75
     76    for (int i=0; i<MAXOBJETS; i++)
     77    {
     78        objets[i].JJ=0;
     79        objets[i].exec=false;
     80    }
     81
     82    // Chargement du fichier contenant les paramÚtres
     83
     84    if (!ChargementParametres("params"))
     85    {
     86        Erreur("Le fichier de configuration 'params' contient des erreurs ou n'existe pas.\n \
     87        Merci de vérifier.\n\n");
     88        exit(1);
     89    }
     90
     91    // Conversion de la latitude et de la longitude en radians
     92
     93    Decomposition(LatitudeChar, 0, &a1, &a2, &a3);
     94
     95    double Latitude = (a1 + a2 / 60.0 + a3 / 3600.0) * Pidiv180;
     96
     97    Decomposition(LongitudeChar, 1, &a1, &a2, &a3);
     98
     99    double Longitude = Pi2 - ( a1 + a2 / 60.0 + a3 / 3600.0 ) * Pidiv180;
     100
     101    // Transfert de la latitude, longitude, pression, température à la classe Astro
     102
     103    DefinirLongitudeLatitude(Longitude, Latitude);
     104
     105    DefinirPressionTemp(Pression, Temperature);
     106
     107    // Ouverture du socket avec indi_BAO
     108
     109    client_socket = new ClientSocket("localhost", atoi(Port.c_str()) );
     110
     111    // On se connecte au pilote indi_BAO
     112
     113    Connect(true);
     114}
     115
     116
     117
     118/**************************************************************************************
     119** Destructeur
     120***************************************************************************************/
     121
     122BAOcontrol::~BAOcontrol()
     123{
     124    // destruction des tableaux
     125
     126    delete [] Antennes;
     127    delete [] objets;
     128
     129    // destruction de la fenêtre graphique, des caractÚres
     130
     131    if (d!=NULL)
     132    {
     133        XFreeGC(d, noir);
     134        XFreeGC(d, vert);
     135        XFreeGC(d, rouge);
     136        XFreeGC(d, gris);
     137        XFreeFont(d, fd);
     138        XDestroyWindow(d, w);
     139        XCloseDisplay(d);
     140    }
     141
     142    // destruction du socket
     143
     144    delete client_socket;
     145}
     146
     147
     148/**************************************************************************************
     149** Affiche le message à l'écran (si AfficheEcran==true) et le sauvegarde dans le fichier
     150** BAOControl.log
     151***************************************************************************************/
     152
     153void BAOcontrol::Affiche(string Message, bool AfficheEcran)
    13154{
    14155    FILE *pFile = NULL;
    15156
    16     pFile = fopen ("BAOControl.log", "a");
    17 
    18     if (AfficheEcran) std::cout << chaine;
    19    
    20     fprintf (pFile, chaine.c_str());
    21 
    22     os.str("");
    23 
    24     fclose (pFile);
    25 }
    26 
    27 
    28 /*Affiche les messages d'erreur en rouge */
    29 void Erreur(std::string chaine)
    30 {
    31     std::cout << red;
     157    if ( (pFile = fopen ("BAOcontrol.log", "a")) != NULL)
     158    {
     159        if (AfficheEcran) cout << Message;
     160
     161        fprintf (pFile, Message.c_str());
     162
     163        fclose (pFile);
     164    }
     165}
     166
     167void BAOcontrol::Affiche(stringstream *Message, bool AfficheEcran)
     168{
     169    Affiche(Message->str(), AfficheEcran);
     170
     171    // on efface le buffer
     172
     173    Message->str("");
     174}
     175
     176
     177/**************************************************************************************
     178** Affiche les messages d'erreur en rouge
     179***************************************************************************************/
     180
     181void BAOcontrol::Erreur(string chaine)
     182{
     183    ChoixCouleurs==1 ? cout << red1  : cout << red2;
    32184    Affiche(chaine, true);
    33     std::cout << black;
    34 }
    35 
    36 
    37 /*initialise une fenêtre graphique */
    38 void initialiserFenetre()
     185    ChoixCouleurs==1 ? cout << grey1 : cout << grey2;
     186}
     187
     188void BAOcontrol::Erreur(stringstream *Message)
     189{
     190    Erreur(Message->str());
     191
     192    // on efface le buffer
     193
     194    Message->str("");
     195}
     196
     197
     198/**************************************************************************************
     199** Initialise la fenêtre graphique
     200***************************************************************************************/
     201
     202void BAOcontrol::initialiserFenetre()
    39203{
    40204    XGCValues gcv;
    41     XFontStruct * fd;
    42    
    43     /*contacte le serveur*/
     205
     206    // contacte le serveur graphique
     207
    44208    if ((d = XOpenDisplay(getenv("DISPLAY"))) == NULL)
    45209    {
     
    48212    }
    49213
    50     /*crée une fenêtre*/
     214    // crée une fenêtre
     215
    51216    w = XCreateSimpleWindow(d, RootWindow(d, DefaultScreen(d)),
    52                             0, 0, larg, haut,
     217                            0, 0, larg_fenetre, haut_fenetre,
    53218                            2, BlackPixel(d, DefaultScreen(d)),
    54219                            WhitePixel(d, DefaultScreen(d)));
    55        
    56     /* Creation du double buffer */
    57     db = XCreatePixmap(d, w, larg, haut, DefaultDepth(d, DefaultScreen(d)));
    58 
    59     /*chargement d'une police de caractÚres*/
    60     if ((fd=XLoadQueryFont(d, "fixed")) == NULL)
     220
     221    // Création du double buffer
     222
     223    db = XCreatePixmap(d, w, larg_fenetre, haut_fenetre, DefaultDepth(d, DefaultScreen(d)));
     224
     225    // Chargement de la police de caractÚres
     226
     227    if ((fd = XLoadQueryFont(d, "fixed")) == NULL)
    61228    {
    62229        Erreur("Impossible de charger la police fixed\n\n");
     
    64231    }
    65232
    66     /*création d'un contexte graphique*/
     233    // Création des couleurs
     234
    67235    gcv.font = fd->fid;
    68236    gcv.foreground = BlackPixel(d, DefaultScreen(d));
     
    78246    gris = XCreateGC(d, w, GCFont | GCForeground, &gcv);
    79247
    80     /*affiche la fenêtre */
     248    // Affichage de fenêtre
     249
    81250    XMapWindow(d, w);
    82251}
    83252
    84253
    85 /* Dessine les éléments de la fenêtre graphique */
    86 void Dessiner()
    87 {
    88     char chaine[100];
     254/**************************************************************************************
     255** Dessine les éléments dans la fenêtre graphique
     256***************************************************************************************/
     257
     258void BAOcontrol::Dessiner()
     259{
     260    char *chaine;
    89261    GC color;
    90262
    91     /* On efface la fenêtre */
     263    chaine = new char [100];
     264
     265    // On efface la fenêtre
     266
    92267    XSetForeground(d, noir, WhitePixel(d, DefaultScreen(d)));
    93     XFillRectangle(d, db, noir, 0, 0, larg, haut);
     268    XFillRectangle(d, db, noir, 0, 0, larg_fenetre, haut_fenetre);
    94269    XSetForeground(d, noir, BlackPixel(d, DefaultScreen(d)));
    95270
    96     /* Affichage de la date et de l'heure */
    97     int h=astro->Heu;
    98     int m=astro->Min;
    99     int s=astro->Sec;
    100     int j=astro->Jour;
    101    
     271    // On récupÚre la date et l'heure contenue dans la classe astro (et le jour julien)
     272
     273    double h  = GetHeure();
     274    double mi = GetMin();
     275    double s  = GetSec();
     276    double a  = GetAnnee();
     277    double m  = GetMois();
     278    double j  = GetJour();
     279    double JJ = GetJJ();
     280
     281    // on évite les affichages de l'heure du genre 12:56:60 ou 24:00:00
     282
    102283    if (s==60) {
    103         s=0;
    104         m++;
    105         if (m==60) {
    106             m=0;
     284        s = 0;
     285        mi++;
     286        if (mi == 60) {
     287            mi = 0;
    107288            h++;
    108             if (h==24) {
    109                 h=0;
     289            if (h == 24) {
     290                h = 0;
    110291                j++;
    111292            }
    112293        }
    113     }   
    114    
    115     sprintf(chaine, "%02i:%02i:%02i TU    %02i/%02.0f/%04.0f    JJ=%10.5f",
    116             h, m, s, j, astro->Mois, astro->Annee, astro->JJ);
     294    }
     295
     296    //affichage de la date et de l'heure
     297
     298    sprintf(chaine, "%02.0f:%02.0f:%02.1f TU    %02.0f/%02.0f/%04.0f    JJ=%10.5f",
     299            h, mi, s, j, m, a, JJ);
    117300
    118301    XDrawString(d, db, noir, 10, 10, chaine, strlen(chaine));
    119302
     303    //En cas d'exécution d'un fichier de mouvements, on affiche la prochaine étape
     304
    120305    if (run)
    121306    {
    122         sprintf(chaine, "Prochaine etape dans %4.1fs", (objets[runnum].JJ-astro->JJ)*3600.0*24.0);
    123 
    124         if ((objets[runnum].JJ-astro->JJ)*3600.0*24.0 >= 0.0) XDrawString(d, db, noir, 350, 10, chaine, strlen(chaine));
    125     }
    126 
    127     /*affichage des cercles d'état*/
     307        sprintf(chaine, "Prochaine etape dans %4.1fs", (objets[runnum].JJ - JJ) * 3600.0 * 24.0);
     308
     309        if ((objets[runnum].JJ - JJ) * 3600.0 * 24.0 >= 0.0)
     310            XDrawString(d, db, noir, 350, 10, chaine, strlen(chaine));
     311    }
     312
     313    // affichage des cercles d'état
     314    // vert = l'antenne fonctionne
     315    // rouge = problÚme détecté sur l'antenne
     316    // gris = antenne non connectée
     317
    128318    for (int i=0; i <20; i++)
    129319    {
    130         for (int j=0; j<5; j++)
    131         {
    132             switch(Antennes[20*j+i].ok)
    133             {
    134               case 1 : color=vert; break;
    135               case 2 : color=rouge; break;
    136               default: color=gris; break;
    137             }
     320        for (int j=0; j<2; j++)
     321        {
     322            switch (Antennes[20*j+i].ok)
     323            {
     324            case 1 :
     325                color=vert;
     326                break;
     327            case 2 :
     328                color=rouge;
     329                break;
     330            default:
     331                color=gris;
     332                break;
     333            }
     334
    138335            XFillArc(d, db ,color, 10+i*30, 20+j*30, 15, 15, 0, 360*64);
    139             XDrawArc(d, db ,noir, 10+i*30, 20+j*30, 15, 15, 0, 360*64);
    140         }
    141     }
    142 
    143 
    144     /*Affichage des messages d'erreur*/
    145     if (lognum>15)
    146     {
    147         for (int i=lognum-1; i>lognum-16; i--)
     336            XDrawArc(d, db ,noir,  10+i*30, 20+j*30, 15, 15, 0, 360*64);
     337        }
     338    }
     339
     340
     341    // Affichage des messages d'indi_BAO
     342    // gÚre aussi le défilement
     343
     344    if (lognum>10)
     345    {
     346        for (int i=lognum-1; i>lognum-11; i--)
    148347        {
    149348            if ((logs[i].find("Err")!=string::npos)
    150349                    || (logs[i].find("ALERTE")!=string::npos)) color=rouge;
    151350            else color=vert;
    152             XDrawString(d, db, color, 10, 15*12+(i-lognum+15)*12, logs[i].c_str(), strlen(logs[i].c_str()));
     351            XDrawString(d, db, color, 10, 9*12+(i-lognum+10)*12, logs[i].c_str(), strlen(logs[i].c_str()));
    153352        }
    154353    }
     
    160359                    || (logs[i].find("ALERTE")!=string::npos)) color=rouge;
    161360            else color=vert;
    162             XDrawString(d, db, color, 10, 15*12+i*12, logs[i].c_str(), strlen(logs[i].c_str()));
    163         }
    164     }
    165    
    166     XCopyArea(d, db, w, noir, 0, 0, larg, haut, 0, 0);
    167          
    168     /* on force le rafraichissement de l'écran */
     361            XDrawString(d, db, color, 10, 9*12+i*12, logs[i].c_str(), strlen(logs[i].c_str()));
     362        }
     363    }
     364
     365    // On affiche la copie de l'écran une fois que tout est dessiné
     366    // on évite ainsi les scientillements de la fenêtre
     367
     368    XCopyArea(d, db, w, noir, 0, 0, larg_fenetre, haut_fenetre, 0, 0);
     369
     370    // On force le rafraichissement de l'écran
     371
    169372    XFlush(d);
    170 }
    171 
    172 
    173 /* Gestion des messages concernant la fenêtre graphique */
    174 void rouler(char* reponse)
     373
     374    delete [] chaine;
     375}
     376
     377
     378/**************************************************************************************
     379** Gestion des événements affectant la fenêtre graphique
     380***************************************************************************************/
     381
     382void BAOcontrol::rouler()
    175383{
    176384    XEvent e;
     
    181389        {
    182390        default:
    183             //std::cout << "J'ai reçu un évÚnement " <<  e.type << std::endl
     391            //cout << "J'ai reçu un événement " <<  e.type << endl
    184392            break;
    185393        case Expose :
     
    191399
    192400
    193 /* RécupÚre les messages envoyés par indi_BAO */
    194 void LireReponse()
    195 {
    196     std::string reponse, decomp;
    197     std::stringstream os;
     401/**************************************************************************************
     402** RécupÚre les messages envoyés par indi_BAO
     403***************************************************************************************/
     404
     405void BAOcontrol::LireReponse()
     406{
     407    string reponse, memreponse, decomp;
    198408    bool test=false;
    199409
    200410    *client_socket >> reponse;
    201 
    202     if (reponse.find("message")!=string::npos)
    203     {
    204         /* on ne garde que la partie intéressante */
    205         reponse=reponse.substr(reponse.find("message")+9);
    206 
    207         reponse=reponse.substr(0, reponse.find("\""));
    208 
    209         /*récupÚre l'adresse ip de l'antenne */
    210         if (reponse.find(". (Antennes connectees")!=string::npos)
    211         {
    212             decomp=reponse.substr(0, reponse.find(". (Antennes connectees"));
    213             decomp=decomp.substr(decomp.rfind(".")+1);
    214 
    215             /*si cette antenne est déjà connectée, on change son état */
    216             for (int i=0; i<numAntenne; i++)
     411   
     412   // printf("%s\n", reponse.c_str());
     413
     414    do
     415    {
     416        if (reponse.find("message")!=string::npos)
     417        {
     418            // On ne garde que la partie intéressante
     419            // La partie suivant "message="...
     420            reponse = reponse.substr(reponse.find("message") + 9);
     421
     422            memreponse = reponse;
     423
     424            // ...jusqu'au "
     425            reponse=reponse.substr(0, reponse.find("\""));
     426
     427            // On récupÚre l'adresse ip de l'antenne qui nous parle
     428            // et on met à jour le tabmeau des états des antennes
     429
     430            if (reponse.find(". (Antennes connectees")!=string::npos)
    217431            {
    218                 if (atoi(decomp.c_str()) == Antennes[i].ip)
     432                decomp=reponse.substr(0, reponse.find(". (Antennes connectees"));
     433                decomp=decomp.substr(decomp.rfind(".")+1);
     434
     435                // si cette antenne est déjà connectée, on change son état
     436
     437                for (int i=0; i<numAntenne; i++)
    219438                {
    220                     Antennes[i].ok=1;
    221                     test=true;
    222                     break;
     439                    if (atoi(decomp.c_str()) == Antennes[i].ip)
     440                    {
     441                        Antennes[i].ok=1;
     442                        test=true;
     443                        break;
     444                    }
     445                }
     446
     447                // ou si c'est une nouvelle antenne, on l'ajoute au tableau
     448
     449                if (!test)
     450                {
     451                    Antennes[numAntenne].ip = atoi(decomp.c_str());
     452                    Antennes[numAntenne++].ok = 1;
    223453                }
    224454            }
    225455
    226             /*ou on ajoute son état */
    227             if (!test)
     456            // erreur sur une antenne -> on change son état dans la fenêtre
     457
     458            if  ((reponse.find("ALERTE antenne ")!=string::npos) ||
     459                    (reponse.find("Erreur sur l antenne ")!=string::npos))
    228460            {
    229                 Antennes[numAntenne].ip=atoi(decomp.c_str());
    230                 Antennes[numAntenne].ok=1;
    231                 numAntenne++;
    232             }
    233         }
    234 
    235         /*erreur sur une antenne -> on change son état dans la fenêtre */
    236         if  ((reponse.find("ALERTE antenne ")!=string::npos) || (reponse.find("Erreur sur l antenne ")!=string::npos))
    237         {
    238             decomp=reponse.substr(0, reponse.find(" :"));
    239             decomp=decomp.substr(decomp.rfind(".")+1);
    240 
    241             for (int i=0; i<numAntenne; i++)
    242             {
    243                 if (atoi(decomp.c_str()) == Antennes[i].ip)
     461                decomp = reponse.substr(0, reponse.find(" :"));
     462                decomp = decomp.substr(decomp.rfind(".") + 1);
     463
     464                for (int i=0; i<numAntenne; i++)
    244465                {
    245                     Antennes[i].ok=2;
     466                    if (atoi(decomp.c_str()) == Antennes[i].ip)
     467                    {
     468                        Antennes[i].ok = 2;  // Erreur sur l'antenne i
     469                    }
    246470                }
    247471            }
    248         }
    249 
    250         /* On sauvegarde le message dans le tableau log */
    251         os << lognum << " : " << reponse;
    252        
    253         Affiche(os.str(), false);
    254         Affiche("\n", false);
    255 
    256         logs[lognum++]=os.str();
    257         if (lognum>=MAXLOG-1) lognum=0;
     472
     473            // On sauvegarde le message dans le tableau logs
     474
     475            stringstream os;
     476
     477            os << lognum << " : " << reponse;
     478
     479            Affiche(os.str() + "\n", false);
     480
     481            if (lognum<MAXLOG-1) logs[lognum++] = os.str();
     482
     483            reponse = memreponse;
     484        }
     485        else reponse="";
    258486         
    259         /*on actualise la fenêtre */
     487
     488    } while ( reponse !="" );
     489
     490     // on actualise la fenêtre
     491
    260492        Dessiner();
    261     }
    262 
    263     rouler((char *)reponse.c_str());
    264 }
    265 
    266 
    267 /* Est-ce que la réponse du pilote indi_BAO
    268 est conforme à ce que l'on attendait ? */
    269 bool VerifReponse(std::string reponseattendue)
    270 {
    271     std::string reponse;
    272 
    273     usleep(10000); // attendre 10 ms pour laisser le temps au pilote indi_BAO de répondre
    274 
    275     *client_socket >> reponse;
    276 
    277     if (reponse.find(reponseattendue)==string::npos)
    278     {   
    279         //réponse inconnue -> une erreur ?
    280         os << "Réponse du pilote indi_BAO :" << std::endl << reponse
    281                   << std::endl << std::endl << std::endl;
    282         Erreur(os.str());         
     493
     494    // on envoie un message pour actualiser la fenêtre graphique
     495
     496    rouler();
     497}
     498
     499
     500/**************************************************************************************
     501** Est-ce que la réponse du pilote indi_BAO est conforme à ce que l'on attendait ?
     502***************************************************************************************/
     503
     504bool BAOcontrol::VerifReponse(string reponseattendue)
     505{
     506    string reponse = "";
     507    string memreponse = "";
     508    int    duree = 0;
     509    bool   test = false;
     510
     511    // TODO :La réponse du driver ne vient pas tout de suite et on peut recevoir
     512    // des messages intermédiaires un peu étranges impliquant la fonction CONNECT, pourquoi ?
     513    // Là on lit les messages trois fois de suite pour essayer de voir passer le bon
     514    // Essayer de voir si on ne peut pas faire mieux...
     515
     516    for (int i=0; i<3 ;i++)
     517    {
     518        do
     519        {
     520            usleep(1000); // attendre 1 ms pour laisser le temps au pilote indi_BAO de répondre
     521
     522            *client_socket >> reponse;
     523
     524            duree++;
     525        }
     526        while (reponse.length() == 0 && duree<10 ); // on attend un message pendant 10 ms max
     527
     528        // on ajoute tous les messages reçus dans memmreponse
     529        // ->intéressant pour le debug
     530
     531        memreponse += reponse;
     532
     533        if (reponse.find(reponseattendue) != string::npos)
     534        {
     535            test = true;
     536            break;
     537        }
     538    }
     539
     540    if (!test)
     541    {
     542        // réponse inconnue -> une erreur ?
     543
     544        int pos = memreponse.find("message=");
     545
     546        if ( pos != string::npos )
     547        {
     548            memreponse = memreponse.substr(pos + 9);
     549
     550            memreponse = memreponse.substr(0, memreponse.find("\""));
     551
     552            Erreur("Réponse du pilote indi_BAO :" + memreponse + "\n\n");
     553        }
     554
     555        return false;
    283556    }
    284557
     
    287560
    288561
    289 /*Récupération de la date et de l'heure
    290  et calcul du jour julien et du tsl */
    291 void CalculJourJulien()
     562/**************************************************************************************
     563** Calcul du jour julien et du temps sidéral local
     564***************************************************************************************/
     565
     566void BAOcontrol::Update()
    292567{
    293568    struct tm date;
     
    296571    struct timezone tz;
    297572
     573    // On récupÚre la date et l'heure depuis l'horloge du systÚme
     574
    298575    time(&t);
    299576    date=*gmtime(&t);
    300577    gettimeofday(&tv, &tz);
    301578
    302     astro->Annee=(double)(date.tm_year+1900);
    303     astro->Mois=(double)(date.tm_mon+1);
    304     astro->Jour=(double)date.tm_mday;
    305     astro->Heu=(double)date.tm_hour;
    306     astro->Min=(double)date.tm_min;
    307     astro->Sec=(double)date.tm_sec+tv.tv_usec/1.0E6;
    308     astro->UTCP=0.0;//(double)date.tm_isdst;
    309 
    310     //Calcul du temps sidéral local et du JJ
    311 
    312     astro->CalculTSL();
    313 }
    314 
    315 
    316 /* gestion du thread permettant l'actualisation de la fenêtre graphique
    317  et la récupération des messages d'indi_BAO */
    318 void *my_thread_process (void * arg)
    319 {
     579    double Annee = (double)date.tm_year + 1900.0;
     580    double Mois  = (double)date.tm_mon + 1.0;
     581    double Jour  = (double)date.tm_mday;
     582    double Heu   = (double)date.tm_hour;
     583    double Min   = (double)date.tm_min;
     584    double Sec   = (double)date.tm_sec + tv.tv_usec / 1.0E6;
     585    double UTCP  = 0.0;//(double)date.tm_isdst;
     586
     587    /*Annee=2011;
     588    Mois=6;
     589    Jour=17;
     590    Heu=15;
     591    Min=53.0;
     592    Sec=00.0;*/
     593
     594    // On actualise la date et l'heure dans la classe Astro
     595
     596    DefinirDateHeure(Annee, Mois, Jour, Heu, Min, Sec);
     597
     598
     599    // On lance le calcul
     600
     601    CalculTSL();
     602}
     603
     604
     605/**************************************************************************************
     606** gestion du thread permettant
     607** -l'exécution d'une liste de mouvements programmés
     608** -l'actualisation de la fenêtre graphique
     609** -la récupération des messages du pilote indi_BAO
     610***************************************************************************************/
     611
     612void *BAOcontrol::my_thread_process ()
     613{
     614    stringstream os;
     615
     616    // Tant ue l'utilisateur n'a pas taper la commande 'exit'
    320617    while (NoExit)
    321618    {
    322         CalculJourJulien();
    323 
    324         //Execution d'un fichier de mouvements
     619        //On actualise le jour julien et le temps sidéral local
     620
     621        Update();
     622
     623        // On récupÚre le jour julien
     624
     625        double JJ = GetJJ();
     626
     627
     628        // Faut-il executer un fichier de mouvements ?
     629        // il faut qu'il y ait plus d'un mouvement
     630        // et exxecuter les commande dans ce test jusqu'au dernier mouvement
     631
    325632        if (run && numobjets>1 && runnum<numobjets)
    326633        {
    327             /* On lance l'exécution des mouvements programmés */
    328             if (astro->JJ>=objets[runnum].JJ && !objets[runnum].exec)
     634            // On lance le mouvement numéro runnum si la date correspond au début
     635            // de son exécution et que ce mouvement n'a pas été encore réalisé
     636
     637            if (JJ >= objets[runnum].JJ && !objets[runnum].exec)
    329638            {
     639                // petits messages pour l'utilisateur
     640
    330641                if (runnum==1) Affiche("Début de l'exécution du fichier de mouvements\n\n", true);
    331                 os << "Suivi de l'objet n°" << runnum << std::endl;
    332                 Affiche(os.str(), true);
     642
     643                os << "Suivi de l'objet n°" << runnum << endl;
     644                Affiche(&os, true);
     645
     646                // on indique que le mouvement est en cours d'exécution
     647                //ou qu'il a été déjà exécuté
     648
    333649                objets[runnum].exec=true;
    334650
    335                 Goto(objets[runnum].ad, objets[runnum].de, Transit);
     651                //on envoie l'ordre goto correspondant
     652
     653                Goto(objets[runnum].ad, objets[runnum].de, Transit, J2000);
    336654            }
    337655
    338             /*on arrive à la fin du mouvements i */
    339             if (astro->JJ>=objets[runnum].JJ+objets[runnum].Duree/3600.0/24.0)
     656
     657            // On arrive à la fin de l'exécution du mouvements runnum
     658
     659            if (JJ >= objets[runnum].JJ + objets[runnum].Duree / 3600.0 / 24.0 )
    340660            {
     661                // On interrompt le mouvement
     662
    341663                Abort();
    342664
    343                 /*fin de la commande run */
    344                 if (runnum+1>=numobjets)
     665                // S'il s'agit du dernier mouvement -> Fin de la commande run
     666
     667                if ( runnum + 1 >= numobjets )
    345668                {
    346669                    Affiche("Fin de l'execution du fichier de mouvements\n\n", true);
    347                     std::cout << std::endl << blue << ">";
     670
     671                    // on réaffiche le prompt
     672
     673                    cout << endl;
     674                    ChoixCouleurs==1 ? cout << blue1 : cout << blue2;
     675                    cout << ">";
     676
     677                    // on réinitiale toutes les variables impliquées dans la commande run
     678
    348679                    run=false;
    349680                    runnum=1;
    350681                    numobjets=1;
    351682
    352                     /*on sort du programme dans le cas ./BAOControl -r fileName */
    353                     if (exitrun) NoExit=false;
     683                    // On sort du programme dans le cas BAOControl -r fileName
     684
     685                    NoExit=!exitrun;
    354686                }
    355687                else
    356688                {
     689                    // on passe au mouvement suivant
     690
    357691                    runnum++;
    358692                }
     
    360694        }
    361695
     696        // on lit et affiche la réponse des microcontrolleurs
     697
    362698        LireReponse();
    363699
    364700        Dessiner();
    365701
    366         usleep(100000); //100 ms
    367     }
     702        // pause de 100 ms
     703
     704        usleep(100000);
     705    }
     706
     707    // l'utilisateur a tapé exit... On sort du thread...
     708
    368709
    369710    pthread_exit (0);
     
    371712
    372713
    373 
    374 /* Décomposition et vérification des dates, heures, AD et déclinaisons
    375  type = 0 -> Déclinaison/latitude
    376  type = 1 -> longitude
    377  type = 2 -> AD ou heure
    378  type = 3 -> date */
    379 bool Decomposition(std::string chaine, char type, float *a1, float *a2, float *a3)
    380 {
    381     std::string car, s;
    382     int pos1, pos2;
    383     float a, b, c;
    384 
    385     if (type==3) car="/"; else car=":";
    386    
    387     /* Y a-t-il 2 caractÚres : ou / à la suite ? */
    388     int test=0;
    389     for (int i=0; i<chaine.length(); i++) if (chaine[i]==car[0]) test++;
    390     if (test<2) return false;
    391 
    392     s=chaine.substr(0, chaine.find(car));
    393 
    394     a=atoi(s.c_str());
    395      
    396     s=chaine.substr(chaine.find(car)+1, chaine.rfind(car)-chaine.find(car)-1);
    397    
    398     b=atoi(s.c_str());
    399 
    400     s=chaine.substr(chaine.rfind(car)+1);
    401 
    402     c=atoi(s.c_str());
    403 
    404     if (type <3)
    405     {
    406         if ((type==0) && (a>90.0 || a<-90.0)) return false;
    407         if ((type==1) && (a>180.0 || a<-180.0)) return false;
    408         if ((type==2) && (a>23.0 || a<0.0)) return false;
    409         if (b<0.0 || b>59.0) return false;
    410         if (c<0.0 || c>=60.0) return false;
    411     }
    412     else
    413     {
    414         if (a<0.0 || a>31.0) return false;
    415         if (b<0.0 || b>12.0) return false;
    416     }
    417 
    418     if (a1!=NULL) *a1=a;
    419     if (a2!=NULL) *a2=b;
    420     if (a3!=NULL) *a3=c;
     714void* LancementThread(BAOcontrol * appli)
     715{
     716    appli->my_thread_process();
     717
     718    return 0;
     719}
     720
     721
     722
     723
     724/**************************************************************************************
     725** Décrypte les commandes saisies par l'utilisateur
     726** Exemples :
     727** DecompositionCommande("goto 10:10:10 25:10:10", "goto", &chaine1, &chaine2)
     728** retourne chaine1  = "10:10:10"
     729**          chaine2  = "25:10:10"
     730**
     731** DecompositionCommande("goto messier 1","goto", &chaine1, NULL) (avec chaine2=NULLL)
     732** retourne chaine1  = "messier 1"
     733**          chaine2  = NULL
     734***************************************************************************************/
     735
     736bool BAOcontrol::DecompositionCommande(string chaine, string commande, string *chaine1, string *chaine2)
     737{
     738    size_t pos = chaine.find(commande);
     739
     740    // si la commande est présente dans chaine, on continue
     741
     742    if (pos != string::npos)
     743    {
     744        // on s'intéresse aux caractÚres qui suivent la commande
     745
     746        pos += commande.length();
     747
     748        chaine = chaine.substr(pos);
     749
     750        // on ignore les espaces superflus
     751
     752        while (chaine[0] == ' ') chaine = chaine.substr(1);
     753
     754        // si on veut prendre les deux arguments d'un commande
     755
     756        if (chaine2 != NULL)
     757        {
     758            // on prend le premier bloc jusqu'au prochain espace -> c'est la chaine1
     759
     760            *chaine1 = chaine.substr(0, chaine.find(" "));
     761
     762            // puis on prend le deuxiÚme bloc -> c'est la chaine2
     763            pos = chaine.find(" ");
     764
     765            if (pos != string::npos)
     766            {
     767                chaine = chaine.substr(pos + 1);
     768
     769                while (chaine[0] == ' ') chaine = chaine.substr(1);
     770
     771                *chaine2 = chaine.substr(0, chaine.find(" "));
     772            }
     773        }
     774        else
     775        {
     776            // on prend tout d'un bloc aprÚs la commande -> chaine 1
     777            // utile pour une commande ty type goto m 42 qui doit retourner "m 42" dans une
     778            // même chaine
     779
     780            *chaine1 = chaine;
     781        }
     782    }
    421783
    422784    return true;
    423785}
    424786
    425 /* isole les différents éléments de la commande saisie par l'utilisateur */
    426 bool DecompositionCommande(std::string chaine, std::string commande, std::string *chaine1, std::string *chaine2)
    427 {
    428     size_t pos;
    429 
    430     pos = chaine.find(commande);
    431 
    432     if (pos!=string::npos)
    433     {
    434         pos+=commande.length();
    435 
    436         chaine=chaine.substr(pos);
    437 
    438         while (chaine[0] == ' ') chaine=chaine.substr(1);
    439 
    440         *chaine1=chaine.substr(0,chaine.find(" "));
    441 
    442         if (chaine2!=NULL)
    443         {
    444             pos = chaine.find(" ");
    445 
    446             if (pos!=string::npos)
    447             {
    448                 chaine=chaine.substr(pos+1);
    449 
    450                 while (chaine[0] == ' ') chaine=chaine.substr(1);
    451 
    452                 *chaine2=chaine.substr(0, chaine.find(" "));
    453             }
    454         }
    455     }
    456 
    457     return true;
    458 }
    459 
    460 
    461 /*Envoie la longitude et la latitude du lieu d'observation au pilote indi_BAO */
    462 bool EncoyerCoordGeographiques()
    463 {
     787
     788
     789/**************************************************************************************
     790** Envoie la longitude et la latitude du lieu d'observation au pilote indi_BAO
     791***************************************************************************************/
     792
     793bool BAOcontrol::EnvoyerCoordGeographiques()
     794{
     795    // la communication avec le pilote indi_BAO
     796    // se fait par l'envoie de petit fichier xml
     797    // d'où le cÃŽté complexe des commandes
     798
    464799    try
    465800    {
    466801        *client_socket << "<newNumberVector device=\"BAO\" name=\"GEOGRAPHIC_COORD\">";
    467802        *client_socket << "<oneNumber name=\"LAT\">";
    468         *client_socket << Latitude;
     803        *client_socket << LatitudeChar;
    469804        *client_socket << "</oneNumber>";
    470805        *client_socket << "<oneNumber name=\"LONG\">";
    471         *client_socket << Longitude;
     806        *client_socket << LongitudeChar;
    472807        *client_socket << "</oneNumber>";
    473808        *client_socket << "</newNumberVector>";
     
    475810        if (!VerifReponse("name=\"GEOGRAPHIC_COORD\" state=\"Ok\""))
    476811        {
    477             Erreur("ERREUR fct EncoyerCoordGeographiques : pas de réponse du pilote indi_BAO.\n\n");
     812            Erreur("ERREUR fct EnvoyerCoordGeographiques : pas de réponse du pilote indi_BAO.\n\n");
    478813
    479814            return false;
     
    481816    }
    482817
     818    // un problÚme ?
     819
    483820    catch ( SocketException& e )
    484821    {
    485         os << "Exception was caught:" << e.description() << std::endl;
    486         Erreur(os.str());
     822        Erreur("Exception was caught:" + e.description() + "\n");
    487823        return false;
    488824    }
    489825
    490     std::cout << "Les coordonnées géographiques ont bien été envoyées au pilote indi_BAO"  << std::endl << std::endl;
     826    Affiche("Les coordonnées géographiques ont bien été envoyées au pilote indi_BAO\n\n", true);
    491827
    492828    return true;
     
    494830
    495831
    496 /* Place les antennes en position de repos */
    497 bool Park()
     832
     833/**************************************************************************************
     834** Place les antennes en position de repos
     835***************************************************************************************/
     836
     837bool BAOcontrol::Park()
    498838{
    499839    try
     
    505845        *client_socket << "</newSwitchVector>";
    506846
    507         if (!VerifReponse("Envoi de la commande Park"))
     847        if (!VerifReponse("PARK OK"))
    508848        {
    509849            Erreur("La commande PARK a échoué.\n\n");;
     
    514854    catch ( SocketException& e)
    515855    {
    516         os << e.description() << "\n";
    517         Erreur(os.str());
     856        Erreur("Exception was caught:" + e.description() + "\n");
    518857        return false;
    519858    }
     
    525864
    526865
    527 /* Annule le mouvement en cours */
    528 bool Abort()
     866
     867/**************************************************************************************
     868** Annule le mouvement en cours
     869***************************************************************************************/
     870
     871bool BAOcontrol::Abort()
    529872{
    530873    try
     
    536879        *client_socket << "</newSwitchVector>";
    537880
    538         if (!VerifReponse("name=\"ABORT_MOTION\" state=\"Ok\""))
     881        if (!VerifReponse("ABORT OK"))
    539882        {
    540883            Erreur("L'annulation a échoué.\n\n");
     
    545888    catch ( SocketException& e)
    546889    {
    547         os << e.description() << "\n";
    548         Erreur(os.str());
     890        Erreur("Exception was caught:" + e.description() + "\n");
    549891        return false;
    550892    }
     
    555897}
    556898
    557 /*aller aux coordonnées ar et dec dans le mode transit ou tracking */
    558 bool Goto(std::string ar, std::string dec, bool Transit)
    559 {
     899
     900
     901/**************************************************************************************
     902** Diriger l'antenne vers les coordonnées ar et dec et suivre l'objet
     903** en activant le mode transit ou tracking.
     904** si J2000 == true, cela signifie que les coordonnées ar et dec sont données dans le
     905** le systÚme de coordonnées J2000 (écliptique et équinoxe du 1 janvier 2000 à 0 h TU)
     906** Des calculs supplémentaires (précession, nutation, abérration) sont alors nécessaires
     907***************************************************************************************/
     908
     909bool BAOcontrol::Goto(string ar, string dec, bool Transit, bool J2000)
     910{
     911    float  ar1, ar2, ar3;
     912    float  dec1, dec2, dec3;
     913    double arf, decf;
     914    double azi, hau;
     915
     916
     917     /*
     918     //Pour les tests
     919     ar="05:39:14.8";
     920     dec="23:19:24.1";
     921     printf("JJ=%10.10f\n", GetJJ());
     922     J2000=true;
     923     */
     924
     925    // Conversion de l'AD et de la déclinaison en radians
     926
     927    Decomposition(ar, 2, &ar1, &ar2, &ar3);
     928    Decomposition(dec, 0, &dec1, &dec2, &dec3);
     929   
     930    arf  = ( ar1  + ar2 / 60.0  + ar3 / 3600.0 ) * 15.0 * Pidiv180;
     931    decf = ( fabs(dec1) + dec2 / 60.0 + dec3 / 3600.0 ) * Pidiv180;
     932
     933    if (dec[0]=='-') decf = -decf;
     934
     935    // calculs pupplémentaires pour se ramener
     936    // à l'époque de l'observation
     937
     938    if (J2000)
     939    {
     940        Precession(&arf, &decf);
     941        NutationEtoile(&arf, &decf);
     942        AberrationAnnuelle(&arf, &decf);
     943    }
     944
     945    // on réécrit l'ar et la dec dans le format d'indi_BAO
     946
     947    ar  = DHMS(arf * N180divPi, true);
     948
     949    dec = DHMS(decf * N180divPi, false);
     950
     951    // on en informe l'utilisateur
     952
     953    Affiche("Coordonnées apparentes de l'objet :\n", true);
     954
     955    Affiche("AD=" + ar  + "   Dec=" + dec +"\n", true);
     956
     957   
     958    /*
     959    //Tests
     960    Azimut(arf, decf, &azi, &hau);
     961
     962    hau=RefractionAtmospherique(hau);
     963
     964    Affiche("Coordonnées rectangulaires liées au lieu d'observation :\n", true);
     965
     966    printf("Azimut = %s   Hauteur = %s\n", DHMS(azi*N180divPi,false).c_str(), DHMS(hau*N180divPi, false).c_str());
     967    */
     968
     969    // On transmet les coordonnées au pilote BAO
     970
    560971    try
    561972    {
     
    5971008    catch ( SocketException& e)
    5981009    {
    599         os << e.description() << "\n";
    600         Erreur(os.str());
     1010        Erreur("Exception was caught:" + e.description() + "\n");
    6011011        return false;
    6021012    }
    6031013
    604     os << "Les nouvelles coordonnées AD=" << ar << "  DEC=" << dec << " ont été envoyées au pilote indi_BAO.\n\n";
    605     Affiche(os.str(), true);
    606 
     1014    Affiche("Les nouvelles coordonnées AD=" + ar + " Dec=" + dec, true);
     1015    Affiche(" ont été envoyées au pilote indi_BAO.\n\n", true);
    6071016    return true;
    6081017}
    6091018
    6101019
    611 /*se connecter ou se déconnecter au pilote indi_BAO */
    612 bool Connect(bool connect)
     1020
     1021/**************************************************************************************
     1022** Se connecte ou se déconnecte au pilote indi_BAO
     1023***************************************************************************************/
     1024
     1025bool BAOcontrol::Connect(bool connect)
    6131026{
    6141027    try
     
    6451058    catch ( SocketException& e )
    6461059    {
    647         os << "Exception was caught:" << e.description() << std::endl;
    648         Erreur(os.str());
     1060        Erreur("Exception was caught:" + e.description() + "\n");
    6491061        return false;
    6501062    }
     
    6541066        Affiche("La connexion a été établie avec le pilote indi_BAO.\n\n", true);
    6551067
    656         EncoyerCoordGeographiques();
     1068        EnvoyerCoordGeographiques();
    6571069    }
    6581070    else
    6591071    {
    660         Affiche("Confirmation de la déconnexion avec le pilote indi_BAO.\n\n", true);
     1072        Affiche("BAOcontrol s'est bien déconnecté du pilote indi_BAO.\n\n", true);
    6611073    }
    6621074
     
    6651077
    6661078
    667 /* Lecture des mouvements planifiés dans le fichier fileName */
    668 bool LectureFichierMouvements(char * fileName)
    669 {
    670     char * section =(char * )malloc(80);
    671     char * key = (char *)malloc(80);
    672     char * chaine = (char *)malloc(80);
    673     char * value;
    674    
    675     Astro * AstroJJ;
    676    
     1079
     1080/**************************************************************************************
     1081** Lecture des mouvements planifiés contenus dans le fichier fileName
     1082***************************************************************************************/
     1083
     1084bool BAOcontrol::LectureFichierMouvements(string fileName)
     1085{
     1086    string section;
     1087    string key;
     1088    char * value   = NULL;
     1089
     1090    stringstream os;
    6771091    float a1, a2, a3, h;
    6781092
    6791093    numobjets=1;
    6801094
    681     os << "Lecture du fichier " << fileName << std::endl << std::endl;
    682     Affiche(os.str(), true);
    683 
    684     strcpy(section, "objet 1");
    685     strcpy(key, "date");
    686 
    687     while ((readINI(section, key, &value, fileName)) && (numobjets<MAXOBJETS))
    688     {
    689         os << "object n°" << numobjets << std::endl;
    690         Affiche(os.str(), true);
    691 
    692         strcpy(key, "date");
    693 
    694         if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 3, &a1, &a2, &a3)))
    695         {
    696             os << "Date du début de l'observation : le " << value;
    697             Affiche(os.str(), true);
    698 
    699             AstroJJ = new Astro();
    700            
    701             AstroJJ->Jour=a1;
    702             AstroJJ->Mois=a2;
    703             AstroJJ->Annee=a3;
    704 
    705             AstroJJ->CalculJJ(0.0);
    706 
    707             objets[numobjets].JJ=AstroJJ->JJ;
    708            
    709             delete AstroJJ;
     1095    Affiche("Lecture du fichier " + fileName +"\n\n", true);
     1096
     1097    //Lecture de la rubrique ParamÚtres
     1098
     1099    section = "parametres";
     1100    key     = "mode";
     1101
     1102    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1103    {
     1104        Transit = ( strstr(value, "transit") != NULL);
     1105        delete [] value;
     1106
     1107        if (Transit) Affiche("Mode transit activé.\n", true);
     1108        else Affiche("Mode tracking activé.\n", true);
     1109    }
     1110    else
     1111    {
     1112        Erreur("Le parametre mode est incorrect.\n");
     1113        return false;
     1114    }
     1115
     1116    key = "J2000";
     1117
     1118    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1119    {
     1120        J2000 = ( strstr(value, "on") != NULL);
     1121        delete [] value;
     1122
     1123        if (J2000) Affiche("Mode J2000 activé.\n\n", true);
     1124        else Affiche("Mode J2000 désactivé.\n\n", true);
     1125    }
     1126    else
     1127    {
     1128        Erreur("Le parametre J2000 est incorrect.\n");
     1129        return false;
     1130    }
     1131
     1132    // Lecture de la liste des observations
     1133
     1134    section = "objet 1";
     1135    key     = "date";
     1136
     1137
     1138    while ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1139            && (numobjets<MAXOBJETS))
     1140    {
     1141        os << "object n°" << numobjets << endl;
     1142        Affiche(&os, true);
     1143        delete [] value;
     1144        value = NULL;
     1145
     1146
     1147        // Lecture de la date et de l'heure de l'observation
     1148
     1149        key = "date";
     1150
     1151        if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1152                && (Decomposition(value, 3, &a1, &a2, &a3)))
     1153        {
     1154            Affiche("Date du début de l'observation : le " + (string)value, true);
     1155            delete [] value;
     1156            value = NULL;
     1157
     1158            objets[numobjets].JJ = CalculJJ(a3, a2, a1, 0.0);
    7101159        }
    7111160        else
    7121161        {
    713             os << "La date de la rubrique [objet " << numobjets << "] est incorrecte !" << std::endl;
    714             Erreur(os.str());       
     1162            os << "La date de la rubrique [objet " << numobjets << "] est incorrecte !" << endl;
     1163            Erreur(&os);
    7151164            return false;
    7161165        }
    7171166
    718         strcpy(key, "heure");
    719 
    720         if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 2, &a1, &a2, &a3)))
    721         {
    722             os << " à " <<  value ;
    723             Affiche(os.str(), true);
    724 
    725             objets[numobjets].JJ+=(a1+a2/60.0+a3/3600.0)/24.0;
    726            
    727             sprintf(chaine, " TU  -> JJ=%10.5f\n", objets[numobjets].JJ);
    728            
    729             Affiche(chaine, true);
    730            
    731             for (int i=1; i<numobjets; i++)
    732             {
    733               if (objets[i].JJ==objets[numobjets].JJ)
    734               {
    735                 os << "Attention, les observations des objets " << i << " et " << numobjets << " sont définies à la même date !\n";
    736                 Erreur(os.str());
    737               }
    738              
    739               if (objets[i].JJ+objets[i].Duree/3600/24.0>objets[numobjets].JJ)
    740               {
    741                 os << "Attention, les observations des objets " << i << " et " << numobjets << " se chevauchent !\n";
    742                 Erreur(os.str());
    743               }
    744             }
     1167        key = "heure";
     1168
     1169        if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1170                && (Decomposition(value, 2, &a1, &a2, &a3)))
     1171        {
     1172            Affiche(" à " + (string)value, true) ;
     1173            delete [] value;
     1174            value = NULL;
     1175
     1176
     1177            objets[numobjets].JJ += ( a1 + a2 / 60.0 + a3 / 3600.0 ) / 24.0;
     1178
     1179            os << " TU  -> JJ=" << fixed << objets[numobjets].JJ << scientific << endl;
     1180
     1181            Affiche(&os, true);
     1182
     1183            for (int i=1; i<numobjets; i++)
     1184            {
     1185                if (objets[i].JJ==objets[numobjets].JJ)
     1186                {
     1187                    os << "Attention, les observations des objets " << i << " et ";
     1188                    os << numobjets << " sont définies à la même date !" << endl;
     1189                    Erreur(&os);
     1190                }
     1191
     1192                if (objets[i].JJ+objets[i].Duree/3600/24.0>objets[numobjets].JJ)
     1193                {
     1194                    os << "Attention, les observations des objets " << i << " et " ;
     1195                    os << numobjets << " se chevauchent !" << endl;
     1196                    Erreur(&os);
     1197                }
     1198            }
    7451199        }
    7461200        else
    7471201        {
    748             os << "L'heure de la rubrique [objet " << numobjets << "] est incorrecte !" << std::endl;
    749             Erreur(os.str());
     1202            os << "L'heure de la rubrique [objet " << numobjets << "] est incorrecte !" << endl;
     1203            Erreur(&os);
    7501204            return false;
    7511205        }
    7521206
    7531207
    754 
    755 
    756         strcpy(key, "duree");
     1208        // Lecture de la durée de l'observation
     1209
     1210        key = "duree";
    7571211
    7581212        objets[numobjets].Duree=0.0;
    7591213
    760         if (readINI(section, key, &value, fileName))
    761         {
    762            os << "Durée de l'observation : " << value << " secondes" << std::endl;
    763            Affiche(os.str(), true);
    764 
    765            objets[numobjets].Duree=atof(value);
     1214        if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1215        {
     1216            Affiche("Durée de l'observation : " + (string)value + " secondes\n", true);
     1217            objets[numobjets].Duree=atof(value);
     1218            delete [] value;
     1219            value = NULL;
    7661220        }
    7671221        else
    7681222        {
    769             os << "La duree d'observation de la rubrique [objet " << numobjets << "] est incorrecte !" << std::endl;
    770             Erreur(os.str());
     1223            os << "La duree d'observation de la rubrique [objet " << numobjets << "] est incorrecte !\n";
     1224            Erreur(&os);
    7711225            return false;
    7721226        }
    7731227
    774 
    775         strcpy(key, "ad");
    776 
    777         strcpy(objets[numobjets].ad, "");
    778 
    779         if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 2, NULL, NULL, NULL)))
    780         {
    781             os << "Ascension droite de l'objet : " << value << std::endl;
    782             Affiche(os.str(), true);
    783            
    784             strcpy(objets[numobjets].ad, value);
     1228        // Lecture de l'ascension droite de l'objet
     1229
     1230        key = "ad";
     1231
     1232        objets[numobjets].ad = "";
     1233
     1234        if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1235                && (Decomposition(value, 2, NULL, NULL, NULL)))
     1236        {
     1237            Affiche("Ascension droite de l'objet : " + (string)value + "\n", true);
     1238            objets[numobjets].ad = value;
     1239            delete [] value;
     1240            value = NULL;
    7851241        }
    7861242        else
    7871243        {
    788             os << "L'ascension droite de la rubrique [objet " << numobjets << "] est incorrecte !" << std::endl;
    789             Erreur(os.str());
     1244            os << "L'ascension droite de la rubrique [objet " << numobjets << "] est incorrecte !";
     1245            os << endl;
     1246            Erreur(&os);
    7901247            return false;
    7911248        }
    7921249
    793 
    794         strcpy(key, "de");
    795 
    796         strcpy(objets[numobjets].de, "");
    797 
    798         if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 0, NULL, NULL, NULL)))
    799         {
    800             os << "Déclinaison de l'objet : " << value << std::endl << std::endl;
    801             Affiche(os.str(), true);
    802 
    803             strcpy(objets[numobjets].de, value);
     1250        // Lecture de la déclinaison de l'objet
     1251
     1252        key = "de";
     1253
     1254        objets[numobjets].de = "";
     1255
     1256        if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1257                && (Decomposition(value, 0, NULL, NULL, NULL)))
     1258        {
     1259            Affiche("Déclinaison de l'objet : " + (string)value + "\n\n", true);
     1260            objets[numobjets].de = value;
     1261            delete [] value;
     1262            value = NULL;
    8041263        }
    8051264        else
    8061265        {
    807             os << "La déclinaison de la rubrique [objet " << numobjets << "] est incorrecte !" << std::endl;
    808             Erreur(os.str());
     1266            os << "La déclinaison de la rubrique [objet " << numobjets << "] est incorrecte !";
     1267            os << endl;
     1268            Erreur(&os);
    8091269            return false;
    8101270        }
    8111271
    812         objets[numobjets].exec=false;
     1272        objets[numobjets].exec = false;
     1273
     1274        // On passe à l'objet suivant
    8131275
    8141276        numobjets++;
    8151277
    816         sprintf(section, "objet %i", numobjets);
    817 
    818     }
    819    
     1278        os << "objet "<< numobjets;
     1279
     1280        section = os.str();
     1281        os.str("");
     1282    }
     1283
     1284    if (value) delete [] value;
    8201285
    8211286    return true;
    8221287}
    8231288
    824 /*Execute le fichier de mouvements */
    825 bool Run(std::string fichier)
    826 {
    827     bool exec=LectureFichierMouvements((char *)fichier.c_str());
    828 
    829     CalculJourJulien();
    830 
    831     if (exec && numobjets>1)
    832     {
    833         if (objets[numobjets-1].JJ+objets[numobjets-1].Duree/3600.0/24.0 < astro->JJ)
     1289
     1290
     1291/**************************************************************************************
     1292** Execute le fichier de mouvements
     1293***************************************************************************************/
     1294
     1295bool BAOcontrol::Run(string fichier)
     1296{
     1297    stringstream os;
     1298
     1299    bool exec = LectureFichierMouvements(fichier);
     1300
     1301    Update();
     1302
     1303    if ( exec && numobjets>1 )
     1304    {
     1305        // Si le chargement du fichier s'est bien déroulé et qu'il y a plus d'un mouvement dedans
     1306
     1307        if (objets[numobjets-1].JJ + objets[numobjets-1].Duree / 3600.0 / 24.0 < GetJJ())
    8341308        {
    8351309            Erreur("Le fichier contient des dates qui sont toutes périmées. Exécution annulée.\n\n");
    836             if (exitrun) NoExit=false;
     1310            NoExit=!exitrun;
    8371311            return false;
    8381312        }
    8391313        else
    8401314        {
    841             os << "Execution du fichier " << fichier << " en attente..." << std::endl << std::endl;
    842             Affiche(os.str(), true);
     1315            Affiche("Execution du fichier " + fichier + " en attente...\n\n", true);
    8431316            run=true;
    8441317        }
     
    8461319    else
    8471320    {
    848         os << std::endl << "Le fichier " << fichier << " contient des erreurs ou n'existe pas...\n" << std::endl << std::endl;
    849         Erreur(os.str());
    850         if (exitrun) NoExit=false;
     1321        Erreur("\nLe fichier " + fichier + " contient des erreurs ou n'existe pas...\n\n\n");
     1322        NoExit=!exitrun;
    8511323        return false;
    8521324    }
     
    8561328
    8571329
    858 /*identification des commandes entrées par l'utilisateur */
    859 void DecodageEntreesUtilisateur(std::string chaine)
    860 {
    861     std::string ar, de, fichier;
    862 
    863 
    864     if (chaine.find("goto")!=string::npos)
    865     {
     1330
     1331/**************************************************************************************
     1332** Décomposition et vérification des dates, heures, AD et déclinaisons
     1333**
     1334** type = 0 -> Déclinaison/latitude
     1335** type = 1 -> longitude
     1336** type = 2 -> AD ou heure
     1337** type = 3 -> date
     1338**
     1339** Exemple de Decomposition("15:23:12", 2, a, b, c) retourne a=15, b=23, c=12
     1340** si la chaine a un format incorrect, la fct retourne false
     1341***************************************************************************************/
     1342
     1343bool BAOcontrol::Decomposition(string chaine, char type, float *a1, float *a2, float *a3)
     1344{
     1345    string car, s;
     1346    float a, b, c;
     1347
     1348    // pour les heures et les coordonnées, on attend ":" comme caractÚre séparateur, sinon
     1349    // on attend d'avoir des "/" pour une date
     1350
     1351    (type==3) ? car="/" : car=":";
     1352
     1353    // Y a-t-il 2 caractÚres ':' ou '/' dans la chaine ?
     1354    // C'est indispensable dans tous les cas
     1355
     1356    int test=0;
     1357    for (int i=0; i<chaine.length(); i++) if (chaine[i] == car[0]) test++;
     1358    if (test<2) return false;
     1359
     1360    // Extraction des trois nombres
     1361
     1362    s = chaine.substr(0, chaine.find(car));
     1363
     1364    a = atoi(s.c_str());
     1365
     1366    s = chaine.substr(chaine.find(car)+1, chaine.rfind(car) - chaine.find(car) - 1);
     1367
     1368    b = atoi(s.c_str());
     1369
     1370    s = chaine.substr(chaine.rfind(car)+1);
     1371
     1372    c = Arrondi(atof(s.c_str())*100.0)/100.0;
     1373
     1374    //vérification de la cohérence des infos contenues dans la chaine
     1375
     1376    if (type < 3 )
     1377    {
     1378        // pour une déclinaison
     1379        if ((type==0) && (a>90.0  || a<-90.0)) return false;
     1380        // pour une AD
     1381        if ((type==1) && (a>360.0 || a<0.0  )) return false;
     1382        // pour une heure
     1383        if ((type==2) && (a>23.0  || a<0.0  )) return false;
     1384        // pour les minutes
     1385        if (b<0.0 || b>59.0 ) return false;
     1386        //pour les secondes
     1387        if (c<0.0 || c>=60.0) return false;
     1388    }
     1389    else
     1390    {
     1391        //pour les jours
     1392        if (a<0.0 || a>31.0) return false;
     1393        //pour les mois
     1394        if (b<0.0 || b>12.0) return false;
     1395    }
     1396
     1397    if (a1!=NULL) *a1 = a;
     1398    if (a2!=NULL) *a2 = b;
     1399    if (a3!=NULL) *a3 = c;
     1400
     1401    return true;
     1402}
     1403
     1404
     1405
     1406
     1407/**************************************************************************************
     1408** identification des commandes entrées par l'utilisateur
     1409** puis exécution des commandes
     1410***************************************************************************************/
     1411
     1412void BAOcontrol::DecodageEntreesUtilisateur(string chaine)
     1413{
     1414    string ar, de, objet, fichier;
     1415    stringstream os;
     1416
     1417    // Permet de savoir si la derniÚre saisie de l'utilisateur
     1418    // est une commande valide
     1419    bool CommandeOK = false;
     1420
     1421
     1422    // Commande goto
     1423
     1424    if ( chaine.find("goto") != string::npos )
     1425    {
     1426        CommandeOK = true;
     1427
     1428        // L'utilisateur a fait suivre la commande goto de l'indication J2000
     1429
     1430        if (J2000 = (chaine.find("j2000") != string::npos))
     1431        {
     1432            Affiche("Prise en compte de la précession, de la nutation et de l'aberration...\n", true);
     1433
     1434            // On je garde que la premiÚre partie de la chaine avant J2000
     1435
     1436            chaine = chaine.substr(0, chaine.find("J2000"));
     1437        }
     1438
    8661439        if (DecompositionCommande(chaine, "goto", &ar, &de) && Decomposition(ar, 2, NULL, NULL, NULL) && Decomposition(de, 0, NULL, NULL, NULL))
    8671440        {
    868             Goto(ar, de, Transit);
     1441            // L'utilisateur a indiqué deux coordonnées valides -> on exécute le goto
     1442
     1443            Goto(ar, de, Transit, J2000);
    8691444        }
    8701445        else
    8711446        {
    872             Erreur("Erreur goto : le format de la commande est goto AD DEC\n \
     1447            // L'utilisateur a indiqué un nom d'objet aprÚs le goto -> on lance la recherche sur internet
     1448            // puis on envoie les coordonnées de l'objet au pilote indi_BAO
     1449
     1450            if ((DecompositionCommande(chaine, "goto", &objet, NULL)) && (chaine.find(":") == string::npos))
     1451            {
     1452                Coordonnees reponse;
     1453               
     1454                if (objet != "sun")
     1455                {
     1456                    reponse = ServeurNED(objet);
     1457                   
     1458                    if (reponse.ar!="" && reponse.dec!="")  Goto(reponse.ar, reponse.dec, Transit, true);
     1459                }
     1460                else
     1461                {   
     1462                    printf(" lancement\n");
     1463                   
     1464                    CalculARDecSoleil(&reponse);
     1465                   
     1466                    printf("%s   %s \n", reponse.ar.c_str(), reponse.dec.c_str());
     1467                   
     1468                    Goto(reponse.ar, reponse.dec, Transit, false);
     1469                }               
     1470            }
     1471            else
     1472            {
     1473                Erreur("Erreur goto : le format de la commande est goto AD DEC\n \
    8731474                    L AD doit être de la forme xx:yy:zz   (ex: 12:00:03 pour 12h 0m 3s)\n \
    874                     La déclinaison doit être de la forme +/-xx:yy:zz (ex: -12:50:01 pour -12° 50' 01'')\n\n");
    875         }
    876     }
    877    
    878    
    879     if (chaine.find("abort")!=string::npos)
    880     {
     1475                    La déclinaison doit être de la forme +/-xx:yy:zz (ex: -12:50:01 pour -12° 50' 01'')\n\n \
     1476                    Il est egalement possible de faire suivre la commande d'un nom d'un objet\n \
     1477                    Exemple goto M 31 ou encore goto ngc145\n \
     1478                    Ne pas préciser dans ce cas J2000.\n\n");
     1479            }
     1480        }
     1481    }
     1482
     1483    // Annulation du suivi en cours
     1484
     1485    if (chaine.find("abort") != string::npos)
     1486    {
     1487        CommandeOK = true;
     1488
    8811489        Abort();
    8821490
    883         if (chaine.find("run")!=string::npos)
     1491        // Annulation de l'exécution d'un fichier de mouvements
     1492
     1493        if (chaine.find("run") != string::npos)
    8841494        {
    8851495            run=false;
     
    8881498
    8891499            Affiche("Annulation de l'exécution du fichier de mouvements.\n\n", true);
    890            
    891             return;
    892         }
    893     }
    894    
    895 
    896     if (chaine.find("run")!=string::npos)
    897     {
     1500
     1501            return;
     1502        }
     1503    }
     1504
     1505    // Lance l'exécution d'un fichier de mouvements
     1506
     1507    if (chaine.find("run") != string::npos)
     1508    {
     1509        CommandeOK = true;
     1510
    8981511        if (DecompositionCommande(chaine, "run", &fichier, NULL))
    8991512        {
     
    9051518        }
    9061519    }
    907    
    908 
    909     if (chaine.find("connect")!=string::npos)
    910     {
    911         Connect(chaine.find("disconnect")==string::npos);
    912     }
    913        
    914 
    915     if (chaine.find("transit")!=string::npos)
    916     {
     1520
     1521    // se connecte/déconnecte au serveur
     1522
     1523    if (chaine.find("connect") != string::npos)
     1524    {
     1525        CommandeOK = true;
     1526
     1527        Connect(chaine.find("disconnect") == string::npos);
     1528    }
     1529
     1530    // Active le mode de suivi "transit"
     1531
     1532    if (chaine.find("transit") != string::npos)
     1533    {
     1534        CommandeOK = true;
     1535
    9171536        Affiche("Mode transit activé.\n\n", true);
    9181537
    9191538        Transit=true;
    9201539    }
    921    
    922 
    923     if (chaine.find("tracking")!=string::npos)
    924     {
     1540
     1541    // Active le mode de suivi "tracking"
     1542
     1543    if (chaine.find("tracking") != string::npos)
     1544    {
     1545        CommandeOK = true;
     1546
    9251547        Affiche("Mode tracking activé.\n\n", true);
    9261548
    9271549        Transit=false;
    9281550    }
    929    
    930 
    931     if (chaine.find("park")!=string::npos)
    932     {
     1551
     1552    // Place les antennes en position de repos
     1553
     1554    if (chaine.find("park") != string::npos)
     1555    {
     1556        CommandeOK = true;
     1557
    9331558        Park();
    9341559    }
    935    
    936 
    937    
    938    
    939 
    940     if (chaine.find("help")!=string::npos)
    941     {
    942         std::cout << std::endl;
    943 
    944         std::cout << "connect : connecte le pilote INDI" << std::endl;
    945         std::cout << "disconnect : ferme la connexion avec le pilote INDI" << std::endl;
    946         std::cout << "goto AD Dec : pointe l'objet aux coordonnées AD Dec" << std::endl;
    947         std::cout << "transit : mode de suivi transit" << std::endl;
    948         std::cout << "tracking : mode de suivi tracking" << std::endl;
    949         std::cout << "run filename : execute le fichier filename" << std::endl;
    950         std::cout << "abort run : annule l'exécution du fichier de mouvements" << std::endl;
    951         std::cout << "abort : annule le mouvement en cours" << std::endl;
    952         std::cout << "park : place les antennes en position de repos" << std::endl;
    953         std::cout << "exit : sortir de BAOControl" << std::endl;
    954 
    955         std::cout << std::endl;
    956     }
    957    
     1560
     1561    // interroge un serveur de temps pour mettre l'horloge du PC à jour
     1562
     1563    if (chaine.find("updatetime") != string::npos)
     1564    {
     1565        CommandeOK = true;
     1566
     1567        int rc = system("sntp -s fr.pool.ntp.org");
     1568
     1569        if (WEXITSTATUS(rc) ==-1 || WEXITSTATUS(rc) ==127)
     1570        {
     1571            Erreur("La commande sntp n'est pas accessible. Merci de vérifier.\n\n");
     1572        }
     1573    }
     1574
     1575    // Affiche tous les paramÚtres du programme
     1576
     1577    if (chaine.find("status") != string::npos)
     1578    {
     1579        CommandeOK = true;
     1580
     1581        os << "Latitude = " << (string)LatitudeChar << "\n";
     1582        os << "Longitude = " << (string)LongitudeChar << "\n\n";
     1583        os << "Serveur Indi = " << (string)Serveur << "\n";
     1584        os << "Port du serveur Indi = " << Port << "\n\n";
     1585        os << "Pression atmosphérique  = " << Pression << " mBar\n";
     1586        os << "Température = " << Temperature << " °C\n\n";
     1587        Affiche(&os, true);
     1588        if (Transit) Affiche("Mode Transit activé.\n\n", true);
     1589        else Affiche ("Mode Tracking activé.\n\n", true);
     1590    }
     1591
     1592    // interroge le serveur NED sur internet -> retourne les coordonnées de l'objet
     1593
     1594    if (chaine.find("search")!=string::npos)
     1595    {
     1596        string objet;
     1597
     1598        CommandeOK = true;
     1599
     1600        if (DecompositionCommande(chaine, "search", &objet, NULL))
     1601        {
     1602            ServeurNED(objet);
     1603        }
     1604    }
     1605
     1606    // Aide du programme
     1607
     1608    if (chaine.find("help") != string::npos)
     1609    {
     1610        CommandeOK = true;
     1611
     1612        cout << endl;
     1613
     1614        cout << "connect :           se connecte au pilote indi_BAO." << endl;
     1615        cout << "disconnect :        se déconnecte du pilote indi_BAO." << endl;
     1616        cout << "goto AD Dec :       pointe l'objet situé aux coordonnées apparentes AD Dec." << endl;
     1617        cout << "                    AD doit être au format xx:yy:zz et dec au format +/-xx:yy:zz" << endl;
     1618        cout << "                    exemple goto 12:10:05 -05:10:11 permettra de pointer l'objet" << endl;
     1619        cout << "                    situé aux coordonnées AD=12h10m5s et dec=-5°10'11''" << endl;
     1620        cout << "goto AD Dec J2000 : pointe l'objet situé aux coordonnées AD Dec dans le repÚre J2000." << endl;
     1621        cout << "                    Avant de pointer l'objet, le programme calcule la précession, la nutation et l'aberration" << endl;
     1622        cout << "                    pour ramener les coordonnées à l'écliptique et à l'équinoxe de l'observation." << endl;
     1623        cout << "goto nom_objet :    interroge la base NED pour trouver les coordonnées de l'objet puis le pointe." << endl;
     1624        cout << "                    exemples: goto m 31, goto messier 1, goto ngc 175, goto ic 434 etc..." << endl;
     1625        cout << "                    Dans ce mode, les coordonnées sont automatiquement rapportées" << endl;
     1626        cout << "                    à l'écliptique et à l'équinoxe de l'observation." << endl;
     1627        cout << "                    Aussi, merci de ne pas faire suivre les coordonnées de l'indication J2000."<< endl;
     1628        cout << "                    Goto sun permet de suivre le soleil." << endl;
     1629        cout << "search nom_objet :  interroge le serveur NED sur internet et retourne les coordonnées de l'objet." << endl;
     1630        cout << "transit :           active le mode de suivi transit." << endl;
     1631        cout << "tracking :          active le mode de suivi tracking." << endl;
     1632        cout << "status :            liste les paramÚtres du programme." << endl;
     1633        cout << "run filename :      exécute le fichier de mouvements filename." << endl;
     1634        cout << "abort run :         annule l'exécution du fichier de mouvements." << endl;
     1635        cout << "abort :             annule le mouvement en cours." << endl;
     1636        cout << "park :              place les antennes en position de repos." << endl;
     1637        cout << "updatetime :        synchronise l'horloge du PC avec un serveur de temps." << endl;
     1638        cout << "exit :              sortir de BAOControl." << endl;
     1639
     1640        cout << endl;
     1641    }
     1642
     1643    // Bye !
    9581644
    9591645    if (chaine.find("exit")!=string::npos)
    9601646    {
    961         Connect (false);
    962 
    963         NoExit=false;
    964     }
    965 }
    966 
    967 
    968 /* chargement des paramÚtres dans le fichier params */
    969 bool ChargementParametres()
    970 {
    971     char * section =(char * )malloc(80);
    972     char * key = (char *)malloc(80);
     1647        CommandeOK = true;
     1648
     1649        Abort();
     1650
     1651        Connect(false);
     1652
     1653        NoExit = false;
     1654    }
     1655
     1656    // La commande n'a pas été identifiée !
     1657
     1658    if (!CommandeOK) Erreur("Commande inconnue... Tapez help pour obtenir la liste des commandes disponibles.\n\n");
     1659}
     1660
     1661
     1662/**************************************************************************************
     1663** Interroge le serveur NED sur internet et retourne les coordonnées dans le repÚre J2000
     1664** Si pas de réponse, alors message d'erreur et les coordonnées sont égales à AR="" dec=""
     1665***************************************************************************************/
     1666
     1667Coordonnees BAOcontrol::ServeurNED(string objet)
     1668{
     1669    Coordonnees reponse;
     1670    stringstream send;
     1671
     1672    FILE *pFile = NULL;
     1673    int rc;
     1674
     1675    //initialsation des variables de retour
     1676
     1677    reponse.ar = "";
     1678    reponse.dec = "";
     1679
     1680    // le nom de l'objet ne doit pas contenir des espace pour la requête NED
     1681    // on les remplace par des '+'
     1682
     1683    for (int i=0; i<objet.length(); i++) if (objet[i] == ' ') objet[i]='+';
     1684
     1685    // Effacer le fichier result s'il existe dans le répertoire du programme
     1686
     1687    if ((pFile = fopen ("result", "r")) != NULL )
     1688    {
     1689        fclose (pFile);
     1690        rc = system( "rm result");
     1691    }
     1692
     1693    // On utilise l'utilitaire curl pour passer la requête au serveur NED
     1694    // On sauvegarde le résultat dans le fichier result
     1695
     1696    send << "curl >> result \"http://ned.ipac.caltech.edu/cgi-bin/nph-objsearch?objname=";
     1697    send << objet;
     1698    send << "&extend=no&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&out_csys=Equatorial&out_equinox=J2000.0";
     1699    send << "&obj_sort=RA+or+Longitude&of=ascii_bar&zv_breaker=30000.0&list_limit=5&img_stamp=NO\"";
     1700
     1701    Affiche("Envoi de la requête au serveur NED...\n", true);
     1702
     1703    // on lance la requête
     1704
     1705    rc = system(send.str().c_str() );
     1706
     1707    // traitement du résultat
     1708
     1709    if (WEXITSTATUS(rc) ==-1 || WEXITSTATUS(rc) ==127)
     1710    {
     1711        Erreur("La commande curl n'est pas accessible. Merci de vérifier.\n\n");
     1712    }
     1713    else
     1714    {
     1715        // On a obtenu quelque chose
     1716
     1717        int nbRead = 0;
     1718
     1719        char *pBuf;
     1720
     1721        pBuf = new char [100000];
     1722
     1723        // On laisse un peu de temps au serveur pour répondre.
     1724        // C'est pas vraiment indispensable mais bon...
     1725
     1726        sleep(1);
     1727
     1728        // On ouvre le fichier result
     1729
     1730        pFile = fopen ("result", "r");
     1731
     1732        if (pFile)
     1733        {
     1734            nbRead = readline (pFile, pBuf);
     1735
     1736            // Si le fichier n'est pas vide
     1737            if (nbRead!=-1)
     1738            {
     1739                if (strstr(pBuf, "Error") != NULL)
     1740                {
     1741                    // Le fichier contient une indication d'erreur -> pas de réponse exploitable
     1742
     1743                    Affiche("\nLe serveur NED n'a pas trouvé de réponse à votre demande...\n", true);
     1744                }
     1745                else
     1746                {
     1747                    // on analyse la réponse
     1748
     1749                    Affiche("\nRéponse du serveur :\n", true);
     1750
     1751                    do
     1752                    {
     1753                        // on cherche la premiÚre suggestion de NED
     1754                        // Il faudra peut-être un peu complexifier par la suite
     1755
     1756                        if (pBuf[0] == '1')
     1757                        {
     1758                            string chaine = (string)pBuf;
     1759                            string chaine2;
     1760
     1761                            chaine=chaine.substr(chaine.find('|')+1);
     1762
     1763                            // affiche le nom de l'objet dans le serveur NED
     1764
     1765                            Affiche(chaine.substr(0, chaine.find('|')) + "\n", true);
     1766
     1767                            chaine = chaine.substr(chaine.find('|') + 1);
     1768
     1769                            chaine2 = chaine.substr(0, chaine.find('|'));
     1770
     1771                            double ar = atof(chaine2.c_str());
     1772
     1773                            // affiche l'ascension droite
     1774
     1775                            Affiche("AD (J2000) = " + DHMS(ar, true) + "\n", true);
     1776
     1777                            reponse.ar = DHMS(ar, true);
     1778
     1779                            chaine=chaine.substr(chaine.find('|')+1);
     1780
     1781                            chaine2 = chaine.substr(0, chaine.find('|'));
     1782
     1783                            double dec = atof(chaine2.c_str());
     1784
     1785                            // on affiche la déclinaison
     1786
     1787                            Affiche("Dec (J2000) = " + DHMS(dec, false)+"\n", true);
     1788
     1789                            reponse.dec = DHMS(dec, false);
     1790                        }
     1791
     1792                        nbRead = readline (pFile, pBuf);
     1793
     1794                    } while (nbRead!=-1);
     1795                }
     1796            }
     1797            else
     1798            {
     1799                Erreur("\nLa connexion semble impossible avec le serveur NED !\n\n");
     1800            }
     1801
     1802            fclose(pFile);
     1803        }
     1804        else
     1805        {
     1806            Erreur("\nLa connexion semble impossible avec le serveur NED !\n\n");
     1807        }
     1808
     1809        delete [] pBuf;
     1810
     1811        Affiche("\n", true);
     1812    }
     1813
     1814    return reponse;
     1815}
     1816
     1817
     1818
     1819/**************************************************************************************
     1820** Lecteur d'un fichier ligne aprÚs ligne
     1821** retourne -1 à la fin
     1822***************************************************************************************/
     1823
     1824int BAOcontrol::readline (FILE * pfile, char *tab)
     1825{
     1826    int nbchar = 0;
     1827    char c;
     1828
     1829    while ((c = getc (pfile)) != '\n')
     1830    {
     1831        if (c == EOF)
     1832        {
     1833            break;
     1834        }
     1835        tab[nbchar++] = c;
     1836    }
     1837    tab[nbchar] = '\0';
     1838
     1839    while (nbchar>0 && tab[nbchar-1]==' ')
     1840    {
     1841        tab[--nbchar] = '\0';
     1842    }
     1843
     1844    while (tab[0]==' ') for (int i=1; i<=nbchar; i++) tab[i-1] = tab[i];
     1845
     1846    if (c == EOF) nbchar=-1;
     1847
     1848    return (nbchar);
     1849}
     1850
     1851
     1852
     1853/**************************************************************************************
     1854** chargement des paramÚtres contenus dans le fichier params
     1855***************************************************************************************/
     1856
     1857bool BAOcontrol::ChargementParametres(string fileName)
     1858{
     1859    string section;
     1860    string key;
    9731861    char * value;
    974     char * fileName = (char *)malloc(sizeof(char)*255);
     1862    stringstream os;
     1863
    9751864
    9761865
    9771866    Affiche("Lecture du fichier de configuration 'params' :\n\n", true);
    9781867
    979     strcpy(fileName,"params");
    980 
    981     strcpy(section, "connexion indi");
    982 
    983     strcpy(key, "serveur");
    984 
    985     strcpy(Serveur, "");
    986 
    987     if (readINI(section, key, &value, fileName))
    988     {
    989         strcpy(Serveur, value);
    990         os << "serveur=" << Serveur << std::endl;
    991         Affiche(os.str(), true);
     1868
     1869    /////////////////////////////////////////
     1870    // Rubrique Coodonnées géographiques
     1871
     1872    section = "coordonnees geographiques";
     1873
     1874    key = "latitude";
     1875
     1876    if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1877            && (Decomposition(value, 0, NULL, NULL, NULL)))
     1878    {
     1879        LatitudeChar = (string)value;
     1880        delete [] value;
     1881        Affiche("latitude = " + LatitudeChar +"\n", true);
    9921882    }
    9931883    else
    9941884    {
    995         os << "Nom du serveur invalide !" << std::endl;
     1885        Erreur("La latitude est incorrecte !\n");
     1886        return false;
     1887    }
     1888
     1889
     1890    key = "longitude";
     1891
     1892    if ((readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1893            && (Decomposition(value, 1, NULL, NULL, NULL)))
     1894    {
     1895        LongitudeChar = (string)value;
     1896        delete [] value;
     1897        Affiche("longitude = " + LongitudeChar +"\n\n", true);
     1898    }
     1899    else
     1900    {
     1901        Erreur("La longitude est incorrecte !\n");
     1902        return false;
     1903    }
     1904
     1905
     1906    /////////////////////////////////////////
     1907    // rubrique connexion
     1908
     1909    section = "connexion indi";
     1910
     1911    key = "serveur";
     1912
     1913    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1914    {
     1915        Serveur = (string)value;
     1916        delete [] value;
     1917        Affiche("serveur = " + Serveur +"\n", true);
     1918    }
     1919    else
     1920    {
     1921        Erreur("Nom du serveur invalide !\n");
     1922        return false;
     1923    }
     1924
     1925
     1926    key = "port";
     1927
     1928    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1929    {
     1930        Port = (string)value;
     1931        delete [] value;
     1932        Affiche("port = " + Port +"\n\n", true);
     1933    }
     1934    else
     1935    {
     1936        Erreur("Numéro de port incorrect !\n");
     1937        return false;
     1938    }
     1939
     1940
     1941    /////////////////////////////////////////
     1942    // Rubrique paramÚtres de l'atmosphÚre
     1943
     1944    section = "atmosphere";
     1945
     1946    key = "pression";
     1947
     1948    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1949    {
     1950        Pression = atof(value);
     1951        delete [] value;
     1952        os << "pression = " << Pression << endl;
     1953        Affiche(&os, true);
     1954    }
     1955    else
     1956    {
     1957        os << "La pression atmosph&rique est incorrecte !" << endl;
     1958        Erreur(&os);
     1959        return false;
     1960    }
     1961
     1962    key = "temperature";
     1963
     1964    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1965    {
     1966        Temperature=atof(value);
     1967        delete [] value;
     1968        os << "température = " << Temperature << endl << endl;
     1969        Affiche(&os, true);
     1970    }
     1971    else
     1972    {
     1973        Erreur("La température est incorrecte !\n");
     1974        return false;
     1975    }
     1976
     1977
     1978    /////////////////////////////////////////
     1979    // Rubrique suivi
     1980
     1981    section = "suivi";
     1982
     1983    key = "mode";
     1984
     1985    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     1986    {
     1987        Transit = (strstr(value, "transit") != NULL);
     1988        Affiche("mode suivi = " + (string)value + "\n", true);
     1989        delete [] value;
     1990    }
     1991    else
     1992    {
     1993        Erreur("Le paramÚtre mode est incorrect !\n");
     1994        return false;
     1995    }
     1996
     1997
     1998
     1999    key = "delai_transit";
     2000
     2001    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     2002    {
     2003        delaitransit=atoi(value);
     2004        delete [] value;
     2005        os << "delai transit = " << delaitransit << " sec" << endl;
     2006        Affiche(&os, true);
     2007    }
     2008    else
     2009    {
     2010        Erreur("Le paramÚtre delai_transit est incorrect !\n");
     2011        return false;
     2012    }
     2013
     2014
     2015    key = "delai_tracking";
     2016
     2017    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     2018    {
     2019        delaitracking=atoi(value);
     2020        delete [] value;
     2021        os << "delai tracking = " << delaitracking << " sec" << endl << endl;
     2022        Affiche(&os, true);
     2023    }
     2024    else
     2025    {
     2026        Erreur("Le paramÚtre delai_tracking est incorrect !\n");
     2027        return false;
     2028    }
     2029
     2030
     2031    /////////////////////////////////////////
     2032    // Rubrique divers
     2033
     2034    section = "divers";
     2035
     2036    key = "couleurs";
     2037
     2038    if (readINI(section.c_str(), key.c_str(), &value, fileName.c_str()))
     2039    {
     2040        ChoixCouleurs=atoi(value);
     2041        delete [] value;
     2042    }
     2043    else
     2044    {
     2045        /*os << "Le paramÚtre couleurs est incorrect !" << endl;
    9962046        Erreur(os.str());
    997         return false;
    998     }
    999 
    1000     strcpy(key, "port");
    1001 
    1002     if (readINI(section, key, &value, fileName))
    1003     {
    1004         Port=atoi(value);
    1005         os << "port=" << Port << std::endl << std::endl;
    1006         Affiche(os.str(), true);
    1007     }
    1008     else
    1009     {
    1010         os << "Numéro de port incorrect !" << std::endl;
    1011         Erreur(os.str());
    1012         return false;
    1013     }
    1014 
    1015     strcpy(section, "coordonnees geographiques");
    1016 
    1017     strcpy(Latitude, "");
    1018     strcpy(Longitude, "");
    1019    
    1020     strcpy(key, "latitude");
    1021 
    1022     if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 0, NULL, NULL, NULL)))
    1023     {
    1024         strcpy(Latitude, value);
    1025         os << "latitude=" << Latitude << std::endl;
    1026         Affiche(os.str(), true);
    1027     }
    1028     else
    1029     {
    1030         os << "La latitude est incorrecte !" << std::endl;
    1031         Erreur(os.str());
    1032         return false;
    1033     }
    1034 
    1035     strcpy(key, "longitude");
    1036 
    1037     if ((readINI(section, key, &value, fileName)) && (Decomposition(value, 1, NULL, NULL, NULL)))
    1038     {
    1039         strcpy(Longitude, value);
    1040         os << "longitude=" << Longitude << std::endl << std::endl;
    1041         Affiche(os.str(), true);
    1042     }
    1043     else
    1044     {
    1045         os << "La longitude est incorrecte !" << std::endl;
    1046         Erreur(os.str());
    1047         return false;
    1048     }
    1049 
    1050     strcpy(section, "transit");
    1051 
    1052     strcpy(key, "delai");
    1053 
    1054     if (readINI(section, key, &value, fileName))
    1055     {
    1056         delaitransit=atoi(value);
    1057         os << "delai transit= " << delaitransit << " sec" << std::endl;
    1058         Affiche(os.str(), true);
    1059     }
    1060     else
    1061     {
    1062         os << "Le paramÚtre transit est incorrect !" << std::endl;
    1063         Erreur(os.str());
    1064         return false;
    1065     }
    1066 
    1067     strcpy(section, "tracking");
    1068 
    1069     strcpy(key, "delai");
    1070 
    1071     if (readINI(section, key, &value, fileName))
    1072     {
    1073         delaitracking=atoi(value);
    1074         os << "delai tracking= " << delaitracking << " sec" << std::endl << std::endl;
    1075         Affiche(os.str(), true);
    1076     }
    1077     else
    1078     {
    1079         os << "Le paramÚtre tracking est incorrect !" << std::endl;
    1080         Erreur(os.str());
    1081         return false;
     2047        return false;*/
    10822048    }
    10832049
     
    10872053
    10882054
    1089 int main(int argc, char **argv)
    1090 {
    1091     std::string chaine;
     2055/**************************************************************************************
     2056** Routine principale
     2057***************************************************************************************/
     2058
     2059int BAOcontrol::init(int argc, char **argv)
     2060{
     2061    string chaine;
    10922062
    10932063    pthread_t th1;
    10942064
    1095     if (argc >1)
     2065    // gestion au démarrage des paramÚtres en ligne de commande
     2066
     2067    if ( argc >1 )
    10962068    {
    10972069        if (strstr(argv[1], "-h")!=NULL)
    10982070        {
    1099             std::cout << "usage :\n \
     2071            cout << "usage :\n \
    11002072       BAOControl -h ou --help : affiche l'aide\n \
    1101        BAOControl -r FileName : execute les mouvements définis dans le fichier FileName\n\n";
     2073       BAOControl -r FileName : exécute les mouvements définis dans le fichier FileName\n\n";
    11022074
    11032075            return 0;
     
    11052077    }
    11062078
    1107     for (int i=0; i<MAXANTENNES; i++)
    1108     {
    1109         Antennes[i].ok=0;
    1110         Antennes[i].ip=0;
    1111     }
    1112 
    1113     for (int i=0; i<MAXOBJETS; i++)
    1114     {
    1115         objets[i].JJ=0;
    1116         objets[i].exec=false;
    1117     }
    1118 
    1119 
    1120     Affiche("\n\n\n\n\n\n \
    1121     ************************\n \
    1122     *      BAO Control     *\n \
    1123     *         v0.1         *\n \
    1124     *      10/11/2010      *\n \
    1125     ************************\n\n", true);
    1126 
    1127     if (!ChargementParametres())
    1128     {
    1129         Erreur("Le fichier de configuration 'params' contient des erreurs ou n'existe pas. Merci de vérifier.\n");
    1130         exit(1);
    1131     }
    1132 
    1133     client_socket = new ClientSocket("localhost", Port );
    1134 
    1135    
    1136     Connect(true);
    1137 
    1138     if (argc == 1)  std::cout << "Tapez help pour obtenir des infos sur les commandes disponibles.\n" << std::endl;
     2079    if (argc == 1)  cout << "Tapez help pour obtenir la liste des commandes disponibles.\n" << endl << endl;
     2080
     2081    // On lance la fenêtre graphique
    11392082
    11402083    initialiserFenetre();
     
    11422085    XSelectInput(d,w, ExposureMask );
    11432086
    1144     if (pthread_create(&th1, NULL, my_thread_process, NULL) < 0) {
     2087    // On lance le thread pour gérer la fenêtre graphique
     2088    // la communication avec indi_BAO et le suivi des objets
     2089
     2090    if (pthread_create(&th1, NULL, (void*(*)(void*))LancementThread, this) < 0) {
    11452091        Erreur("Impossible de créer le thread\n");
    1146         exit (1);
    1147     }
    1148    
    1149     astro = new Astro();
     2092        return -1;
     2093    }
     2094
     2095
     2096
     2097    // si on a utilisé l'option -r en ligne de commande
     2098    // alors on charge et on lance l'exécution d'un fichier de mouvements
    11502099
    11512100    if (argc == 3)
     
    11562105
    11572106            Run(argv[2]);
     2107
     2108            // on attend ici la fin de l'exécution du fichier de mouvements
    11582109
    11592110            do
     
    11692120    else
    11702121    {
     2122        // Saisie et décodage des commandes entrées par l'utilisateur
    11712123
    11722124        do
    11732125        {
    1174             std::cout << blue << '>';
    1175             getline(std::cin, chaine);
    1176             std::cout << black;
    1177 
     2126            // Prompt
     2127            ChoixCouleurs==1 ? cout << blue1 : cout << blue2;
     2128            cout << '>';
     2129            // saisie
     2130            getline(cin, chaine);
     2131            ChoixCouleurs==1 ? cout << grey1 : cout << grey2;
     2132
     2133            // on met en minuscules
    11782134            for (int i=0; i<chaine.size();++i) chaine[i] = tolower(chaine[i]);
    11792135
     2136            // on décode et exécute les commandes
    11802137            DecodageEntreesUtilisateur(chaine);
    11812138        }
    11822139        while (NoExit);
    1183     }
    1184 
    1185     delete astro;
    1186     delete client_socket;
     2140
     2141        pthread_join(th1 ,NULL);
     2142        //pthread_detach(th1);
     2143    }
    11872144
    11882145    return 0;
  • BAORadio/libindi/libindi/BAOControl/baocontrol.h

    r502 r504  
     1// Definition of the Astro BAOcontrol
     2// Franck RICHARD
     3// BAORadio
     4
     5#ifndef BAOcontrol_class
     6#define BAOcontrol_class
     7
     8
    19#include <iostream>
    210#include <string.h>
     
    513#include "SocketException.h"
    614#include <stdio.h>
     15#include <stdlib.h>
    716#include <pthread.h>
    817#include <X11/Xlib.h>
    918#include "filetools.h"
    10 #include "astro.h"
     19#include "../drivers/telescope/astro.h"
    1120#include "math.h"
    1221#include <time.h>
     
    1524
    1625
    17 #define red "\033[0;31m"
    18 #define blue "\033[0;34m"
    19 #define green "\033[0;32m"
    20 #define black "\033[0;30m"
     26// couleurs utilisées dans le terminal
     27
     28#define red1 "\033[0;31m"
     29#define blue1 "\033[0;34m"
     30#define green1 "\033[0;32m"
     31#define black1 "\033[0;30m"
     32#define grey1 "\033[1;30m"
     33#define red2 "\033[1;31m"
     34#define blue2 "\033[1;34m"
     35#define green2 "\033[1;32m"
     36#define black2 "\033[1;30m"
     37#define grey2 "\033[1;37m"
     38
     39
     40// limites des tableaux
    2141
    2242#define MAXLOG 1000
    2343#define MAXOBJETS 100
    24 #define MAXANTENNES 100
     44#define MAXANTENNES 50
    2545
    26 #define larg 600
    27 #define haut 10+30*12
     46
     47//dimensions de la fenêtre graphique
     48
     49#define haut_fenetre 10+22*10
     50#define larg_fenetre 605
    2851
    2952using namespace std;
     
    3255struct DefAntenne
    3356{
    34     unsigned char ip;
     57    unsigned char ip;                   // Adresse ip d'une antenne
    3558
    36     char ok;
     59    char ok;                            // actuellement disponible ?
    3760};
     61
     62// objets stockés dans le fichier de mouvements
    3863
    3964struct DefObjets
    4065{
    41     double JJ;
    42     double Duree;
    43     char ad[10];
    44     char de[10];
    45     bool exec;
     66    double JJ;                          // Jour julien où le télescope doit aller pointer vers l'objet
     67    double Duree;                       // Durée de l'observation de l'objet en sec
     68    string ad;                          // Ascension droite J2000 de l'objet
     69    string de;                          // déclinaison J2000 de l'objet
     70    bool exec;                          // En cours d'exécution ?
    4671};
    4772
    4873
    49 char Latitude[80];
    50 char Longitude[80];
    51 char Serveur[80];
    5274
    53 std::string logs[MAXLOG];
     75class BAOcontrol : public Astro
     76{
    5477
    55 std::stringstream os;
     78public:
     79    BAOcontrol();
     80    ~BAOcontrol();
    5681
    57 int Port=0;
    58 int delaitransit=0;
    59 int delaitracking=0;
    60 int lognum=0;
    61 int numAntenne=0;
    62 int numobjets=0;
    63 int runnum=1;
    64 
    65 struct DefAntenne Antennes[MAXANTENNES];
    66 struct DefObjets objets[MAXOBJETS];
    67 
    68 bool NoExit=true;
    69 bool Transit=false;
    70 bool run=false;
    71 bool exitrun=false;
    72 
    73 ClientSocket *client_socket;
    74 Astro *astro;
    75 
    76 Display * d;
    77 Window w;
    78 Pixmap db;
    79 GC noir, vert, rouge, gris;
     82    void *my_thread_process ();
     83    int init(int argc, char **argv);
    8084
    8185
    82 void initialiserFenetre();
    83 void Dessiner();
    84 void rouler(char* reponse);
    85 void LireReponse();
    86 void *my_thread_process (void * arg);
    87 bool Decomposition(std::string chaine, char type, float *a1, float *a2, float *a3);
    88 bool DecompositionCommande(std::string chaine, std::string commande, std::string *chaine1, std::string *chaine2);
    89 bool EncoyerCoordGeographiques();
    90 bool Connect(bool connect);
    91 bool Park();
    92 bool Abort();
    93 bool Goto(std::string ar, std::string dec, bool Transit);
    94 bool LectureFichierMouvements(char * fileName);
    95 bool Run(std::string fichier);
    96 void DecodageFonction(std::string chaine);
    97 bool ChargementParametres();
     86private:
     87    void Affiche(string chaine, bool AfficheEcran);
     88    void Affiche(stringstream *Message, bool AfficheEcran);
     89    void Erreur(string chaine);
     90    void Erreur(stringstream *Message);
     91    void initialiserFenetre();
     92    void Dessiner();
     93    void rouler();
     94    void LireReponse();
     95    bool VerifReponse(string reponseattendue);
     96    void Update();
     97    bool Decomposition(string chaine, char type, float *a1, float *a2, float *a3);
     98    bool DecompositionCommande(string chaine, string commande, string *chaine1, string *chaine2);
     99    bool EnvoyerCoordGeographiques();
     100    bool Park();
     101    bool Abort();
     102    bool Goto(string ar, string dec, bool Transit, bool J2000);
     103    bool Connect(bool connect);
     104    bool LectureFichierMouvements(string fileName);
     105    void DecodageEntreesUtilisateur(string chaine);
     106    bool Run(string fichier);
     107    bool ChargementParametres(string fileName);
     108    Coordonnees ServeurNED(string objet);
     109    int  readline (FILE * pfile, char *tab);
     110
     111
     112
     113    // Variables globales
     114
     115    XFontStruct * fd;                           // Police de caractÚres dans la fenêtre graphique
     116
     117    char ChoixCouleurs;                         // 1-pour un terminal à fond blanc    2-pour un terminal à fond noir
     118
     119    string logs[MAXLOG];                        // Sauvegarde de toutes les actions et réponses dans un tableau logs
     120
     121    int delaitransit;                           // Délai entre deux actualisations de la position en mode transit
     122    int delaitracking;                          // Délai entre deux actualisations de la position en mode tracking
     123    int lognum;                                 // Nbre d'enregistrements dans le tableau logs
     124    int numAntenne;                             // Nbre d'antennes connectées
     125    int numobjets;                              // Nbre d'objets dans le dernier fichier de mouvements chargé
     126    int runnum;                                 // Numéro de l'objet actuellement visé dans le fichier de mouvement
     127
     128    double Pression;                            // Pression atmosphérique en mBar
     129    double Temperature;                         // température de l'atmosphÚre
     130
     131    bool NoExit;                                // A-t-on tapé exit pour sortir ? Permet de fermer le thread à ce moment-là
     132    bool Transit;                               // Si oui, le mode transit est activé, sinon, c'est le mode tracking
     133    bool run;                                   // execute actuellement un fichier de mouvements
     134    bool exitrun;                               // doit-on sortir du programme à la fin de l'execution de la commande run ?
     135    bool J2000;                                 // est-ce que les coordonnées du fichier de mouvements sont en coordonnées J2000 ?
     136
     137    struct DefAntenne *Antennes;                // Sauvegarde de la situation actuelle de l'antenne i
     138    struct DefObjets  *objets;                  // Liste des objets chargés depuis un fichier de mouvements
     139
     140    string LatitudeChar;                        // Latitude du lieu d'observation. Chargée depuis le fichier de configuration
     141    string LongitudeChar;                       // Longitude du lieu d'observation. Chargée depuis le fichier de configuration
     142    string Serveur;                             // Nom ou IP du serveur faisant tourner indi_BAO. Par defaut c'est localhost
     143    string Port;                                // Port utilisé pour connecter le serveur indi_BAO
     144
     145    ClientSocket *client_socket;                // Socket permettant la connexion avec le pilote indi_BAO
     146
     147    Display * d;                                // contexte graphique
     148    Window w;                                   // fenêtre graphique
     149    Pixmap db;                                  // copie de la fenêtre pour permettre une actualisation sans scintillement
     150    GC noir, vert, rouge, gris;                 // couleurs utilisées dans la fenêtre graphique
     151
     152};
     153
     154#endif
  • BAORadio/libindi/libindi/BAOControl/filetools.cpp

    r502 r504  
    44
    55#define MAX_LENGHT 255
     6
     7
    68
    79/******************************************************
     
    2224readINI (char *sectionName, char *pKeyName, char **ppStr, char *fileName)
    2325{
    24   INI *pIni = NULL;
    25   SECTION *pSection = NULL;
    26   KEY *pKey = NULL;
    27   int trouve = 0;
    28   char *pSectionName = NULL;
    29   int offset = 0;
    30   //pStr = resultValue;
    31   TRY
    32   {
     26    INI *pIni = NULL;
     27    SECTION *pSection = NULL;
     28    KEY *pKey = NULL;
     29    int trouve = 0;
     30    char *pSectionName = NULL;
     31    int offset = 0;
     32 
     33
    3334    trouve = 0;
    3435    pIni = _loadINI (fileName);
     36    if (!pIni) return 0;
     37
    3538    /*recherche de la section */
    3639    offset = strlen (sectionName) + 3;
    37     pSectionName = (char *) m_malloc (sizeof (char) * offset);
     40    pSectionName = new char [offset];
    3841    pSectionName[0] = '[';
    3942    strcpy (pSectionName + 1, sectionName);
     
    4346    pSection = _findSECTION (pIni, pSectionName);
    4447
     48    delete [] pSectionName;
     49
    4550    if (pSection != NULL)
    46       {
     51    {
    4752        /*recherche de la cle */
    4853        pKey = _findKEY (pSection, pKeyName);
    4954        if (pKey != NULL)
    5055        {
    51           *ppStr = (char *) m_malloc (sizeof (char) * strlen (pKey->value) + 2);
    52           strcpy (*ppStr, pKey->value);
    53           (*ppStr)[strlen (pKey->value)] = '\0';
    54           trouve = 1;
    55         }
    56       }
    57   }
    58   CATCH (ERR_FOPEN)
    59   {
    60     printf ("impossible d'ouvrir le fichier %s\n", fileName);
    61     ppStr = NULL;
    62   }
    63   CATCH (ERR_MALLOC)
    64   {
    65     perror ("Probleme d'allocation memoire");
    66     exit (EXIT_FAILURE);
    67   } 
    68   ENDTRY;
    69  
    70  
    71   return trouve;
     56            *ppStr = new char [strlen (pKey->value) + 2];
     57            strcpy (*ppStr, pKey->value);
     58            (*ppStr)[strlen (pKey->value)] = '\0';
     59            trouve = 1;
     60
     61        }
     62    }
     63
     64    //On efface toutes les clés et toutes les sections
     65
     66    KEY *keyprev=NULL;
     67    SECTION * secprev=NULL;
     68    pSection=pIni->fils;
     69
     70    do
     71    {
     72        pKey=pSection->fils;
     73
     74        do
     75        {
     76            if (pKey->name) delete [] pKey->name;
     77            if (pKey->value) delete [] pKey->value;
     78
     79            keyprev=pKey;
     80
     81            KEY *prev=pKey;
     82            pKey=pKey->next;
     83
     84            delete prev;
     85
     86
     87        } while (pKey!=keyprev);
     88 
     89        if (pSection->name) delete []pSection->name;
     90
     91        secprev=pSection;
     92
     93        SECTION *sprev=pSection;
     94        pSection=pSection->next;
     95
     96        delete sprev;
     97
     98    }  while (pSection!=secprev);
     99
     100
     101
     102    delete [] pIni->fileName;
     103    delete pIni;
     104    pIni=NULL;
     105
     106    return trouve;
     107}
     108
     109int
     110readINI (const char *sectionName, const char *pKeyName, char **ppStr, const char *fileName)
     111{
     112     return readINI((char*)sectionName, (char*)pKeyName, ppStr, (char*)fileName);
    72113}
    73114
     
    87128 * 1 si reussite de la suppression, 0 sinon           *
    88129 ******************************************************/
     130/*
    89131int
    90132delINI (char *sectionName, char *pKeyName, char **ppStr, char *fileName)
     
    101143
    102144    pIni = _loadINI (fileName);
    103     /*recherche de la section */
     145    //recherche de la section
    104146    offset = strlen (sectionName) + 3;
    105147    pSectionName = (char *) m_malloc (sizeof (char) * offset);
     
    115157        if (pKeyName == NULL)
    116158          {
    117             /*on supprime toute la section */
     159            //on supprime toute la section
    118160
    119161            pKey = _lastKEY (pSection);
     
    128170        else
    129171          {
    130             /*recherche de la cle si indiquee */
     172            //recherche de la cle si indiquee
    131173            pKey = _findKEY (pSection, pKeyName);
    132174            if (pKey != NULL)
     
    139181                if (_delKEY (pKey))
    140182                  {
    141                     /*si la cle supprimee etait la derniere de la section */
     183                    //si la cle supprimee etait la derniere de la section
    142184                    _delSECTION (pSection);
    143185                  }
     
    165207  return del;
    166208}
    167 
     209*/
    168210/******************************************************
    169211 * NOM:                writeINI                       *
     
    173215 *  et la valeur de la cle est initialisee            *
    174216 *  sinon la cle existante de la section existante est*
    175  *  mise a jour                                       * 
     217 *  mise a jour                                       *
    176218 * ARGUMENTS:                                         *
    177219 * ENVIRONNEMENT:                                     *
     
    179221 *  NULL si echec ou keyValue si reussite             *
    180222 ******************************************************/
    181 char *
    182 writeINI (char *sectionName, char *keyName, char *keyValue, char *fileName)
     223
     224/*
     225
     226char * writeINI (char *sectionName, char *keyName, char *keyValue, char *fileName)
    183227{
    184228  char *pSectionName = NULL;
     
    209253    pSectionName[strlen (sectionName) + 1] = ']';
    210254    pSectionName[strlen (sectionName) + 2] = '\0';
    211     /*chargement */
     255    //chargement
    212256    pIni = _loadINI (fileName);
    213257
     
    225269  ENDTRY;
    226270
    227   /*recherche de la section */
     271  //recherche de la section
    228272  pSection = _findSECTION (pIni, pSectionName);
    229   /*recherche de la cle */
     273  //recherche de la cle
    230274  if (pSection != NULL)
    231275    {
     
    245289      else
    246290        {
    247           /*cle pas trouve dans la section, on ajoute la cle a la section */
     291          //cle pas trouve dans la section, on ajoute la cle a la section
    248292          pKey = _newKEY (pKeyName, pKeyValue);
    249293          _addKEY (pSection, pKey);
     
    252296  else
    253297    {
    254       /*section pas trouve, on la cree avec sa cle */
     298      //section pas trouve, on la cree avec sa cle
    255299      pSection = _newSECTION (pSectionName);
    256300      _addSECTION (pIni, pSection);
     
    262306  {
    263307
    264     /*sauvegarde */
     308    //sauvegarde
    265309    _saveINI (pIni);
    266310
     
    272316  ENDTRY;
    273317
    274   /*nettoyage */
     318  //nettoyage
    275319
    276320  free (pIni);
     
    284328  return pKeyValue;
    285329}
     330*/
    286331
    287332/******************************************************
     
    297342_delKEY (KEY * pKey)
    298343{
    299   int result = 0;
    300   if (pKey != NULL)
    301     {
    302       /*la cle n'est pas la premiere */
    303       if (pKey->prev != pKey)
    304         {
    305           if (pKey->next != pKey)
    306             {
    307               /*la cle n'est pas la derniere */
    308               pKey->prev->next = pKey->next;
    309             }
    310           else
    311             {
    312               result = 1;
    313               pKey->prev->next = pKey->prev;
    314             }
    315         }
    316       else
    317         {
    318           if (pKey->next != pKey)
    319             {
    320               /*la cle n'est pas non plus la derniere */
    321               pKey->parent->fils = pKey->next;
    322             }
    323           else
    324             {
    325               result = 1;
    326               pKey->parent->fils = NULL;
    327             }
    328         }
    329       _freeKEY (pKey);
    330       return result;
    331     }
    332   else
    333     {
    334       result = -1;
    335       return result;
     344    int result = 0;
     345    if (pKey != NULL)
     346    {
     347        /*la cle n'est pas la premiere */
     348        if (pKey->prev != pKey)
     349        {
     350            if (pKey->next != pKey)
     351            {
     352                /*la cle n'est pas la derniere */
     353                pKey->prev->next = pKey->next;
     354            }
     355            else
     356            {
     357                result = 1;
     358                pKey->prev->next = pKey->prev;
     359            }
     360        }
     361        else
     362        {
     363            if (pKey->next != pKey)
     364            {
     365                /*la cle n'est pas non plus la derniere */
     366                pKey->parent->fils = pKey->next;
     367            }
     368            else
     369            {
     370                result = 1;
     371                pKey->parent->fils = NULL;
     372            }
     373        }
     374        _freeKEY (pKey);
     375        return result;
     376    }
     377    else
     378    {
     379        result = -1;
     380        return result;
    336381    }
    337382}
     
    350395_delSECTION (SECTION * pSection)
    351396{
    352   if (pSection != NULL)
    353     {
    354       /*la cle n'est pas la premiere */
    355       if (pSection->prev != pSection)
    356         {
    357           /*la cle n'est pas la derniere */
    358           if (pSection->next != pSection)
    359             {
    360               pSection->prev->next = pSection->next;
    361             }
    362           else
    363             {
    364               pSection->prev->next = pSection->prev;
    365             }
    366         }
    367       else
    368         {
    369           /*la cle n'estpas nonplus la derniere */
    370           if (pSection->next != pSection)
    371             {
    372               pSection->parent->fils = pSection->next;
    373               pSection->next->prev = pSection->next;
    374             }
    375           else
    376             {
    377               pSection->parent->fils = NULL;
    378             }
    379         }
    380       _freeSECTION (pSection);
    381       return 1;
    382     }
    383   else
    384     {
    385       return 0;
     397    if (pSection != NULL)
     398    {
     399        /*la cle n'est pas la premiere */
     400        if (pSection->prev != pSection)
     401        {
     402            /*la cle n'est pas la derniere */
     403            if (pSection->next != pSection)
     404            {
     405                pSection->prev->next = pSection->next;
     406            }
     407            else
     408            {
     409                pSection->prev->next = pSection->prev;
     410            }
     411        }
     412        else
     413        {
     414            /*la cle n'estpas nonplus la derniere */
     415            if (pSection->next != pSection)
     416            {
     417                pSection->parent->fils = pSection->next;
     418                pSection->next->prev = pSection->next;
     419            }
     420            else
     421            {
     422                pSection->parent->fils = NULL;
     423            }
     424        }
     425        _freeSECTION (pSection);
     426        return 1;
     427    }
     428    else
     429    {
     430        return 0;
    386431    }
    387432}
     
    393438_freeKEY (KEY * pKey)
    394439{
    395   if (pKey != NULL)
    396     {
    397       pKey->parent = NULL;
    398       pKey->next = NULL;
    399       pKey->prev = NULL;
    400       if (pKey->value != NULL)
    401         {
    402           free (pKey->value);
    403         }
    404       if (pKey->name != NULL)
    405         {
    406           free (pKey->name);
    407         }
    408       free (pKey);
     440    if (pKey != NULL)
     441    {
     442        pKey->parent = NULL;
     443        pKey->next = NULL;
     444        pKey->prev = NULL;
     445        if (pKey->value != NULL)
     446        {
     447            delete [] pKey->value;
     448        }
     449        if (pKey->name != NULL)
     450        {
     451            delete [] pKey->name;
     452        }
     453        delete pKey;
     454
     455        pKey=NULL;
    409456    }
    410457}
     
    412459_freeSECTION (SECTION * pSection)
    413460{
    414   if (pSection != NULL)
    415     {
    416       pSection->parent = NULL;
    417       pSection->next = NULL;
    418       pSection->prev = NULL;
    419       if (pSection->name != NULL)
    420         {
    421           free (pSection->name);
    422         }
    423       free (pSection);
     461    if (pSection != NULL)
     462    {
     463        pSection->parent = NULL;
     464        pSection->next = NULL;
     465        pSection->prev = NULL;
     466        if (pSection->name != NULL)
     467        {
     468            delete [] pSection->name;
     469        }
     470        delete pSection;
     471
     472        pSection=NULL;
    424473    }
    425474}
     
    439488_newKEY (char *pKeyName, char *pKeyValue)
    440489{
    441   KEY *pKey;
    442   TRY
    443   {
    444     pKey = (KEY *) m_malloc (sizeof (KEY));
    445 
    446     pKey->name = (char *) m_malloc (sizeof (char) * strlen (pKeyName) + 1);
    447     pKey->value = (char *) m_malloc (sizeof (char) * strlen (pKeyValue) + 1);
    448   }
    449   CATCH (ERR_MALLOC)
    450   {
    451     perror ("Probleme d'allocation memoire");
    452     exit (EXIT_FAILURE);
    453   }
    454   ENDTRY;
    455 
    456   strcpy (pKey->name, pKeyName);
    457   strcpy (pKey->value, pKeyValue);
    458   pKey->parent = NULL;
    459   pKey->prev = pKey;
    460   pKey->next = pKey;
    461 
    462 
    463   return pKey;
     490    KEY *pKey;
     491
     492    {
     493        pKey = new KEY;
     494
     495        pKey->name = new char [strlen (pKeyName) + 1];
     496        pKey->value = new char [strlen (pKeyValue) + 1];
     497    }
     498
     499
     500    strcpy (pKey->name, pKeyName);
     501    strcpy (pKey->value, pKeyValue);
     502    pKey->parent = NULL;
     503    pKey->prev = pKey;
     504    pKey->next = pKey;
     505
     506    return pKey;
    464507}
    465508
     
    478521_newSECTION (char *pSectionName)
    479522{
    480   SECTION *pSection;
    481   TRY
    482   {
    483     pSection = (SECTION *) m_malloc (sizeof (SECTION));
    484 
    485     pSection->name =
    486       (char *) m_malloc (sizeof (char) * strlen (pSectionName) + 1);
    487   }
    488   CATCH (ERR_MALLOC)
    489   {
    490     perror ("Probleme d'allocation memoire");
    491     exit (EXIT_FAILURE);
    492   }
    493   ENDTRY;
    494 
    495   strcpy (pSection->name, pSectionName);
    496   pSection->parent = NULL;
    497   pSection->fils = NULL;
    498   pSection->prev = pSection;
    499   pSection->next = pSection;
    500   return pSection;
     523    SECTION *pSection;
     524
     525    {
     526        pSection = new SECTION;
     527
     528        pSection->name = new char [strlen (pSectionName) + 1];
     529    }
     530
     531
     532    strcpy (pSection->name, pSectionName);
     533    pSection->parent = NULL;
     534    pSection->fils = NULL;
     535    pSection->prev = pSection;
     536    pSection->next = pSection;
     537
     538    return pSection;
    501539}
    502540
     
    515553_findSECTION (INI * pIni, char *pSectionName)
    516554{
    517   SECTION *pSection = NULL;
    518   pSection = pIni->fils;
    519   while ((pSection != NULL) && (strcmp (pSection->name, pSectionName) != 0))
    520     {
    521       if (pSection == pSection->next)
    522         {
    523           pSection = NULL;
    524         }
    525       else
    526         {
    527           pSection = pSection->next;
    528         }
    529     }
    530   return pSection;
     555    SECTION *pSection = NULL;
     556    pSection = pIni->fils;
     557    while ((pSection != NULL) && (strcmp (pSection->name, pSectionName) != 0))
     558    {
     559        if (pSection == pSection->next)
     560        {
     561            pSection = NULL;
     562        }
     563        else
     564        {
     565            pSection = pSection->next;
     566        }
     567    }
     568    return pSection;
    531569}
    532570
     
    545583_findKEY (SECTION * pSection, char *pKeyName)
    546584{
    547   KEY *pKey = NULL;
    548   pKey = pSection->fils;
    549   while ((pKey != NULL) && (strcmp (pKey->name, pKeyName) != 0))
    550     {
    551       if (pKey == pKey->next)
    552         {
    553           pKey = NULL;
    554         }
    555       else
    556         {
    557           pKey = pKey->next;
    558         }
    559     }
    560   return pKey;
     585    KEY *pKey = NULL;
     586    pKey = pSection->fils;
     587    while ((pKey != NULL) && (strcmp (pKey->name, pKeyName) != 0))
     588    {
     589        if (pKey == pKey->next)
     590        {
     591            pKey = NULL;
     592        }
     593        else
     594        {
     595            pKey = pKey->next;
     596        }
     597    }
     598    return pKey;
    561599}
    562600
     
    575613_lastKEY (SECTION * pSection)
    576614{
    577   KEY *pKey_pred = NULL;
    578   KEY *pKey = NULL;
    579   pKey = pSection->fils;
    580   pKey_pred = pKey;
    581   while (pKey != NULL)
    582     {
    583       pKey_pred = pKey;
    584       if (pKey == pKey->next)
    585         {
    586           pKey = NULL;
    587         }
    588       else
    589         {
    590           pKey = pKey->next;
    591         }
    592     }
    593   return pKey_pred;
     615    KEY *pKey_pred = NULL;
     616    KEY *pKey = NULL;
     617    pKey = pSection->fils;
     618    pKey_pred = pKey;
     619    while (pKey != NULL)
     620    {
     621        pKey_pred = pKey;
     622        if (pKey == pKey->next)
     623        {
     624            pKey = NULL;
     625        }
     626        else
     627        {
     628            pKey = pKey->next;
     629        }
     630    }
     631    return pKey_pred;
    594632}
    595633
     
    608646_lastSECTION (INI * pIni)
    609647{
    610   SECTION *pSection_pred = NULL;
    611   SECTION *pSection = NULL;
    612   pSection = pIni->fils;
    613   pSection_pred = pSection;
    614   while (pSection != NULL)
    615     {
    616       pSection_pred = pSection;
    617       if (pSection == pSection->next)
    618         {
    619           pSection = NULL;
    620         }
    621       else
    622         {
    623           pSection = pSection->next;
    624         }
    625     }
    626   return pSection_pred;
     648    SECTION *pSection_pred = NULL;
     649    SECTION *pSection = NULL;
     650    pSection = pIni->fils;
     651    pSection_pred = pSection;
     652    while (pSection != NULL)
     653    {
     654        pSection_pred = pSection;
     655        if (pSection == pSection->next)
     656        {
     657            pSection = NULL;
     658        }
     659        else
     660        {
     661            pSection = pSection->next;
     662        }
     663    }
     664    return pSection_pred;
    627665}
    628666
     
    634672 *  la section ne doit pas appartenir a une INI       *
    635673 * ARGUMENTS:                                         *
    636  * la structure INI, la structure SECTION             * 
     674 * la structure INI, la structure SECTION             *
    637675 * ENVIRONNEMENT:                                     *
    638676 * VALEUR RETOURNEE:                                  *
     
    642680_addSECTION (INI * pIni, SECTION * pSection)
    643681{
    644   SECTION *pSection_last = NULL;
    645 
    646   if (pSection->parent != NULL)
    647     {
    648       return NULL;
    649     }
    650   else
    651     {
    652       pSection_last = _lastSECTION (pIni);
    653       pSection->parent = pIni;
    654       if (pSection_last != NULL)
    655         {
    656           pSection_last->next = pSection;
    657           pSection->prev = pSection_last;
    658         }
    659       else
    660         {
    661           pIni->fils = pSection;
    662         }
    663       return pSection;
     682    SECTION *pSection_last = NULL;
     683
     684    if (pSection->parent != NULL)
     685    {
     686        return NULL;
     687    }
     688    else
     689    {
     690        pSection_last = _lastSECTION (pIni);
     691        pSection->parent = pIni;
     692        if (pSection_last != NULL)
     693        {
     694            pSection_last->next = pSection;
     695            pSection->prev = pSection_last;
     696        }
     697        else
     698        {
     699            pIni->fils = pSection;
     700        }
     701        return pSection;
    664702    }
    665703}
     
    680718_addKEY (SECTION * pSection, KEY * pKey)
    681719{
    682   KEY *pKey_last = NULL;
    683 
    684   if (pKey->parent != NULL)
    685     {
    686       return NULL;
    687     }
    688   else
    689     {
    690 
    691       pKey_last = _lastKEY (pSection);
    692       pKey->parent = pSection;
    693       if (pKey_last != NULL)
    694         {
    695           pKey_last->next = pKey;
    696           pKey->prev = pKey_last;
    697         }
    698       else
    699         {
    700           pSection->fils = pKey;
    701         }
    702       pKey->next = pKey;
    703       return pKey;
     720    KEY *pKey_last = NULL;
     721
     722    if (pKey->parent != NULL)
     723    {
     724        return NULL;
     725    }
     726    else
     727    {
     728
     729        pKey_last = _lastKEY (pSection);
     730        pKey->parent = pSection;
     731        if (pKey_last != NULL)
     732        {
     733            pKey_last->next = pKey;
     734            pKey->prev = pKey_last;
     735        }
     736        else
     737        {
     738            pSection->fils = pKey;
     739        }
     740        pKey->next = pKey;
     741        return pKey;
    704742    }
    705743}
     
    717755*  -1 si un probleme a eu lieu, 0 sinon              *
    718756******************************************************/
    719 int
     757
     758/*
     759 * int
    720760_saveINI (INI * pIni)
    721761{
     
    774814      while (pSection != pSection_pred);
    775815    }
    776   /*nettoyage */
     816  //nettoyage
    777817  fclose (pFile);
    778 }
     818}*/
    779819
    780820/******************************************************
     
    795835_loadINI (char *fileName)
    796836{
    797   FILE *pFile = NULL;
    798   char *pBuf;
    799   int nbRead = 0;
    800   SECTION *pSection = NULL;
    801   KEY *pKey = NULL;
    802 
    803   INI *pIni = NULL;
    804   pBuf = (char *) m_malloc (sizeof (char) * MAX_LENGHT);
    805 
    806   pFile = fopen (fileName, "r");
    807   if (pFile == NULL)
    808     {
    809       pFile = fopen (fileName, "a");
    810       if (pFile == NULL)
    811         THROW (ERR_FOPEN);      /*encore NULL !!? la! il y a vraiment un probleme !! */
    812     }
    813 
    814   pIni = (INI *) m_malloc (sizeof (INI));
    815   pIni->fileName = (char *) m_malloc (sizeof (char) * strlen (fileName) + 1);
    816   strcpy (pIni->fileName, fileName);
    817   pIni->fils = NULL;
    818   /* on lit ligne par ligne */
    819   nbRead = readline (pFile, pBuf);
    820   while (nbRead != -1)
    821     {
    822 
    823       if ((pBuf[0] == '[') && (pBuf[strlen (pBuf) - 1] == ']'))
    824         {
    825           /* une section */
    826           pSection = NULL;
    827 
    828           pSection = _newSECTION (pBuf);
    829           _addSECTION (pIni, pSection);
    830         }
    831 
    832       /* les cles de la section */
    833       while (((nbRead = readline (pFile, pBuf)) !=-1) && (pBuf[0] != '['))
    834         {
    835           int ind = 0;
    836           pKey = NULL;
    837           if ((ind = _isKey (pBuf)) >= 0)
    838             {
    839 
    840               char *strName = NULL;
    841               strName = (char *) m_malloc (sizeof (char) * ind + 1);
    842               strncpy (strName, pBuf, ind);
    843               strName[ind] = '\0';
    844               pKey = _newKEY (strName, pBuf + ind + 1);
    845               _addKEY (pSection, pKey);
    846             }
    847         }
    848     }
    849 
    850   /*nettoyage */
    851   free (pBuf);
    852   fclose (pFile);
    853   return pIni;
     837    FILE *pFile = NULL;
     838    char *pBuf;
     839    int nbRead = 0;
     840    SECTION *pSection = NULL;
     841    KEY *pKey = NULL;
     842
     843    INI *pIni = NULL;
     844    pBuf = new char [MAX_LENGHT];
     845
     846    pFile = fopen (fileName, "r");
     847    if (pFile == NULL)
     848    {
     849        pFile = fopen (fileName, "a");
     850        if (pFile == NULL)
     851           
     852        return NULL;
     853    }
     854
     855    pIni = new INI;
     856    pIni->fileName = new char [strlen (fileName) + 1];
     857    strcpy (pIni->fileName, fileName);
     858    pIni->fils = NULL;
     859    /* on lit ligne par ligne */
     860    nbRead = readline (pFile, pBuf);
     861    if (nbRead==-1) { fclose(pFile); delete  [] pIni->fileName; delete pIni; delete [] pBuf; return 0;}
     862    while (nbRead != -1)
     863    {
     864
     865        if ((pBuf[0] == '[') && (pBuf[strlen (pBuf) - 1] == ']'))
     866        {
     867            /* une section */
     868            pSection = NULL;
     869
     870            pSection = _newSECTION (pBuf);
     871            _addSECTION (pIni, pSection);
     872        }
     873
     874        /* les cles de la section */
     875        while (((nbRead = readline (pFile, pBuf)) !=-1) && (pBuf[0] != '['))
     876        {
     877            int ind = 0;
     878            pKey = NULL;
     879            if ((ind = _isKey (pBuf)) >= 0)
     880            {
     881
     882                char *strName = NULL;
     883                strName = new char [ind + 1];
     884                strncpy (strName, pBuf, ind);
     885                strName[ind] = '\0';
     886                pKey = _newKEY (strName, pBuf + ind + 1);
     887                _addKEY (pSection, pKey);
     888                delete [] strName;
     889            }
     890        }
     891    }
     892
     893    /*nettoyage */
     894    delete [] pBuf;
     895    fclose (pFile);
     896    return pIni;
    854897}
    855898
     
    868911_isKey (char *str)
    869912{
    870   int ind = 0;
    871   for (ind; (ind < strlen (str)) && (str[ind] != '='); ind++);
    872   if (str[ind] == '=')
    873     return ind;
    874   else
    875     return -1;
     913    int ind = 0;
     914    for (ind; (ind < strlen (str)) && (str[ind] != '='); ind++);
     915    if (str[ind] == '=')
     916        return ind;
     917    else
     918        return -1;
    876919}
    877920
     
    887930 * VALEUR RETOURNEE:                                  *
    888931 ******************************************************/
    889 void
     932/*void
    890933_printINI (INI * pIni)
    891934{
     
    906949    }
    907950  printf ("\n#Fin du fichier INI#\n");
    908 }
     951}*/
    909952
    910953/******************************************************
     
    918961 * VALEUR RETOURNEE:                                  *
    919962 ******************************************************/
    920 void
     963/*void
    921964_printSECTION (SECTION * pSection)
    922965{
     
    935978      while (pKey != pKey_pred);
    936979    }
    937 }
     980}*/
    938981
    939982/******************************************************
     
    947990 * VALEUR RETOURNEE:                                  *
    948991 ******************************************************/
    949 void
     992/*
     993 * void
    950994_printKEY (KEY * pKey)
    951995{
    952996  printf ("%s=%s\n", pKey->name, pKey->value);
    953 }
     997}*/
    954998
    955999/******************************************************
     
    9631007 * VALEUR RETOURNEE:                                  *
    9641008 ******************************************************/
    965 void
     1009
     1010/*void
    9661011printINI (char *file)
    9671012{
     
    9851030  _printINI (pIni);
    9861031  free (pIni);
    987 }
     1032}*/
    9881033
    9891034/******************************************************
     
    10021047jumpline (int nbline, FILE * pfile)
    10031048{
    1004   int compteur = 0, c;
    1005 
    1006   while ((compteur < nbline) && ((c = getc (pfile)) != EOF))
    1007     {
    1008       if (c == '\n')
    1009         compteur++;
    1010     }
    1011   return (compteur);
     1049    int compteur = 0, c;
     1050
     1051    while ((compteur < nbline) && ((c = getc (pfile)) != EOF))
     1052    {
     1053        if (c == '\n')
     1054            compteur++;
     1055    }
     1056    return (compteur);
    10121057}
    10131058
     
    10271072readline (FILE * pfile, char *tab)
    10281073{
    1029   int nbchar = 0;
    1030   char c;
    1031   while ((c = getc (pfile)) != '\n')
    1032     {
    1033       if (c == EOF)
    1034         {
    1035           break;         
    1036         }
    1037       tab[nbchar++] = c;
    1038     }
    1039   tab[nbchar] = '\0';
    1040  
    1041   while (nbchar>0 && tab[nbchar-1]==' ') { tab[--nbchar] = '\0';}
    1042  
    1043   while (tab[0]==' ') for (int i=1; i<=nbchar; i++) tab[i-1]=tab[i];
    1044  
    1045   if (c == EOF) nbchar=-1;
    1046  
    1047   return (nbchar);
     1074    int nbchar = 0;
     1075    char c;
     1076    while ((c = getc (pfile)) != '\n')
     1077    {
     1078        if (c == EOF)
     1079        {
     1080            break;
     1081        }
     1082        tab[nbchar++] = c;
     1083    }
     1084    tab[nbchar] = '\0';
     1085
     1086    while (nbchar>0 && tab[nbchar-1]==' ') {
     1087        tab[--nbchar] = '\0';
     1088    }
     1089
     1090    while (tab[0]==' ') for (int i=1; i<=nbchar; i++) tab[i-1]=tab[i];
     1091
     1092    if (c == EOF) nbchar=-1;
     1093
     1094    return (nbchar);
    10481095}
    10491096
     
    10561103 * VALEUR RETOURNEE:                                  *
    10571104 ******************************************************/
    1058 void *
    1059 m_malloc (size_t size)
     1105
     1106/*
     1107void * m_malloc (size_t size)
    10601108{
    10611109  void *ptr = malloc (size);
     
    10641112  else
    10651113    return ptr;
    1066 }
     1114}*/
  • BAORadio/libindi/libindi/BAOControl/filetools.h

    r502 r504  
    5757
    5858**********************************************************************************/
    59 
     59int readINI (const char *sectionName, const char *pKeyName, char **ppStr, const char *fileName);
    6060
    6161char *writeINI (char *section, char *key, char *pKeyValue, char *fileName);
  • BAORadio/libindi/libindi/BAOControl/mouvements

    r502 r504  
     1[parametres]
     2mode=tracking
     3J2000=on
     4
    15[objet 1]
    2 date=07/11/2010
    3 heure=14:19:00
     6date=19/06/2011
     7heure=22:52:00
    48duree=30
    59ad=12:25:00
     
    711
    812[objet 2]
    9 date=07/11/2010
    10 heure=14:19:31
     13date=19/06/2011
     14heure=22:53:00
    1115duree=30
    1216ad=00:25:00
    1317de=89:00:00
     18
     19[objet 3]
     20date=19/06/2011
     21heure=22:54:00
     22duree=30
     23ad=00:25:00
     24de=87:00:00
  • BAORadio/libindi/libindi/BAOControl/params

    r502 r504  
    44
    55[coordonnees geographiques]
    6 latitude=48:41:56
    7 longitude=2:10:13
     6latitude=48:51:00
     7longitude=2:19:59
    88
    9 [transit]
    10 delai=100
     9[atmosphere]
     10pression=1013
     11temperature=10
    1112
    12 [tracking]
    13 delai=5
     13[suivi]
     14mode=tracking
     15delai_transit=100
     16delai_tracking=5
     17
     18[divers]
     19couleurs=1
    1420
    1521
  • BAORadio/libindi/libindi/BAOTest/BAOtest_main.cpp

    r498 r504  
    6969    result.y=0;
    7070
    71     if (str.length()>2)
     71    if (str.length() > 2)
    7272    {
    7373        result.x=atoi(str.substr(2, 4).c_str());
     
    203203                            if (Aleat)
    204204                            {
    205                                 sprintf(chaine, "POSITION/%04i/%04i/\n", Pos.x, Pos.y);
     205                                sprintf(chaine, "POSITION/%05i/%05i/\n", Pos.x, Pos.y);
    206206                            }
    207207                            else
  • BAORadio/libindi/libindi/CMakeLists.txt

    r501 r504  
    11cmake_minimum_required(VERSION 2.4.7)
    2 
    3  if(COMMAND cmake_policy)
    4       cmake_policy(SET CMP0003 NEW)
    5     endif(COMMAND cmake_policy)
    6 
    7 
    82
    93##################  INDI version  ################################
    104set(INDI_SOVERSION "0")
    115set(CMAKE_INDI_VERSION_MAJOR 0)
    12 set(CMAKE_INDI_VERSION_MINOR 7)
     6set(CMAKE_INDI_VERSION_MINOR 8)
    137set(CMAKE_INDI_VERSION_RELEASE 0)
    148set(CMAKE_INDI_VERSION_STRING "${CMAKE_INDI_VERSION_MAJOR}.${CMAKE_INDI_VERSION_MINOR}.${CMAKE_INDI_VERSION_RELEASE}")
     
    3832find_package(ZLIB REQUIRED)
    3933
     34FIND_PACKAGE(Boost)
     35IF (BOOST_FOUND)
     36    INCLUDE_DIRECTORIES(${BOOST_INCLUDE_DIR})
     37ENDIF()
     38
     39
    4040macro_optional_find_package(USB)
    41 macro_log_feature(LIBUSB_FOUND "libusb" "User level access to USB devices" "http://indi.sf.net" FALSE "" "Provides support for USB based drivers in INDI.")
     41macro_log_feature(LIBUSB_FOUND "libusb" "User level access to USB devices" "http://www.libusb.org" FALSE "" "Provides support for USB based drivers in INDI.")
    4242
    4343macro_optional_find_package(CFITSIO)
    4444
    4545if (NOT CFITSIO_FOUND OR CFITSIO_VERSION_MAJOR LESS 3)
    46   message(FATAL_ERROR "CFITSIO version too old, Please install cfitsio 3.x and try again. http://indi.sf.net")
     46  message(FATAL_ERROR "CFITSIO version too old, Please install cfitsio 3.x and try again. http://heasarc.gsfc.nasa.gov/fitsio/fitsio.html")
    4747endif (NOT CFITSIO_FOUND OR CFITSIO_VERSION_MAJOR LESS 3)
    4848
     
    5050macro_log_feature(CFITSIO_FOUND "libcfitsio" "A library for reading and writing data files in FITS (Flexible Image Transport System) data format" "http://indi.sf.net" FALSE "3.03" "Provides INDI with FITS I/O support.")
    5151
    52 
    53 macro_optional_find_package(FLI)
    54 macro_log_feature(FLI_FOUND "libfli" "Finger Lakes Instrument Library" "http://indi.sourceforge.net/" FALSE "1.71" "Provides INDI with support for controlling FLI CCDS & Filter Wheels.")
    5552
    5653macro_optional_find_package(Nova)
     
    6158check_include_files(termios.h TERMIOS_FOUND)
    6259macro_bool_to_01(TERMIOS_FOUND HAVE_TERMIOS_H)
     60
     61configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h )
     62
     63if(COMMAND cmake_policy)
     64 cmake_policy(SET CMP0003 NEW)
     65endif(COMMAND cmake_policy)
    6366
    6467include_directories( ${CMAKE_CURRENT_BINARY_DIR})
     
    7477    include_directories(${NOVA_INCLUDE_DIR})
    7578endif (NOVA_FOUND)
    76 
    77 if (FLI_FOUND)
    78     include_directories(${FLI_INCLUDE_DIR})
    79 endif (FLI_FOUND)
    8079
    8180set(liblilxml_SRCS  ${CMAKE_SOURCE_DIR}/libs/lilxml.c )
     
    10099    )
    101100
    102 set (indibase_SRCS
     101set (indiclient_SRCS
    103102        ${CMAKE_SOURCE_DIR}/libs/indibase/basedriver.cpp
    104103        ${CMAKE_SOURCE_DIR}/libs/indibase/baseclient.cpp
    105104    )
    106105
    107 set (indidefaultdevice_SRCS
     106set (indidriver_SRCS
    108107        ${CMAKE_SOURCE_DIR}/libs/indibase/basedriver.cpp
    109108        ${CMAKE_SOURCE_DIR}/libs/indibase/defaultdriver.cpp
     109        ${CMAKE_SOURCE_DIR}/libs/indibase/indiccd.cpp
     110        ${CMAKE_SOURCE_DIR}/libs/indibase/inditelescope.cpp
     111        ${CMAKE_SOURCE_DIR}/libs/indibase/indifilterwheel.cpp
     112        ${CMAKE_SOURCE_DIR}/libs/indibase/indifocuser.cpp
     113        ${CMAKE_SOURCE_DIR}/libs/indibase/indiusbdevice.cpp
    110114    )
    111115
     
    127131install(TARGETS indiserver RUNTIME DESTINATION bin )
    128132
    129 
    130 ######################################
    131 ######## INDI Shared Library #########
    132 ######################################
     133#################################################
     134############# INDI Shared Library ###############
     135# To offer lilxml and communination routines    #
     136# Mostly used by generic clients                #
     137#################################################
    133138add_library(indi SHARED ${libindicom_SRCS} ${liblilxml_SRCS})
    134139target_link_libraries(indi m z)
     
    140145target_link_libraries(indi ${CFITSIO_LIBRARIES})
    141146endif(CFITSIO_FOUND)
    142 if (FLI_FOUND)
    143 target_link_libraries(indi ${FLI_LIBRARIES})
    144 endif(FLI_FOUND)
    145147
    146148install(TARGETS indi LIBRARY DESTINATION lib${LIB_POSTFIX})
    147149set_target_properties(indi PROPERTIES VERSION ${CMAKE_INDI_VERSION_STRING} SOVERSION ${INDI_SOVERSION})
    148150
    149 
    150 ######################################
    151 ######## INDI Static Library #########
    152 ######################################
    153 add_library(indidriver STATIC ${indimain_SRCS})
     151##################################################
     152############ INDI Main Static Library ############
     153# To link with main() for 3rd party drivers      #
     154##################################################
     155add_library(indimain STATIC ${indimain_SRCS})
     156install(TARGETS indimain ARCHIVE DESTINATION lib${LIB_POSTFIX})
     157
     158##################################################
     159###### INDI Default Driver Static Library ########
     160# To link with main() and indibase classes       #
     161##################################################
     162add_library(indidriver STATIC ${indimain_SRCS} ${indidriver_SRCS})
    154163install(TARGETS indidriver ARCHIVE DESTINATION lib${LIB_POSTFIX})
    155164
    156 ##############################################
    157 ######## INDI Default Driver Library #########
    158 ##############################################
    159 add_library(indidefaultdriver STATIC ${indimain_SRCS} ${indidefaultdevice_SRCS})
    160 install(TARGETS indidefaultdriver ARCHIVE DESTINATION lib${LIB_POSTFIX})
    161 
    162 ##############################################
    163 ######## INDI Client Library #########
    164 ##############################################
    165 add_library(indiclient STATIC ${indibase_SRCS})
    166 target_link_libraries(indiclient indi)
     165##################################################
     166########### INDI Client Static Library ###########
     167##################################################
     168add_library(indiclient STATIC ${indiclient_SRCS})
     169target_link_libraries(indiclient indi pthread)
    167170install(TARGETS indiclient ARCHIVE DESTINATION lib${LIB_POSTFIX})
    168171
     
    324327install(TARGETS indi_BAO RUNTIME DESTINATION bin )
    325328
     329########### Syncscan ###############
     330set(synscan_SRCS
     331   ${indimain_SRCS}
     332   ${CMAKE_SOURCE_DIR}/drivers/telescope/synscanmount.cpp )
     333
     334add_executable(indi_synscan ${synscan_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     335
     336target_link_libraries(indi_synscan indidriver m z)
     337
     338if (NOVA_FOUND)
     339  target_link_libraries(indi_synscan ${NOVA_LIBRARIES})
     340endif (NOVA_FOUND)
     341
     342install(TARGETS indi_synscan RUNTIME DESTINATION bin )
     343
     344########### Telescope Simulator ##############
     345set(telescopesimulator_SRCS
     346        ${indimain_SRCS}
     347        ${CMAKE_SOURCE_DIR}/drivers/telescope/telescope_simulator.cpp
     348   )
     349
     350add_executable(indi_simulator_telescope ${telescopesimulator_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     351
     352target_link_libraries(indi_simulator_telescope indidriver ${CFITSIO_LIBRARIES} m z pthread)
     353
     354if (NOVA_FOUND)
     355  target_link_libraries(indi_simulator_telescope ${NOVA_LIBRARIES})
     356endif (NOVA_FOUND)
     357
     358install(TARGETS indi_simulator_telescope RUNTIME DESTINATION bin )
     359
    326360#####################################
    327361########## FOCUSER GROUP ############
    328362#####################################
    329363
    330 ###### FLI Precision Digital Focuser ######
    331 if (FLI_FOUND)
    332 set(flipdf_SRCS
    333         ${indimain_SRCS}
    334         ${CMAKE_SOURCE_DIR}/drivers/focuser/fli_pdf.c
    335 )
    336 
    337 add_executable(indi_fli_pdf ${flipdf_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
    338 
    339 target_link_libraries(indi_fli_pdf m ${FLI_LIBRARIES})
    340 
    341 if (NOVA_FOUND)
    342   target_link_libraries(indi_fli_pdf ${NOVA_LIBRARIES})
    343 endif (NOVA_FOUND)
    344 
    345 install(TARGETS indi_fli_pdf RUNTIME DESTINATION bin )
    346 endif(FLI_FOUND)
     364########### CCD Simulator ##############
     365if (CFITSIO_FOUND)
     366
     367set(ccdsimulator_SRCS
     368        ${indimain_SRCS}
     369        ${CMAKE_SOURCE_DIR}/drivers/ccd/ccd_simulator.cpp
     370   )
     371
     372add_executable(indi_simulator_ccd ${ccdsimulator_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     373
     374target_link_libraries(indi_simulator_ccd indidriver ${CFITSIO_LIBRARIES} m z pthread)
     375
     376if (NOVA_FOUND)
     377  target_link_libraries(indi_simulator_ccd ${NOVA_LIBRARIES})
     378endif (NOVA_FOUND)
     379
     380install(TARGETS indi_simulator_ccd RUNTIME DESTINATION bin )
     381
     382endif (CFITSIO_FOUND)
     383
     384
     385#####################################
     386########## FOCUSER GROUP ############
     387#####################################
     388
    347389#################################################################################
    348390
     
    355397   )
    356398
    357 add_executable(indi_robofocus ${robofocus_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
    358 
    359 target_link_libraries(indi_robofocus m)
    360 
    361 if (NOVA_FOUND)
    362   target_link_libraries(indi_robofocus ${NOVA_LIBRARIES})
    363 endif (NOVA_FOUND)
    364 
    365 install(TARGETS indi_robofocus RUNTIME DESTINATION bin )
     399add_executable(indi_robo_focus ${robofocus_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     400
     401target_link_libraries(indi_robo_focus m)
     402
     403if (NOVA_FOUND)
     404  target_link_libraries(indi_robo_focus ${NOVA_LIBRARIES})
     405endif (NOVA_FOUND)
     406
     407install(TARGETS indi_robo_focus RUNTIME DESTINATION bin )
     408
     409################ Optec TCF-S ################
     410
     411set(tcfs_SRCS
     412        ${indimain_SRCS}
     413        ${CMAKE_SOURCE_DIR}/drivers/focuser/tcfs.cpp
     414   )
     415
     416add_executable(indi_tcfs_focus ${tcfs_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     417
     418target_link_libraries(indi_tcfs_focus indidriver m z)
     419
     420if (NOVA_FOUND)
     421  target_link_libraries(indi_tcfs_focus ${NOVA_LIBRARIES})
     422endif (NOVA_FOUND)
     423
     424install(TARGETS indi_tcfs_focus RUNTIME DESTINATION bin )
     425
     426file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/make_tcfs_symlink.cmake
     427"exec_program(${CMAKE_COMMAND} ARGS -E create_symlink ${BIN_INSTALL_DIR}/indi_tcfs_focus ${BUILD_ROOT}${BIN_INSTALL_DIR}/indi_tcfs3_focus)\n")
     428set_target_properties(indi_tcfs_focus PROPERTIES POST_INSTALL_SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/make_tcfs_symlink.cmake)
    366429
    367430#################################################################################
     
    387450install(TARGETS indi_trutech_wheel RUNTIME DESTINATION bin )
    388451
    389 #################################################################################
    390 
    391 ########## FLI Filter Wheel ############
    392 if (FLI_FOUND)
    393 set(fliwheel_SRCS
    394         ${indimain_SRCS}
    395         ${CMAKE_SOURCE_DIR}/drivers/filter_wheel/fli_wheel.c
    396    )
    397 
    398 add_executable(indi_fli_wheel ${fliwheel_SRCS}  ${liblilxml_SRCS} ${libindicom_SRCS})
    399 
    400 target_link_libraries(indi_fli_wheel ${FLI_LIBRARIES} m)
    401 
    402 if (NOVA_FOUND)
    403   target_link_libraries(indi_fli_wheel ${NOVA_LIBRARIES})
    404 endif (NOVA_FOUND)
    405 
    406 install(TARGETS indi_fli_wheel RUNTIME DESTINATION bin )
    407 endif (FLI_FOUND)
    408 #################################################################################
    409 
    410 #######################################
    411 ############# CCD GROUP ###############
    412 #######################################
    413 
    414 ############# FLI CCD ###############
    415 if (CFITSIO_FOUND AND FLI_FOUND)
    416 
    417 set(fliccd_SRCS
    418         ${indimain_SRCS}
    419         ${CMAKE_SOURCE_DIR}/drivers/ccd/fli_ccd.c
    420 )
    421 
    422 add_executable(indi_fli_ccd ${fliccd_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
    423 
    424 target_link_libraries(indi_fli_ccd ${FLI_LIBRARIES} ${CFITSIO_LIBRARIES} m z)
    425 
    426 if (NOVA_FOUND)
    427   target_link_libraries(indi_fli_ccd ${NOVA_LIBRARIES})
    428 endif (NOVA_FOUND)
    429 
    430 install(TARGETS indi_fli_ccd RUNTIME DESTINATION bin )
    431 
    432 endif (CFITSIO_FOUND AND FLI_FOUND)
     452########### Filter Simulator ##############
     453set(filtersimulator_SRCS
     454        ${indimain_SRCS}
     455        ${CMAKE_SOURCE_DIR}/drivers/filter_wheel/filter_simulator.cpp
     456   )
     457
     458add_executable(indi_simulator_wheel ${filtersimulator_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     459
     460target_link_libraries(indi_simulator_wheel indidriver ${CFITSIO_LIBRARIES} m z pthread)
     461
     462if (NOVA_FOUND)
     463  target_link_libraries(indi_simulator_wheel ${NOVA_LIBRARIES})
     464endif (NOVA_FOUND)
     465
     466install(TARGETS indi_simulator_wheel RUNTIME DESTINATION bin )
     467
    433468#################################################################################
    434469
     
    458493
    459494### Meade Lunar Planetary Imager ########
     495if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    460496if (CFITSIO_FOUND)
    461497
     
    479515
    480516endif (CFITSIO_FOUND)
     517endif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    481518
    482519#################################################################################
    483520
    484521########### V4L Philips ##############
     522if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    485523if (CFITSIO_FOUND)
    486524
     
    503541
    504542endif (CFITSIO_FOUND)
     543endif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    505544
    506545#################################################################################
    507546
    508547########### Generic V4L Driver ###############
     548if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    509549if (CFITSIO_FOUND)
    510550
     
    526566
    527567endif (CFITSIO_FOUND)
     568endif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    528569
    529570#################################################################################
     
    630671
    631672########### Tutorial four ##############
     673if (CFITSIO_FOUND)
     674
    632675set(tutorialfour_SRCS
    633676        ${indimain_SRCS}
     
    637680add_executable(tutorial_four ${tutorialfour_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
    638681
    639 target_link_libraries(tutorial_four indidefaultdriver indiclient m z pthread)
     682target_link_libraries(tutorial_four indidriver ${CFITSIO_LIBRARIES} m z pthread)
    640683
    641684if (NOVA_FOUND)
     
    643686endif (NOVA_FOUND)
    644687
     688endif (CFITSIO_FOUND)
    645689
    646690########### Tutorial dome ##############
     
    672716endif (NOVA_FOUND)
    673717
    674 #################################################################################
    675 
    676 install( FILES drivers.xml DESTINATION ${DATA_INSTALL_DIR})
     718
     719########### Client Tutorial ##############
     720set(tutorialclient_SRCS
     721        ${CMAKE_SOURCE_DIR}/examples/tutorial_client.cpp
     722   )
     723
     724add_executable(tutorial_client ${tutorialclient_SRCS} ${liblilxml_SRCS} ${libindicom_SRCS})
     725
     726target_link_libraries(tutorial_client indiclient m)
     727
     728if (NOVA_FOUND)
     729  target_link_libraries(tutorial_client ${NOVA_LIBRARIES})
     730endif (NOVA_FOUND)
     731
     732#################################################################################
     733
     734install( FILES drivers.xml ${CMAKE_SOURCE_DIR}/drivers/focuser/indi_tcfs_sk.xml DESTINATION ${DATA_INSTALL_DIR})
    677735
    678736install( FILES indiapi.h indidevapi.h base64.h eventloop.h indidriver.h ${CMAKE_SOURCE_DIR}/libs/lilxml.h ${CMAKE_SOURCE_DIR}/libs/indibase/indibase.h
    679737${CMAKE_SOURCE_DIR}/libs/indibase/basedriver.h  ${CMAKE_SOURCE_DIR}/libs/indibase/defaultdriver.h
     738${CMAKE_SOURCE_DIR}/libs/indibase/indiccd.h  ${CMAKE_SOURCE_DIR}/libs/indibase/indifilterwheel.h
     739${CMAKE_SOURCE_DIR}/libs/indibase/indifocuser.h  ${CMAKE_SOURCE_DIR}/libs/indibase/inditelescope.h
    680740${CMAKE_SOURCE_DIR}/libs/indibase/baseclient.h ${CMAKE_SOURCE_DIR}/libs/indicom.h
     741${CMAKE_SOURCE_DIR}/libs/indibase/indiusbdevice.h
    681742 DESTINATION ${INCLUDE_INSTALL_DIR}/libindi COMPONENT Devel)
    682743
    683744configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libindi.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/libindi.pc @ONLY)
    684745install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libindi.pc DESTINATION ${PKGCONFIG_INSTALL_PREFIX})
    685 
  • BAORadio/libindi/libindi/ChangeLog

    r501 r504  
     1From 0.7.2 to 0.8
     2
     3      # TCF-S Focuser driver.
     4      # Synscan Telescope driver.
     5
     6From 0.7.0 to 0.7.1
     7
     8      # Fixed change filter bug in true technology filter wheel. (JM)
     9      # setINDI updated and improved. (ED)
     10      # Improved INDI::Mediator functionality. (JM)
     11      # Fixed buffer reading in INDI::BaseClient. (JM)
     12      # Add new tutorial for INDI::BaseClient. (JM).
     13
    114From 0.6.2 to 0.7.0
    215
  • BAORadio/libindi/libindi/INSTALL

    r501 r504  
    1 INDI Library Setup 0.7.0
     1INDI Library Setup 0.8.0
    22========================
    33
     
    2222+ cfitsio >= 3.0
    2323
    24 You can download packages for the dependencies above from SUSE BuildService:
    25 
    26 http://software.opensuse.org/search
    27 
    28 The packages are available for all major distributions.
  • BAORadio/libindi/libindi/README

    r501 r504  
    1 libindi v0.6.2
    2 ==============
     1libindi v0.8
     2============
    33
    44The code here demonstrates the use of INDI, an Instrument-Neutral Device
     
    103103        more stuff
    104104
    105 ! For RCS Only -- Do Not Edit
    106 ! @(#) $RCSfile$ $Date: 2004-02-03 09:34:32 +0300 (Tue, 03 Feb 2004) $ $Revision: 284704 $ $Name:  $
     105
  • BAORadio/libindi/libindi/README.drivers

    r490 r504  
    1010You can find more up to date information on INDI drivers from the following sources:
    1111
    12 1. INDI Device Profiles: http://indi.sf.net/devices.html
    13 2. INDI Wiki: http://wiki.kde.org/tiki-index.php?page=indi
     121. INDI Device Profiles: http://www.indilib.org
     132. INDI Wiki: http://www.indilib.org
    1414
    1515
  • BAORadio/libindi/libindi/cmake_modules/FindFLI.cmake

    r490 r504  
    4545  else (FLI_FOUND)
    4646    if (FLI_FIND_REQUIRED)
    47       message(FATAL_ERROR "FLI not found. Please install libfli1-devel. http://indi.sf.net")
     47      message(FATAL_ERROR "FLI not found. Please install libfli-dev. http://www.indilib.org")
    4848    endif (FLI_FIND_REQUIRED)
    4949  endif (FLI_FOUND)
  • BAORadio/libindi/libindi/cmake_modules/FindINDI.cmake

    r501 r504  
    55#  INDI_INCLUDE_DIR - the INDI include directory
    66#  INDI_LIBRARIES - Link these to use INDI
    7 #  INDI_DEVICE_LIBRARY - The indi default device library
     7#  INDI_MAIN_LIBRARIES - Link to these to build INDI drivers with main()
     8#  INDI_DRIVER_LIBRARIES - Link to these to build INDI drivers with indibase support
     9#  INDI_CLIENT_LIBRARIES - Link to these to build INDI clients
    810#  INDI_DATA_DIR - INDI shared data dir.
    911
    10 # Copyright (c) 2010, Jasem Mutlaq <mutlaqja@ikarustech.com>
     12# Copyright (c) 2011, Jasem Mutlaq <mutlaqja@ikarustech.com>
    1113# Based on FindLibfacile by Carsten Niehaus, <cniehaus@gmx.de>
    1214#
     
    1416# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
    1517
    16 if (INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     18if (INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
    1719
    1820  # in cache already
     
    2123
    2224
    23 else (INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     25else (INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
    2426
    2527  find_path(INDI_INCLUDE_DIR indidevapi.h
     
    3032
    3133 find_path(INDI_DATA_DIR drivers.xml
     34    PATHS /usr/share /usr/local/share /opt ${GNUWIN32_DIR}/share
    3235    PATH_SUFFIXES indi
    33     /usr
    34     /usr/local
    35     /opt
    36     ${GNUWIN32_DIR}/share
     36  )
     37
     38  find_library(INDI_LIBRARIES NAMES indi
     39    PATHS
     40    ${_obLinkDir}
     41    ${GNUWIN32_DIR}/lib
    3742  )
    3843
     
    4348  )
    4449
    45   find_library(INDI_DEVICE_LIBRARIES NAMES indidefaultdevice
     50  find_library(INDI_MAIN_LIBRARIES NAMES indimain
    4651    PATHS
    4752    ${_obLinkDir}
     
    4954  )
    5055
    51 
    52   find_library(INDI_LIBRARIES NAMES indi
     56  find_library(INDI_CLIENT_LIBRARIES NAMES indiclient
    5357    PATHS
    5458    ${_obLinkDir}
     
    5660  )
    5761
    58   if(INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     62  if(INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
    5963    set(INDI_FOUND TRUE)
    60   else (INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     64  else (INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
    6165    set(INDI_FOUND FALSE)
    62   endif(INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     66  endif(INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
    6367
    6468
    6569  if (INDI_FOUND)
    6670    if (NOT INDI_FIND_QUIETLY)
    67       message(STATUS "Found INDI: ${INDI_LIBRARIES}, ${INDI_DRIVER_LIBRARIES}")
     71      message(STATUS "Found INDI: ${INDI_LIBRARIES}, ${INDI_MAIN_LIBRARIES}")
     72      message(STATUS "INDI Include: ${INDI_INCLUDE_DIR}, INDI Data: ${INDI_DATA_DIR}")
    6873    endif (NOT INDI_FIND_QUIETLY)
    6974  else (INDI_FOUND)
    7075    if (INDI_FIND_REQUIRED)
    71       message(FATAL_ERROR "indi-devel not found. Cannot compile INDI drivers. Please install indi-devel and try again. http://www.indilib.org")
     76      message(FATAL_ERROR "indi-dev not found. Cannot compile INDI drivers. Please install indi-dev and try again. http://www.indilib.org")
    7277    endif (INDI_FIND_REQUIRED)
    7378  endif (INDI_FOUND)
    7479
    75   mark_as_advanced(INDI_INCLUDE_DIR INDI_LIBRARIES INDI_DRIVER_LIBRARIES INDI_DEVICE_LIBRARIES INDI_DATA_DIR)
     80  mark_as_advanced(INDI_INCLUDE_DIR INDI_DATA_DIR INDI_LIBRARIES INDI_DRIVER_LIBRARIES INDI_MAIN_LIBRARIES INDI_CLIENT_LIBRARIES)
    7681
    77 endif (INDI_INCLUDE_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES)
     82endif (INDI_INCLUDE_DIR AND INDI_DATA_DIR AND INDI_LIBRARIES AND INDI_DRIVER_LIBRARIES AND INDI_MAIN_LIBRARIES)
  • BAORadio/libindi/libindi/config.h.cmake

    r490 r504  
    1313/* Define if you have libnova.h */
    1414#cmakedefine   HAVE_NOVA_H 1
     15
  • BAORadio/libindi/libindi/drivers.xml

    r490 r504  
    11<devGroup group="Telescopes">
     2        <device label="BAO" focal_length="" aperture="">
     3                <driver name="BAO">indi_BAO</driver>
     4                <version>1.0</version>
     5        </device>
    26        <device label="LX200 Basic" focal_length="" aperture="">
    37                <driver name="LX200 Basic">indi_lx200basic</driver>
    4                 <version>1.0</version>
    5         </device>
    6         <device label="BAO" focal_length="" aperture="">
    7                 <driver name="BAO">indi_BAO</driver>
    88                <version>1.0</version>
    99        </device>
     
    9292                <version>0.2</version>
    9393        </device>
     94        <device label="SynScan" focal_length="" aperture="">
     95                <driver name="SynScan">indi_synscan</driver>
     96                <version>1.0</version>
     97        </device>
     98        <device label="EQ6" focal_length="" aperture="">
     99                <driver name="SynScan">indi_synscan</driver>
     100                <version>1.0</version>
     101        </device>
     102        <device label="HEQ5" focal_length="" aperture="">
     103                <driver name="SynScan">indi_synscan</driver>
     104                <version>1.0</version>
     105        </device>
     106        <device label="NEQ3" focal_length="" aperture="">
     107                <driver name="SynScan">indi_synscan</driver>
     108                <version>1.0</version>
     109        </device>
     110        <device label="Telescope Simulator" focal_length="" aperture="">
     111                <driver name="Telescope Simulator">indi_simulator_telescope</driver>
     112                <version>1.0</version>
     113        </device>
     114</devGroup>
     115<devGroup group="Focusers">
     116        <device label="Robo Focus">
     117                <driver name="Robofocus">indi_robo_focus</driver>
     118                <version>0.1</version>
     119        </device>
     120        <device label="Optec TCF-S">
     121                <driver name="Optec TCF-S">indi_tcfs_focus</driver>
     122                <version>0.1</version>
     123        </device>
     124        <device label="Optec TCF-S3">
     125                <driver name="Optec TCF-S">indi_tcfs3_focus</driver>
     126                <version>0.1</version>
     127        </device>
    94128</devGroup>
    95129<devGroup group="CCDs">
    96         <device label="FLI CCD">
    97                 <driver name="FLI CCD">indi_fli_ccd</driver>
    98                 <version>1.0</version>
    99         </device>
    100 </devGroup>
    101 <devGroup group="Focusers">
    102         <device label="FLI PDF">
    103                 <driver name="FLI PDF">indi_fli_pdf</driver>
    104                 <version>0.1</version>
    105         </device>
    106         <device label="Robo Focus">
    107                 <driver name="Robofocus">indi_robofocus</driver>
    108                 <version>0.1</version>
    109         </device>
     130        <device label="CCD Simulator">
     131                <driver name="CCD Simulator">indi_simulator_ccd</driver>
     132                <version>0.1</version>
     133        </device>
    110134</devGroup>
    111135<devGroup group="Filter Wheels">
     
    118142                <version>0.1</version>
    119143        </device>
     144        <device label="Filter Simulator">
     145                <driver name="Filter Simulator">indi_simulator_wheel</driver>
     146                <version>0.1</version>
     147        </device>
    120148</devGroup>
    121149<devGroup group="Video">
  • BAORadio/libindi/libindi/drivers/filter_wheel/trutech_wheel.c

    r501 r504  
    168168                unsigned char type = 0x03;
    169169                unsigned char chksum = COMM_INIT + type + COMM_FILL;
    170                 /*char filter_command[5] = { COMM_PRE, COMM_INIT, type, COMM_FILL, chksum };*/
    171170                unsigned char filter_command[CMD_SIZE];
    172                 snprintf(filter_command, CMD_SIZE,  "%c%c%c%c%c", COMM_PRE, COMM_INIT, type, COMM_FILL, chksum);
     171                //snprintf(filter_command, CMD_SIZE,  "%c%c%c%c%c", COMM_PRE, COMM_INIT, type, COMM_FILL, chksum);
     172                snprintf(filter_command, CMD_SIZE,  "%c%c%c%c", COMM_INIT, type, COMM_FILL, chksum);
    173173
    174174                if (checkPowerS(&HomeSP))
     
    181181                if (DEBUG_ON)
    182182                {
    183                     IDLog("Home Search Command (int): #%d#%d#%d#%d#%d#\n",COMM_PRE, COMM_INIT, type, COMM_FILL, chksum);
    184                     IDLog("Home Search Command (char): #%c#%c#%c#%c#%c#\n",COMM_PRE, COMM_INIT, type, COMM_FILL, chksum);
     183                    IDLog("Home Search Command (int): #%d#%d#%d#%d#\n",COMM_INIT, type, COMM_FILL, chksum);
     184                    IDLog("Home Search Command (char): #%c#%c#%c#%c#\n",COMM_INIT, type, COMM_FILL, chksum);
    185185                }
    186186
     
    273273                        IUUpdateNumber(&FilterPositionNP, values, names, n);
    274274
    275                         snprintf(filter_command, CMD_SIZE,  "%c%c%c%c%c", COMM_PRE, COMM_INIT, type, targetFilter, chksum);
     275                        //snprintf(filter_command, CMD_SIZE,  "%c%c%c%c%c", COMM_PRE, COMM_INIT, type, targetFilter, chksum);
     276                        snprintf(filter_command, CMD_SIZE,  "%c%c%c%c", COMM_INIT, type, targetFilter, chksum);
    276277
    277278                        if (DEBUG_ON)
    278279                        {
    279                             IDLog("Filter Position Command (int): #%d#%d#%d#%d#%d#\n",COMM_PRE, COMM_INIT, type, targetFilter, chksum);
    280                             IDLog("Filter Position Command (char): #%c#%c#%c#%c#%c#\n",COMM_PRE, COMM_INIT, type, targetFilter, chksum);
     280                            IDLog("Filter Position Command (int): #%d#%d#%d#%d#\n", COMM_INIT, type, targetFilter, chksum);
     281                            IDLog("Filter Position Command (char): #%c#%c#%c#%c#\n", COMM_INIT, type, targetFilter, chksum);
    281282                        }
    282283
  • BAORadio/libindi/libindi/drivers/telescope/BAO.cpp

    r501 r504  
    1 #if 0
    2 
     1/*
    32#############################
    43##
    54## BAORadio Indi driver
    65## Franck RICHARD
    7 ## Mai 2010
     6## franckrichard033@gmail.com
     7## Juin 2011
    88##
    99#############################
    10 #endif
    11 
    12 #include <stdio.h>
    13 #include <stdlib.h>
    14 #include <string.h>
    15 #include <stdarg.h>
    16 #include <math.h>
    17 #include <unistd.h>
    18 #include <time.h>
    19 #include <memory>
    20 #include <pthread.h>
    21 #include <iostream>
    22 #include <time.h>
    23 #include <unistd.h>
    24 #include <sys/time.h>
    25 
    26 #include <config.h>
    27 
    28 #include "indicom.h"
    29 
    30 #include "Socket.h"
     10*/
    3111
    3212#include "BAO.h"
    3313
    34 using namespace std;
    3514
    3615auto_ptr<BAO> telescope(0);
    3716
    38 const int POLLMS = 1;                           // Period of update, 1 ms.
    39 
    40 const char *mydev = "BAO";                      // Name of our device.
     17const int POLLMS = 1;                                   // Period of update, 1 ms.
     18
     19const char *mydev = "BAO";                              // Name of our device.
    4120
    4221const char *BASIC_GROUP    = "Main Control";            // Main Group
     
    5231static void ISPoll(void *);
    5332
    54 static void retry_connection(void *);
    55 
    56 /**************************************************************************************
    57 **
    58 ***************************************************************************************/
    59 void *pThreadSocket (void * arg)
    60 {
    61     try
    62     {
    63         int pos = SocketsNumber;
    64 
    65         // Trouver éventuellement un emplacement disponible dans l'intervalle [1..SocketsNumber]
    66 
    67         /*
    68         for (int i=1; i<SocketsNumber; i++)
    69         {
    70         if (!Sockets[i].Connected)
    71         {
    72         pos = i;
    73         break;
    74         }
    75         }*/
    76 
    77         server.accept ( Sockets[pos].new_sock );
    78 
    79         Sockets[pos].IP=server.recupip(Sockets[pos].new_sock);
    80 
    81         Sockets[pos].Connected=true;
    82 
    83         if (pos == SocketsNumber ) SocketsNumber++;
    84 
    85         InitThreadOK=true;
    86     }
    87     catch ( SocketException& e )
    88     {
    89         //A activer pour vérif
    90 
    91         /*std::string oss;
    92         oss="pThreadSocket exception : " + e.description() + "\n";
    93         size_t size = oss.size() + 1;
    94         char* buffer = new char[size];
    95         strncpy(buffer, oss.c_str(), size);
    96 
    97         IDLog(buffer);
    98 
    99         delete [] buffer;*/
    100     }
    101 
    102     return NULL;
    103 }
    104 
    105 
    106 /**************************************************************************************
    107 ** Utilisation d'un thread pour éviter de bloquer l'execution du pilote
    108 ** avec la commande accept
    109 ***************************************************************************************/
    110 
    111 void BAO::InitThread()
    112 {
    113     if (pthread_create (&th1, NULL, pThreadSocket, NULL) < 0)
    114     {
    115         IDLog("pthread_create error for threadSocket\n");
    116     }
    117 
    118     pthread_join (th1, NULL);
    119 }
    120 
    121 /**************************************************************************************
    122 ** Initialisation du pilote BAO
    123 ***************************************************************************************/
    124 void ISInit()
    125 {
    126     static int isInit=0;
    127 
    128     if (isInit) return;
    129 
    130     if (telescope.get() == 0) telescope.reset(new BAO());
    131 
    132     isInit = 1;
    133 
    134     IEAddTimer (POLLMS, ISPoll, NULL);
    135 }
    136 
    137 /**************************************************************************************
    138 **
    139 ***************************************************************************************/
    140 void ISGetProperties (const char *dev)
    141 {
    142     ISInit();
    143     telescope->ISGetProperties(dev);
    144 }
    145 
    146 /**************************************************************************************
    147 **
    148 ***************************************************************************************/
    149 void ISNewSwitch (const char *dev, const char *name, ISState *states, char *names[], int n)
    150 {
    151     ISInit();
    152     telescope->ISNewSwitch(dev, name, states, names, n);
    153 }
    154 
    155 /**************************************************************************************
    156 **
    157 ***************************************************************************************/
    158 void ISNewText (const char *dev, const char *name, char *texts[], char *names[], int n)
    159 {
    160     ISInit();
    161     telescope->ISNewText(dev, name, texts, names, n);
    162 }
    163 
    164 /**************************************************************************************
    165 **
    166 ***************************************************************************************/
    167 void ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n)
    168 {
    169     ISInit();
    170     telescope->ISNewNumber(dev, name, values, names, n);
    171 }
    172 
    173 /**************************************************************************************
    174 **
    175 ***************************************************************************************/
    176 void ISPoll (void *p)
    177 {
    178     INDI_UNUSED(p);
    179 
    180     telescope->ISPoll();
    181     IEAddTimer (POLLMS, ISPoll, NULL);
    182 }
    183 
    184 
    185 /**************************************************************************************
    186 **
    187 ***************************************************************************************/
    188 void ISNewBLOB (const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[], char *names[], int n)
    189 {
    190     INDI_UNUSED(dev);
    191     INDI_UNUSED(name);
    192     INDI_UNUSED(sizes);
    193     INDI_UNUSED(blobsizes);
    194     INDI_UNUSED(blobs);
    195     INDI_UNUSED(formats);
    196     INDI_UNUSED(names);
    197     INDI_UNUSED(n);
    198 }
    199 
    200 /**************************************************************************************
    201 **
    202 ***************************************************************************************/
    203 void ISSnoopDevice (XMLEle *root)
    204 {
    205     INDI_UNUSED(root);
    206 }
     33void* LancementThread(BAO * appli);
     34
    20735
    20836/**************************************************************************************
    20937** Initialisation de la classe BAO
    21038***************************************************************************************/
     39
    21140BAO::BAO()
    21241{
    21342    init_properties();
    21443
    215     ConnectSP.s = IPS_IDLE;
    216 
     44    // télescope en état IDLE
     45    ConnectSP.s    = IPS_IDLE;
     46
     47    // derniÚre actualisation
     48    lastRA         = 0.0;
     49    lastDEC        = 0.0;
     50    JJAnc          = 0.0;
     51
     52    currentSet     =  0;
    21753    lastSet        = -1;
    218     fd             = -1;
    219     simulation     = false;
    220     lastRA         = 0;
    221     lastDEC        = 0;
    222     currentSet     = 0;
    223     JJAnc          = 0.0;
    224 
    225     SocketsNumber  = 1;
    226 
    227     ActualisationTM1 = 15.0*60.0;
    228 
     54    SocketsNumber  =  1;
     55    TrackingMode   =  1;
     56
     57    // délais en sec entre deux actualisations de la
     58    // position dans les modes transit et tracking
     59
     60    ActualisationTM1 = 15.0 * 60.0;
    22961    ActualisationTM2 = 5.0;
    23062
    231     InitThreadOK=false;
    232     LecturePosition=false;
    233     Abort=false;
    234     Park=false;
    235     Goto=false;
    236     LastGotoOK=true;
    237 
    238     TrackingMode=1;
    239 
     63    UpdateGoto      = true;
     64    InitThreadOK    = false;
     65    ActualisationPosition = false;
     66    Abort           = false;
     67    Park            = false;
     68    Suivi            = false;
     69    Exit            = false;
     70
     71
     72    // initialisation des sockets (Antennes)
    24073    for (int i=0; i<MAXHOSTNAME; i++)
    24174    {
     
    24477    }
    24578
     79    // initialisations supplémentaires
    24680    InitAntennes();
    24781
    248 
     82    // Numéro de version
    24983    IDLog("Initilizing from BAO device...\n");
    250     IDLog("Driver Version: 2010-11-10\n");
    251 
    252     //enableSimulation(true);
    253 }
    254 
    255 /**************************************************************************************
    256 **
     84    IDLog("Driver Version: 2011-06-27\n");
     85
     86    //connect_telescope();
     87}
     88
     89
     90/**************************************************************************************
     91** Destructeur
     92** Lorsque l'on lance indi_BAO depuis indiserver dans un terminal
     93** Le destructeur ne semble jamais être atteint lorsque l'on sort...
    25794***************************************************************************************/
    25895BAO::~BAO()
    25996{
    260 
    261 }
     97    Exit=true;
     98    sleep(1);
     99    pthread_join (th1, NULL);
     100}
     101
     102
    262103
    263104/**************************************************************************************
    264105** Initialisation des boutons et des zones d'affichage dans la boîte de dialogue INDI
    265106***************************************************************************************/
     107
    266108void BAO::init_properties()
    267109{
     
    288130    IUFillTextVector(&ObjectTP, ObjectT, NARRAY(ObjectT), mydev, "OBJECT_INFO", "Object", BASIC_GROUP, IP_RW, 0, IPS_IDLE);
    289131
    290 
    291132    // Equatorial Coords - SET
    292133    IUFillNumber(&EquatorialCoordsWN[0], "RA", "RA  H:M:S", "%10.6m",  0., 24., 0., 0.);
     
    294135    IUFillNumberVector(&EquatorialCoordsWNP, EquatorialCoordsWN, NARRAY(EquatorialCoordsWN), mydev, "EQUATORIAL_EOD_COORD_REQUEST" , "Equatorial JNow", BASIC_GROUP, IP_WO, 0, IPS_IDLE);
    295136
    296     // Equatorial Coords - READ
    297     //    IUFillNumber(&EquatorialCoordsRN[0], "RA", "RA  H:M:S", "%10.6m",  0., 24., 0., 0.);
    298     //    IUFillNumber(&EquatorialCoordsRN[1], "DEC", "Dec D:M:S", "%10.6m", -90., 90., 0., 0.);
    299     //    IUFillNumberVector(&EquatorialCoordsRNP, EquatorialCoordsRN, NARRAY(EquatorialCoordsRN), mydev, "EQUATORIAL_EOD_COORD" , "Equatorial JNow", BASIC_GROUP, IP_RO, 0, IPS_IDLE);
    300 
    301137    // Geographic coord - SET
    302138    IUFillNumber(&GeographicCoordsWN[0], "LAT", "Lat  D", "%10.6m",  -90., 90., 0., 0.);
     
    310146    IUFillNumber(&ActualisationN2[0], "DELAY", "Tracking mode delay (Sec)", "%10.6m",  0., 3600., 0., 0.);
    311147    IUFillNumberVector(&ActualisationNP2, ActualisationN2, NARRAY(ActualisationN2), mydev, "DELAY2" , "", OPTIONS_GROUP, IP_WO, 0, IPS_IDLE);
    312 
    313     // Transit threshold
    314     //IUFillNumber(&SlewAccuracyN[0], "TransitRA",  "RA (arcmin)", "%10.6m",  0., 60., 1., 3.0);
    315     //IUFillNumber(&SlewAccuracyN[1], "TransitDEC", "Dec (arcmin)", "%10.6m", 0., 60., 1., 3.0);
    316     //IUFillNumberVector(&SlewAccuracyNP, SlewAccuracyN, NARRAY(SlewAccuracyN), mydev, "Transit Accuracy", "", OPTIONS_GROUP, IP_RW, 0, IPS_IDLE);
    317 
    318     // Tracking threshold
    319     //IUFillNumber(&TrackAccuracyN[0], "TrackingRA", "RA (arcmin)", "%10.6m",  0., 60., 1., 3.0);
    320     //IUFillNumber(&TrackAccuracyN[1], "TrackingDEC", "Dec (arcmin)", "%10.6m", 0., 60., 1., 3.0);
    321     //IUFillNumberVector(&TrackAccuracyNP, TrackAccuracyN, NARRAY(TrackAccuracyN), mydev, "Tracking Accuracy", "", OPTIONS_GROUP, IP_RW, 0, IPS_IDLE);
    322 
    323 }
     148}
     149
    324150
    325151/**************************************************************************************
    326152** Initialisation de la boîte de dialogue INDI (suite)
    327153***************************************************************************************/
     154
    328155void BAO::ISGetProperties(const char *dev)
    329156{
     
    336163    IDDefText(&ObjectTP, NULL);
    337164    IDDefNumber(&EquatorialCoordsWNP, NULL);
    338     //IDDefNumber(&EquatorialCoordsRNP, NULL);
    339165    IDDefNumber(&GeographicCoordsWNP, NULL);
    340166    IDDefSwitch(&OnCoordSetSP, NULL);
     
    343169
    344170    // Options
    345     //IDDefNumber(&SlewAccuracyNP, NULL);
    346     //IDDefNumber(&TrackAccuracyNP, NULL);
    347171    IDDefNumber(&ActualisationNP1, NULL);
    348172    IDDefNumber(&ActualisationNP2, NULL);
     
    350174}
    351175
    352 /**************************************************************************************
    353 ** En cas de changement de texte dans la boîte de dialogue
    354 ***************************************************************************************/
     176
     177
     178/**************************************************************************************
     179** En cas de changement de texte dans la boîte de dialogue. Exemple : changement du
     180** nom de l'objet. Cette fonction n'est pas encore utilisée
     181***************************************************************************************/
     182
    355183void BAO::ISNewText (const char *dev, const char *name, char *texts[], char *names[], int n)
    356184{
     
    380208}
    381209
     210
    382211/**************************************************************************************
    383212** En cas de changement d'une valeur numérique dans la boîte de dialogue Indi
    384 ***************************************************************************************/
     213** Exemple : longitude, latitude, ar, dec etc...
     214**
     215***************************************************************************************/
     216
    385217void BAO::ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n)
    386218{
     
    416248                nset += Latitude >= -90.0 && Latitude <= 90.0;
    417249
    418                 Latitude*=Pidiv180;
     250                Latitude *= Pidiv180;
    419251            }
    420252            else if (eqp == &GeographicCoordsWN[1])
     
    423255                nset += Longitude >= 0.0 && Longitude <= 360.0;
    424256
    425                 Longitude*=-Pidiv180;
     257                Longitude *= -Pidiv180;
    426258            }
    427259        }
    428260
     261        // Si la longitude et la latitude sont correctes
    429262        if (nset == 2)
    430263        {
     
    443276            Longitude=0.0;
    444277        }
     278
     279        DefinirLongitudeLatitude(Longitude, Latitude);
    445280
    446281        return;
     
    471306        }
    472307
    473         targetRA  = newRA;
    474         targetDEC = newDEC;
    475 
     308
     309        // si les coordonnées de l'objet sont correctes
    476310        if (nset == 2)
    477311        {
    478312            char RAStr[32], DecStr[32];
    479313            double targetAZ, targetAlt;
     314
     315            targetRA  = newRA;
     316            targetDEC = newDEC;
    480317
    481318            fs_sexa(RAStr, newRA, 2, 3600);
     
    521358                if (newAct1 >= 0.0 && newAct1 <= 3600.0)
    522359                {
    523                     ActualisationTM1=newAct1;
     360                    ActualisationTM1 = newAct1;
    524361
    525362                    ActualisationNP1.s = IPS_OK;
     
    549386                if (newAct2 >= 0.0 && newAct2 <= 3600.0)
    550387                {
    551                     ActualisationTM2=newAct2;
     388                    ActualisationTM2 = newAct2;
    552389
    553390                    ActualisationNP2.s = IPS_OK;
     
    561398            }
    562399        }
    563 
    564     } /* end EquatorialCoordsWNP */
    565 }
     400    }
     401}
     402
    566403
    567404/**************************************************************************************
    568405** L'utilisateur clique sur l'un des boutons de la boîte Indi
    569406***************************************************************************************/
     407
    570408void BAO::ISNewSwitch (const char *dev, const char *name, ISState *states, char *names[], int n)
    571409{
     
    583421
    584422        connect_telescope();
     423
    585424        return;
    586425    }
     
    615454        IUResetSwitch(&AbortSlewSP);
    616455
    617         /*
    618         if (EquatorialCoordsWNP.s == IPS_BUSY)
    619         {
    620 
    621         AbortSlewSP.s = IPS_OK;
    622         EquatorialCoordsWNP.s       = IPS_IDLE;
    623         EquatorialCoordsRNP.s       = IPS_IDLE;
    624         HorizontalCoordsWNP.s       = IPS_IDLE;
    625         IDSetSwitch(&AbortSlewSP, "Slew aborted.");
    626         IDSetNumber(&EquatorialCoordsWNP, NULL);
    627         IDSetNumber(&EquatorialCoordsRNP, NULL);
    628         IDSetNumber(&HorizontalCoordsWNP, NULL);
    629         }
    630         */
     456        if (EquatorialCoordsWNP.s == IPS_OK)
     457        {
     458            AbortSlewSP.s = IPS_OK;
     459            EquatorialCoordsWNP.s       = IPS_IDLE;
     460            ObjectTP.s = IPS_IDLE;
     461
     462            IDSetSwitch(&ConnectSP, "Envoi de la commande Abort\n");
     463            IDSetNumber(&EquatorialCoordsWNP, NULL);
     464            IDSetText(&ObjectTP, NULL);
     465        }
     466
    631467        return;
    632468    }
     
    642478        IUResetSwitch(&ParkSP);
    643479
    644         /*
    645         if (EquatorialCoordsWNP.s == IPS_BUSY)
    646         {
    647 
    648         AbortSlewSP.s = IPS_OK;
    649         EquatorialCoordsWNP.s       = IPS_IDLE;
    650         EquatorialCoordsRNP.s       = IPS_IDLE;
    651         HorizontalCoordsWNP.s       = IPS_IDLE;
    652         IDSetSwitch(&AbortSlewSP, "Slew aborted.");
    653         IDSetNumber(&EquatorialCoordsWNP, NULL);
    654         IDSetNumber(&EquatorialCoordsRNP, NULL);
    655         IDSetNumber(&HorizontalCoordsWNP, NULL);
    656         }
    657         */
     480        if (EquatorialCoordsWNP.s == IPS_OK)
     481        {
     482            AbortSlewSP.s = IPS_OK;
     483            EquatorialCoordsWNP.s       = IPS_IDLE;
     484            ObjectTP.s = IPS_IDLE;
     485
     486            IDSetSwitch(&ConnectSP, "Envoi de la commande Park\n");
     487            IDSetNumber(&EquatorialCoordsWNP, NULL);
     488            IDSetText(&ObjectTP, NULL);
     489        }
     490
    658491        return;
    659492    }
    660493}
    661494
    662 /**************************************************************************************
    663 ** fct peut-être inutile
    664 ***************************************************************************************/
    665 void BAO::handle_error(INumberVectorProperty *nvp, int err, const char *msg)
    666 {
    667     nvp->s = IPS_ALERT;
    668 
    669     /* If the error is a time out, then the device doesn't support this property */
    670     if (err == -2)
    671     {
    672         nvp->s = IPS_ALERT;
    673         IDSetNumber(nvp, "Device timed out. Current device may be busy or does not support %s. Will retry again.", msg);
    674     }
    675     else
    676         /* Changing property failed, user should retry. */
    677         IDSetNumber( nvp , "%s failed.", msg);
    678 
    679     fault = true;
    680 }
    681495
    682496/**************************************************************************************
    683497** Initialisation des vecteurs INDI
    684498***************************************************************************************/
     499
    685500void BAO::reset_all_properties()
    686501{
     502    char chaine[10];
     503
    687504    ConnectSP.s                 = IPS_IDLE;
    688505    OnCoordSetSP.s              = IPS_IDLE;
     
    691508    ObjectTP.s                  = IPS_IDLE;
    692509    EquatorialCoordsWNP.s       = IPS_IDLE;
    693     //EquatorialCoordsRNP.s     = IPS_IDLE;
    694510    GeographicCoordsWNP.s       = IPS_IDLE;
    695     //SlewAccuracyNP.s          = IPS_IDLE;
    696     //TrackAccuracyNP.s         = IPS_IDLE;
    697511    ActualisationNP1.s          = IPS_IDLE;
    698512    ActualisationNP2.s          = IPS_IDLE;
     
    712526    IDSetText(&ObjectTP, NULL);
    713527    IDSetNumber(&EquatorialCoordsWNP, NULL);
    714     //IDSetNumber(&EquatorialCoordsRNP, NULL);
    715528    IDSetNumber(&GeographicCoordsWNP, NULL);
    716     //IDSetNumber(&SlewAccuracyNP, NULL);
    717     //IDSetNumber(&TrackAccuracyNP, NULL);
    718529    IDSetNumber(&ActualisationNP1, NULL);
    719530    IDSetNumber(&ActualisationNP2, NULL);
    720 
    721 }
    722 
    723 /**************************************************************************************
     531}
     532
     533
     534
     535
     536
     537/**************************************************************************************
     538** Gestion du thread
     539** permet de suivre la connexion/déconnexion des antennes
    724540**
    725 ***************************************************************************************/
    726 void BAO::correct_fault()
    727 {
    728     fault = false;
    729     IDMessage(mydev, "Telescope is online.");
    730 }
    731 
    732 /**************************************************************************************
     541** l'utilisation d'un thread permet d'éviter de bloquer l'exécution du pilote
     542** avec la fonction accept qui est bloquante
     543***************************************************************************************/
     544
     545void *BAO::pThreadSocket ()
     546{
     547    do
     548    {
     549        try
     550        {
     551            server.accept( Sockets[SocketsNumber].new_sock );
     552
     553            Sockets[SocketsNumber].IP = server.recupip(Sockets[SocketsNumber].new_sock);
     554
     555            Sockets[SocketsNumber++].Connected = true;
     556
     557            InitThreadOK = true;
     558
     559            usleep(100);
     560        }
     561        catch ( SocketException& e )
     562        {
     563            /*IDLog("Indi_BAO, pThreadSocket exception : ");
     564            IDLog(e.description().c_str());
     565            IDLog("\n");*/
     566        }
     567    }
     568    while (!Exit);
     569
     570    pthread_exit (0);
     571}
     572
     573
     574
     575
     576/**************************************************************************************
     577** Astuce pour lancer le thread depuis la classe BAO
    733578**
    734579***************************************************************************************/
    735 bool BAO::is_connected()
    736 {
    737     if (simulation) return true;
    738 
    739     // return (ConnectSP.sp[0].s == ISS_ON);
    740     return (ConnectSP.s == IPS_OK);
    741 }
    742 
    743 /**************************************************************************************
    744 **
    745 ***************************************************************************************/
    746 static void retry_connection(void * p)
    747 {
    748 
    749 }
    750 
    751 
    752 /**************************************************************************************
    753 ** Extraction de la position de l'antenne
    754 ** dans le retour de la commande POS
    755 ** POS/Valeur az/Valeur alt
    756 ***************************************************************************************/
    757 
    758 Position BAO::ExtractPosition(std::string str)
    759 {
    760     Position result;
    761 
    762     std::string str2;
    763 
    764     result.x = -1;
    765     result.y = -1;
     580
     581void* LancementThread(BAO * appli)
     582{
     583    appli->pThreadSocket();
     584
     585
     586    return 0;
     587}
     588
     589
     590/**************************************************************************************
     591** Extraction de la position de l'antenne aprÚs l'envoie de la commande P
     592** Le retour de la commande P est POSITION/valeur_az/valeur_alt/
     593** ExtractPosition retourne donc Valeur_az et Valeur_alt
     594***************************************************************************************/
     595
     596bool BAO::ExtractPosition(string str, Position *result)
     597{
     598    string str2;
    766599
    767600    int pos = str.find("/");
     
    769602    if (pos != string::npos)
    770603    {
    771         str2 = str.substr(pos+1);
     604        str2 = str.substr(pos + 1);
    772605
    773606        pos = str2.find("/");
     
    775608        if (pos != string::npos)
    776609        {
    777             result.x = atoi(str2.substr(0, pos).c_str());
    778 
    779             result.y = atoi(str2.substr(pos+1).c_str());
    780         }
    781     }
    782 
    783     return result;
     610            result->x = atol(str2.substr(0, pos).c_str());
     611
     612            result->y = atol(str2.substr(pos + 1).c_str());
     613           
     614            return true;
     615        }       
     616    }
     617
     618    IDLog((str +" fail\n").c_str());
     619
     620    return false;
    784621}
    785622
     
    787624
    788625/************************************************************************************
    789 * cette procédure convertit les coordonnées equatoriales de l'objet visé
     626* cette procédure convertit les coordonnées équatoriales de l'objet visé
    790627* en unités de codeurs des paraboles (nb de tours des deux axes moteurs depuis la position PARK)
    791628************************************************************************************/
     629
    792630void BAO::ADDEC2Motor(double newRA, double newDEC)
    793631{
     
    797635    char AltStr[32];
    798636
     637
    799638    // Calcule la hauteur et l'azimut de la zone du ciel pointée (en fonction de la date et du lieu)
    800639
    801     Azimut(tsl, Latitude, newRA * 15.0 * Pidiv180, newDEC * Pidiv180, &targetAz, &targetAlt);
     640    Azimut( newRA * 15.0 * Pidiv180, newDEC * Pidiv180, &targetAz, &targetAlt);
     641   
     642    // Refraction atmosphérique
     643   
     644    targetAlt = RefractionAtmospherique(targetAlt);
     645
     646    // Petit calcul pour faire en sorte que le sud soit à ° d'azimut
     647
     648    targetAz = VerifAngle( targetAz + Pi );
    802649
    803650    // En degrés
    804651
    805652    targetAlt *= N180divPi;
    806     targetAz *= N180divPi;
     653    targetAz *=  N180divPi;
     654
    807655
    808656    // Affichage dans les logs
     
    811659    fs_sexa(AltStr, targetAlt, 2, 3600);
    812660
    813     IDLog("Horizontal coords : az %s - Alt %s\n", AzStr, AltStr);
    814 
    815     // Le calcul est ici trÚs sommaire et arbitraire :
    816     // Je considÚre qu'il y a 100 positions possibles sur les deux axes
    817     // De plus, je considÚre qu'il n'est pas possible de viser un objet à
    818     // moins de 30° de hauteur au-dessus de l'horizon
    819 
    820     TargetPosition.x=(int)(targetAz*100.0/360.0);
    821 
    822     targetAlt=((90.0-targetAlt)/60.0);
    823 
    824     if (targetAlt>=1.0)
    825     {
    826         targetAlt=1.0; //on ne peut pas viser un objet situé à moins de 30°
    827         //au-dessus de l'horizon
     661    IDLog("Horizontal coords : az = %s     Alt = %s\n", AzStr, AltStr);
     662
     663
     664    //Conversion des deux angles en pas codeurs
     665
     666    if (targetAlt < 30.0 )
     667    {
     668        // L'objet est trop bas (<30°). On annule le suivi...
    828669
    829670        IDSetSwitch(&OnCoordSetSP, "Erreur ! L objet suivi est situe a moins de 30° au-dessus de l horizon. Goto annule.");
    830671
    831         Goto=false;
    832 
    833         LecturePosition=false;
     672        Suivi = false;
     673
     674        ActualisationPosition = false;
    834675
    835676        InitAntennes();
    836677    }
    837 
    838     TargetPosition.y=(int)(100.0*targetAlt);
     678    else
     679    {
     680        // Si la hauteur est supérieure à 90°, on doit faire une rotation de l'azimut de 180° et corriger
     681        // la hauteur en appliquant hauteur= 180° - hauteur
     682
     683        if (targetAlt > 90.0)
     684        {
     685            targetAlt = 180.0 - targetAlt;
     686            targetAz += 180.0;
     687        }
     688
     689        // On applique la formule de Marc pour convertir la hauteur en nombre de pas codeur alt
     690
     691        double I0 = 81.0;
     692        double I2 = 128279.4 - 129723.4 * sin( (targetAlt - 20.2345) * Pidiv180 ) ;
     693
     694        double Codalt = (sqrt(I2) - I0) / 0.078947;
     695
     696
     697        TargetPosition.y = (int) Arrondi(Codalt);
     698
     699        //4000 pas pour 360° sur l'axe az
     700
     701        TargetPosition.x = (int) Arrondi( targetAz * 4000.0 / 360.0);
     702
     703        IDLog("Nbre de pas codeurs az = %i        Alt = %i\n", TargetPosition.x, TargetPosition.y);
     704    }
    839705}
    840706
     
    842708/************************************************************************************
    843709* Retourne simplement le nombre d'antennes connectées
    844 * et capables de communiquer
    845710************************************************************************************/
    846711
    847712int BAO::AntennesConnectees()
    848713{
    849     int num=0;
     714    int num = 0;
    850715
    851716    for (int i=1; i<SocketsNumber; i++) if (Sockets[i].Connected) num++;
     
    861726void BAO::InitAntennes()
    862727{
    863     for (int i=0; i < MAXHOSTNAME ; i++)
    864     {
    865         Sockets[i].status=0;
    866         Sockets[i].sendalertes=0;
    867         Sockets[i].AttenteExecution=0;
    868         Sockets[i].AnomaliesExecution=0;
    869         Sockets[i].etape=0;
    870 
    871         Sockets[i].ack_status=false;
    872         Sockets[i].ack_pos=false;
    873         Sockets[i].ack_park=false;
    874         Sockets[i].ack_abort=false;
    875         Sockets[i].ack_goto=false;
    876 
    877         Sockets[i].PosValides=false;
    878         Sockets[i].GotoOk=false;
    879     }
     728    for (int i=0; i < MAXHOSTNAME; i++)
     729    {
     730        Sockets[i].status             = 0;
     731        Sockets[i].sendalertes        = 0;
     732        Sockets[i].AttenteExecution   = 0;
     733        Sockets[i].AnomaliesExecution = 0;
     734        Sockets[i].etape              = 0;
     735
     736        Sockets[i].ack_status = false;
     737        Sockets[i].ack_pos    = false;
     738        Sockets[i].ack_park   = false;
     739        Sockets[i].ack_abort  = false;
     740        Sockets[i].ack_goto   = false;
     741
     742        Sockets[i].PosValides = false;
     743        Sockets[i].GotoOk     = false;
     744    }
     745}
     746
     747
     748
     749/**************************************************************************************
     750** En cas de problÚme
     751** Déconnecter l'antenne utilisant le socket num
     752***************************************************************************************/
     753
     754void BAO::DeconnecterSocket(int num)
     755{
     756    IDLog("Deconnexion de l antenne : %s\n", Sockets[num].IP.c_str());
     757    Sockets[num].new_sock.shutdown();
     758    Sockets[num].Connected = false;
     759    Sockets[num].IP = "";
    880760}
    881761
     
    883763/**************************************************************************************
    884764** Procédure principale
    885 ** Elle est appelée toutes les POLLMS ms (ici 1 ms)
    886 ***************************************************************************************/
     765** Elle est appelée toutes les ms
     766***************************************************************************************/
     767
    887768void BAO::ISPoll()
    888769{
    889     static bool ISPOLLRunning=false;
    890     static int memSocketsNumber=-1;
    891     static unsigned int compt=100;
     770    static int memSocketsNumber = -1;       // Combien d'antennes étaient-elles connectées à l'appel précédent d'ISPoll ?
     771    static unsigned int compt   =  0;      // permet de répondre toutes les 100ms aux demandes de nouvelles connexions
     772
     773    // utilise pour le travail sur les chaine
    892774
    893775    int pos;
     
    898780    struct timezone tz;
    899781
     782    //si pas de connexion avec le seveur d'indi -> on sort
     783
    900784    if (is_connected() == false) return;
    901785
    902     if (ISPOLLRunning) return;
    903 
    904     ISPOLLRunning=true;
    905 
    906     compt++;
    907 
    908 
    909     //toutes les 100 millisec
    910 
    911     if ( compt%100 == 0)
     786
     787    // toutes les 100 millisec, on actualise le jour julien
     788    // le temps sidéral local etc...
     789
     790    if ( compt%100 == 0 )
    912791    {
    913792        //Récupération de la date et de l'heure
     
    917796        gettimeofday(&tv, &tz);
    918797
    919         Annee=(double)(date.tm_year+1900);
    920         Mois=(double)(date.tm_mon+1);
    921         Jour=(double)date.tm_mday;
    922         Heu=(double)date.tm_hour;
    923         Min=(double)date.tm_min;
    924         Sec=(double)date.tm_sec+tv.tv_usec/1.0E6;
    925         UTCP=0.0;//(double)date.tm_isdst;
    926 
    927 
    928         //Calcul du temps sidéral local
     798        double Annee=(double)(date.tm_year+1900);
     799        double Mois=(double)(date.tm_mon+1);
     800        double Jour=(double)date.tm_mday;
     801        double Heu=(double)date.tm_hour;
     802        double Min=(double)date.tm_min;
     803        double Sec=(double)date.tm_sec+tv.tv_usec/1.0E6;
     804        double UTCP=0.0;//(double)date.tm_isdst;
     805
     806        // On transmet la date et l'heure à la classe Astro
     807
     808        DefinirDateHeure(Annee, Mois, Jour, Heu, Min, Sec);
     809
     810        //Puis on calule le temps sidéral local, le JJ etc...
    929811
    930812        CalculTSL();
    931 
    932 
    933         //Y a-t-il de nouvelles tentatives de connexion sur le serveur ?
    934 
    935         InitThread();
    936     }
    937 
    938 
    939 
    940 
    941     if (InitThreadOK)  // Il faut qu'il y ait eu au moins une connexion détectée par le thread pour continuer
     813    }
     814
     815
     816    // Il faut que le thread soit actif
     817
     818    if (InitThreadOK)
    942819    {
    943820
    944821        // Nouvelle connexion sur le socket !
    945822
    946         if (SocketsNumber>memSocketsNumber)
    947         {
    948             memSocketsNumber=SocketsNumber;
     823        if (SocketsNumber > memSocketsNumber)
     824        {
     825            memSocketsNumber = SocketsNumber;
    949826
    950827            IDSetSwitch(&ConnectSP, "Connexion de l antenne %s. (Antennes connectees : %i)",
     
    953830
    954831
    955 
     832        /////////////////////////////////////////////////
    956833        // Début des échanges avec les microcontrÃŽleurs
    957834
    958835        // Analyse des réponses des microcontrÃŽleurs
    959836
    960         for (int i=1; i<SocketsNumber; i++) /*if (Sockets[i].Connected)*/
    961         {
    962             try
     837        for (int i=1; i<SocketsNumber; i++)
     838        {
     839            if (Sockets[i].Connected)
    963840            {
    964                 std::string reponse, memreponse;
    965                 // on récupÚre la réponse du microcontrÃŽleur
    966 
    967                 Sockets[i].new_sock >> reponse;
    968 
    969                 //IDSetSwitch(&OnCoordSetSP, "Réponse ISPOLL : %s\n", reponse.c_str());        // pour vérif
    970 
    971                 //Dans le cas où plusieurs trames seraient arrivées entre deux appels de POLLMS
    972                 //les traiter successivement
    973 
    974                 pos=reponse.find("\n");   // d'où l'intérêt de mettre un '\n' à la fin des trames
    975                 //pour différencier une trame de la précédente
    976 
    977                 while ((pos!=string::npos) && (reponse.length()>1))
     841                try
    978842                {
    979                     memreponse=reponse.substr(pos+1);
    980 
    981                     reponse=reponse.substr(0, pos);
    982 
    983 
    984                     // On traite ici les acknowledges
    985 
    986                     if ((reponse.find("ACK")!=string::npos) && (reponse.find("NACK")==string::npos))
     843                    string reponse, buffereponse;
     844
     845                    // on récupÚre la réponse du microcontrÃŽleur
     846
     847                    Sockets[i].new_sock >> reponse;
     848
     849                    // Dans le cas où plusieurs trames seraient arrivées entre deux appels de POLLMS
     850                    // les traiter successivement
     851
     852                    // d'où l'intérêt de mettre un '\n' à la fin des trames
     853                    // pour différencier une trame de la précédente
     854
     855                    pos = reponse.find("\n");
     856
     857                    // S'il y a une réponse
     858
     859                    while ((pos != string::npos) && (reponse.length() > 1))
    987860                    {
    988                         if (reponse.find("POSITION")!=string::npos)
     861                        // on garde en stock la seconde partie trame pour un
     862                        // traitement ultérieure
     863                        buffereponse = reponse.substr(pos + 1);
     864
     865                        // Partie traitée
     866                        reponse = reponse.substr(0, pos);
     867                       
     868                        IDLog("Réponse reçue de %s : %s\n", Sockets[i].IP.c_str(), reponse.c_str());
     869
     870                        // On analyse ici les acknowledges
     871                        if ((reponse.find("ACK") != string::npos) && (reponse.find("NACK") == string::npos))
    989872                        {
    990                             Sockets[i].ack_pos=true;
     873                            if (reponse.find("POSITION")  != string::npos)
     874                            {
     875                                Sockets[i].ack_pos=true;
     876                            }
     877                            else if (reponse.find("GOTO") != string::npos)
     878                            {
     879                                Sockets[i].ack_goto=true;
     880                            }
     881                            else if (reponse.find("PARK") != string::npos)
     882                            {
     883                                Sockets[i].ack_park=true;
     884                            }
     885                            else if (reponse.find("ABORT")!= string::npos)
     886                            {
     887                                Sockets[i].ack_abort=true;
     888                            }
    991889                        }
    992                         else if (reponse.find("GOTO")!=string::npos)
     890                        else
    993891                        {
    994                             Sockets[i].ack_goto=true;
    995                         }
    996                         else if (reponse.find("PARK")!=string::npos)
    997                         {
    998                             Sockets[i].ack_park=true;
    999                         }
    1000                         else if (reponse.find("ABORT")!=string::npos)
    1001                         {
    1002                             Sockets[i].ack_abort=true;
    1003                         }
    1004                     }
    1005                     else
    1006                     {
    1007 
    1008                         //réponse à la requête POSITION
    1009                         if (reponse.find("POSITION")!=string::npos)
    1010                         {
    1011                             if (reponse.find("NACK")!=string::npos)
     892                            //réponse à la requête POSITION
     893
     894                            if (reponse.find("POSITION") != string::npos)
    1012895                            {
    1013                                 OnCoordSetSP.s = IPS_ALERT;
    1014                                 IDSetSwitch(&OnCoordSetSP, "ALERTE antenne %s : position de l antenne inconnue !\n",
    1015                                             Sockets[i].IP.c_str());
    1016                                 Sockets[i].PosValides=false;
    1017                                 // Si la position de l'antenne est inconnue, on déconnecte l'antenne
    1018                                 Sockets[i].Connected=false;
     896                                if (reponse.find("NACK") != string::npos)
     897                                {
     898                                    //problÚme concernant la réponse à la commande P
     899                                    OnCoordSetSP.s = IPS_ALERT;
     900                                    IDSetSwitch(&OnCoordSetSP, "ALERTE antenne %s : position de l antenne inconnue !\n",
     901                                                Sockets[i].IP.c_str());
     902                                    Sockets[i].PosValides = false;
     903                                    // Si la position de l'antenne est inconnue, on déconnecte l'antenne
     904                                    Sockets[i].Connected  = false;
     905                                }
     906                                else if (Sockets[i].ack_pos)
     907                                {                             
     908                                    if ( Sockets[i].PosValides = (ExtractPosition(reponse, &Sockets[i].Pos) == true) )
     909                                    {
     910                                      OnCoordSetSP.s = IPS_OK;
     911                                      IDSetSwitch(&OnCoordSetSP, "Antenne %s : POSITION OK  (x=%i, y=%i)\n",
     912                                                Sockets[i].IP.c_str(), Sockets[i].Pos.x, Sockets[i].Pos.y);
     913                                    }
     914                                    else
     915                                    {
     916                                      OnCoordSetSP.s = IPS_ALERT;
     917                                      IDSetSwitch(&OnCoordSetSP, "Antenne %s : La position n est pas valide !\n",
     918                                                Sockets[i].IP.c_str());
     919                                    }
     920                                     
     921                                }
    1019922                            }
    1020                             else if (Sockets[i].ack_pos)
     923
     924                            //réponse à la requête PARK
     925
     926                            if (reponse.find("PARK") != string::npos)
    1021927                            {
    1022                                 OnCoordSetSP.s = IPS_OK;
    1023                                 Sockets[i].Pos = ExtractPosition(reponse);
    1024                                 Sockets[i].PosValides = true;
    1025                                 IDSetSwitch(&ParkSP, "Antenne %s : POSITION OK  (x=%i, y=%i)\n",
    1026                                             Sockets[i].IP.c_str(), Sockets[i].Pos.x, Sockets[i].Pos.y);
     928                                if (reponse.find("NACK") != string::npos)
     929                                {
     930                                    ParkSP.s = IPS_ALERT;
     931                                    IDSetSwitch(&ParkSP, "ALERTE antenne %s : erreur PARK !\n", Sockets[i].IP.c_str());
     932                                }
     933                                else if (Sockets[i].ack_park && reponse.find("OK")!=string::npos)
     934                                {
     935                                    ParkSP.s = IPS_OK;
     936                                    IDSetSwitch(&ParkSP, "Antenne %s : PARK OK\n",  Sockets[i].IP.c_str());
     937                                }
    1027938                            }
    1028939
    1029                         }//réponse à la requête PARK
    1030                         else if (reponse.find("PARK")!=string::npos)
    1031                         {
    1032                             if (reponse.find("NACK")!=string::npos)
     940                            //réponse à la requête ABORT
     941
     942                            if (reponse.find("ABORT") != string::npos)
    1033943                            {
    1034                                 ParkSP.s = IPS_ALERT;
    1035                                 IDSetSwitch(&ParkSP, "ALERTE antenne %s : erreur PARK !\n", Sockets[i].IP.c_str());
     944                                if (reponse.find("NACK") != string::npos)
     945                                {
     946                                    AbortSlewSP.s = IPS_ALERT;
     947                                    IDSetSwitch(&AbortSlewSP, "ALERTE antenne %s : erreur ABORT !\n",  Sockets[i].IP.c_str());
     948                                }
     949                                else if (Sockets[i].ack_abort && reponse.find("OK")!=string::npos)
     950                                {
     951                                    AbortSlewSP.s = IPS_OK;
     952                                    IDSetSwitch(&AbortSlewSP, "Antenne %s : ABORT OK\n",  Sockets[i].IP.c_str());
     953                                }
     954
    1036955                            }
    1037                             else if (reponse.find("OK")!=string::npos)
     956
     957                            //réponse à la requête GOTO
     958
     959                            if (reponse.find("GOTO") != string::npos)
    1038960                            {
    1039                                 ParkSP.s = IPS_OK;
    1040                                 IDSetSwitch(&ParkSP, "Antenne %s : PARK OK\n",  Sockets[i].IP.c_str());
    1041                             }
    1042 
    1043                         }//réponse à la requête ABORT
    1044                         else if (reponse.find("ABORT")!=string::npos)
    1045                         {
    1046                             if (reponse.find("NACK")!=string::npos)
    1047                             {
    1048                                 AbortSlewSP.s = IPS_ALERT;
    1049                                 IDSetSwitch(&AbortSlewSP, "ALERTE antenne %s : erreur ABORT !\n",  Sockets[i].IP.c_str());
    1050                             }
    1051 
    1052                             if (reponse.find("OK")!=string::npos)
    1053                             {
    1054                                 AbortSlewSP.s = IPS_OK;
    1055                                 IDSetSwitch(&AbortSlewSP, "Antenne %s : ABORT OK\n",  Sockets[i].IP.c_str());
    1056                             }
    1057 
    1058                         } //réponse à la requête GOTO
    1059                         else if (reponse.find("GOTO")!=string::npos)
    1060                         {
    1061                             if (reponse.find("NACK")!=string::npos)
    1062                             {
    1063                                 OnCoordSetSP.s = IPS_ALERT;
    1064                                 IDSetSwitch(&OnCoordSetSP, "ALERTE antenne %s : Erreur GOTO !\n",  Sockets[i].IP.c_str());
    1065                                 Sockets[i].Connected=false;
    1066                             }
    1067                             else if (Sockets[i].ack_goto)
    1068                             {
    1069                                 if (reponse.find("OK")!=string::npos)
     961                                if (reponse.find("NACK") != string::npos)
    1070962                                {
    1071                                     OnCoordSetSP.s = IPS_OK;
    1072 
    1073                                     Sockets[i].GotoOk=true;
    1074 
    1075                                     IDSetSwitch(&ParkSP, "Antenne %s : GOTO OK.\n",  Sockets[i].IP.c_str());
    1076 
    1077                                     lastRA  = targetRA;
    1078                                     lastDEC = targetDEC;
    1079 
    1080                                     //IDLog("We received JNow RA %s - DEC %s\n", RAStr, DecStr);*/
    1081 
    1082                                     EquatorialCoordsWNP.s = IPS_OK;
    1083                                     IDSetNumber (&EquatorialCoordsWNP, NULL);
    1084 
    1085                                     // Fin du Goto pour toutes les antennes ?
    1086 
    1087                                     int num=0;
    1088 
    1089                                     for (int j=1; j<SocketsNumber; j++) if (Sockets[j].Connected)
     963                                    OnCoordSetSP.s = IPS_ALERT;
     964                                    IDSetSwitch(&OnCoordSetSP, "ALERTE antenne %s : Erreur GOTO !\n",  Sockets[i].IP.c_str());
     965                                    DeconnecterSocket(i);
     966                                }
     967                                else if (Sockets[i].ack_goto)
     968                                {
     969                                    if (reponse.find("OK") != string::npos)
     970                                    {
     971                                        // On a la confirmation que l'antenne 'i' a bien réalisé
     972                                        // le goto
     973
     974                                        // On prend note
     975
     976                                        Sockets[i].GotoOk = true;
     977
     978                                        // Message pour l'utilisateur
     979                                       
     980                                        OnCoordSetSP.s = IPS_OK;
     981                                        IDSetSwitch(&OnCoordSetSP, "Antenne %s : GOTO OK.\n",  Sockets[i].IP.c_str());
     982
     983                                        // Fin du Goto pour toutes les antennes ?
     984
     985                                        int num=0;
     986
     987                                        for (int j=1; j<SocketsNumber; j++)
     988                                        {
     989                                          if (Sockets[j].Connected)
     990                                            {
     991                                                if (Sockets[j].GotoOk) num++;
     992                                            }
     993                                        }
     994
     995                                        if ((num == AntennesConnectees()) && (num>0))
    1090996                                        {
    1091                                             if (Sockets[j].GotoOk) num++;
    1092                                         }
    1093 
    1094                                     if ((num == AntennesConnectees()) && (num>0))
    1095                                     {
    1096                                         LecturePosition=false;
    1097 
    1098                                         InitAntennes();
    1099 
    1100                                         LastGotoOK=true;
    1101 
    1102                                         IDSetSwitch(&OnCoordSetSP, "GOTO OK !");
     997                                            // C'est bon ! Tout marche bien...
     998                                            // On actualise l'AR et la dec dans la boîte de dialogue
     999
     1000                                            lastRA  = targetRA;
     1001                                            lastDEC = targetDEC;
     1002
     1003                                            // On change en vert les voyants dans la boîte de dialogue
     1004
     1005                                            OnCoordSetSP.s = IPS_OK;
     1006                                            EquatorialCoordsWNP.s = IPS_OK;
     1007                                            IDSetNumber (&EquatorialCoordsWNP, NULL);
     1008
     1009                                            // On a fini le mouvement. On attend le prochain goto...
     1010
     1011                                            ActualisationPosition=false;
     1012
     1013                                            // Réinitialisation des antennes en vue d'un prochain goto
     1014
     1015                                            InitAntennes();
     1016
     1017                                            UpdateGoto=true;
     1018
     1019                                            // Confirmation dans la boîte de dialogue que toutes
     1020                                            // les antennes sont OK
     1021                                           
     1022                                            OnCoordSetSP.s = IPS_OK;
     1023                                            IDSetSwitch(&OnCoordSetSP, "GOTO OK !");
     1024                                        }                                       
    11031025                                    }
    11041026                                }
    11051027                            }
    11061028                        }
     1029
     1030                        // On passe à la trame suivante si memreponse n'est pas vide
     1031
     1032                        reponse=buffereponse;
     1033                        pos=reponse.find("\n");
    11071034                    }
    1108 
    1109                     // On passe éventuellement à la trame suivante
    1110 
    1111                     reponse=memreponse;
    1112                     pos=reponse.find("\n");
    1113 
     1035                }
     1036                catch (SocketException& e) //Aïe
     1037                {
     1038                    DeconnecterSocket(i);
     1039
     1040                    IDLog("Indi_BAO, SocketException IsPoll : ");
     1041                    IDLog(e.description().c_str());
     1042                    IDLog("\n");
    11141043                }
    11151044            }
    1116             catch (SocketException& e) //Aïe
     1045        }
     1046
     1047
     1048        ///////////////////////////////////////
     1049        // L'utilisateur a demandé l'annulation du mouvement
     1050        // en cours
     1051
     1052        if (Abort)
     1053        {
     1054            // On arrête le suivi d'un objet
     1055
     1056            Suivi = false;
     1057
     1058            // On arrête l'enchaînement des actions
     1059            // pour réaliser un goto
     1060
     1061            ActualisationPosition = false;
     1062
     1063            // On envoie l'ordre ABORT à toutes les antennes
     1064
     1065            for (int i=1; i<SocketsNumber; i++)
    11171066            {
    1118                 Sockets[i].new_sock.shutdown();
    1119                 Sockets[i].new_sock.create();
    1120                 Sockets[i].Connected = Sockets[i].new_sock.connect((std::string)Sockets[i].IP);
    1121 
    11221067                if (Sockets[i].Connected)
    1123                 {
    1124                     Sockets[i].AttenteExecution=0;
    1125                     Sockets[i].AnomaliesExecution=0;
    1126                 }
    1127 
    1128                 std::string oss;
    1129                 oss="SocketException IsPoll : " + e.description() + "\n";
    1130                 size_t size = oss.size() + 1;
    1131                 char* buffer = new char[size];
    1132                 strncpy(buffer, oss.c_str(), size);
    1133                 IDLog(buffer);
    1134                 delete [] buffer;
    1135             }
    1136         }
    1137 
    1138 
    1139 
    1140         if (Abort)
    1141         {
    1142             IDSetSwitch(&ConnectSP, "Envoi de la commande Abort\n");
    1143 
    1144             Goto=false;
    1145 
    1146             for (int i=1; i<SocketsNumber; i++) if (Sockets[i].Connected)
    11471068                {
    11481069                    if (!ABORT(i)) Sockets[i].sendalertes++;
    11491070                }
    1150 
    1151             LecturePosition=false;
     1071            }
     1072
     1073            IDSetSwitch(&OnCoordSetSP, "ABORT OK !");
     1074
     1075            // Réinititialisation des paramÚtres des antennes
    11521076
    11531077            InitAntennes();
    11541078
     1079            //Pour permettre de refaire un abort
     1080
    11551081            Abort=false;
    11561082        }
    11571083
     1084        ///////////////////////////////////////
     1085        // L'utilisateur a demandé de mettre les antennes au repos
    11581086
    11591087        if (Park)
    11601088        {
    1161             IDSetSwitch(&ConnectSP, "Envoi de la commande Park\n");
    1162 
    1163             Goto=false;
    1164 
    1165             for (int i=1; i<SocketsNumber; i++) if (Sockets[i].Connected)
     1089            // On arrête le suivi d'un objet
     1090
     1091            Suivi = false;
     1092
     1093            // On arrête l'enchaînement des actions
     1094            // pour réaliser un goto
     1095
     1096            ActualisationPosition = false;
     1097
     1098            // On envoie l'ordre PARK à toutes les antennes
     1099
     1100            for (int i=1; i<SocketsNumber; i++)
     1101            {
     1102                if (Sockets[i].Connected)
    11661103                {
    11671104                    if (!PARK(i)) Sockets[i].sendalertes++;
    11681105                }
    1169 
    1170             LecturePosition=false;
     1106            }
     1107
     1108            IDSetSwitch(&OnCoordSetSP, "PARK OK !");
     1109
     1110            // Réinititialisation des paramÚtres des antennes
    11711111
    11721112            InitAntennes();
    11731113
     1114            //Pour permettre de refaire un park
     1115
    11741116            Park=false;
    11751117        }
    11761118
    11771119
     1120        ///////////////////////////////////////
    11781121        // Gestion du suivi
    11791122
    1180         if ((Goto) && (LastGotoOK))
     1123        if ((Suivi) && (UpdateGoto))
    11811124        {
    11821125            // Durée entre deux actualisations
    11831126
    1184             double delai=ActualisationTM1/3600.0/24.0;   // Actualisation toutes les 15 minutes en mode transit
    1185 
    1186             if (TrackingMode==2) delai=ActualisationTM2/3600.0/24.0;   //et 5 secs en mode tracking
    1187 
    1188 
    1189             // On actualise la position
    1190 
    1191             if (JJ-JJAnc > delai)
     1127            double delai=ActualisationTM1 / 3600.0 / 24.0;   // Actualisation toutes les 15 minutes en mode transit
     1128
     1129            if (TrackingMode==2) delai=ActualisationTM2 / 3600.0 / 24.0;   //et 5 secs en mode tracking
     1130
     1131
     1132            // On actualise la position si le delai est dépassé
     1133
     1134            if (GetJJ() - JJAnc > delai)
    11921135            {
    1193 
    1194                 LastGotoOK=false;
    1195 
    1196                 LecturePosition=true;
     1136                UpdateGoto = false;
     1137
     1138                // Conversion des coordonnées en pas moteur
    11971139
    11981140                ADDEC2Motor(targetRA, targetDEC);
    11991141
     1142                // On réinitialise les antennes en vue du goto
     1143
    12001144                InitAntennes();
    12011145
    1202                 JJAnc=JJ;
     1146                ActualisationPosition = true;
     1147
     1148                // On sauvegarde la date
     1149
     1150                JJAnc = GetJJ();
    12031151            }
    12041152
    1205             //Plus d'antenne !
     1153            //Plus d'antenne ! On arrête le suivi
    12061154
    12071155            if (AntennesConnectees() == 0)
    12081156            {
    1209                 // LecturePosition=false;
    1210 
    1211                 // Goto=false;
    1212 
    1213                 // InitAntennes();
    1214 
    1215                 if ( compt % 1000 == 0)  IDSetSwitch(&OnCoordSetSP, "Erreur ! Plus d antennes connectees !");
     1157                if ( compt % 1000 == 0)
     1158                {
     1159                    IDSetSwitch(&OnCoordSetSP, "Erreur ! Plus d antennes connectees !");
     1160
     1161                    if (Suivi) IDLog("Arrêt du suivi !");
     1162
     1163                    ActualisationPosition=false;
     1164
     1165                    Suivi=false;
     1166
     1167                    InitAntennes();
     1168                }
    12161169            }
    12171170        }
     
    12221175        // puis envoi d'une commande Goto
    12231176
    1224         if (LecturePosition)
    1225         {
    1226             for (int i=1; i<SocketsNumber; i++) /*if (Sockets[i].Connected)*/
     1177        if (ActualisationPosition)
     1178        {
     1179            for (int i=1; i<SocketsNumber; i++)
    12271180            {
    1228                 switch (Sockets[i].etape)
     1181                if (Sockets[i].Connected)
    12291182                {
    1230 
    1231                     //Envoi de la commande POS
    1232                 case 0 :
    1233                 {
    1234                     Sockets[i].ack_pos=false;
    1235                     Sockets[i].PosValides=false;
    1236 
    1237                     if (!POSITION(i)) Sockets[i].sendalertes++;
    1238 
    1239                     Sockets[i].etape++;
    1240                 }
    1241                 break;
    1242 
    1243                 //ack POS
    1244                 case 1 :
    1245                 {
    1246                     if (Sockets[i].ack_pos)
     1183                    switch (Sockets[i].etape)
    12471184                    {
    1248                         Sockets[i].AttenteExecution=0;
    1249                         Sockets[i].AnomaliesExecution=0;
     1185
     1186                        //Envoi de la commande POS
     1187
     1188                    case 0 :
     1189                    {
     1190                        Sockets[i].ack_pos    = false;
     1191                        Sockets[i].PosValides = false;
     1192
     1193                        if (!POSITION(i)) Sockets[i].sendalertes++;
     1194
    12501195                        Sockets[i].etape++;
    1251                         i--;
    12521196                    }
    1253                     else
     1197                    break;
     1198
     1199
     1200                    // A-ton bien reçu l'ack POS ?
     1201
     1202                    case 1 :
    12541203                    {
    1255                         // on réitÚre l'ordre précédent si rien ne se passe
    1256 
    1257                         Sockets[i].AttenteExecution++;
    1258 
    1259                         if (Sockets[i].AttenteExecution>MAXATTENTE)
     1204                        if (Sockets[i].ack_pos)
    12601205                        {
    1261                             Sockets[i].etape=0;
    1262                             Sockets[i].AttenteExecution=0;
    1263                             Sockets[i].AnomaliesExecution++;
     1206                            // tout marche bien
     1207                            Sockets[i].AttenteExecution = 0;
     1208                            Sockets[i].AnomaliesExecution = 0;
     1209                            Sockets[i].etape++;
     1210                            i--; //permet de revenir sur ce même socket malgré la boucle
     1211                            // -> plus rapide
    12641212                        }
    1265 
    1266                         if (Sockets[i].AnomaliesExecution>MAXANOMALIES)
     1213                        else
    12671214                        {
    1268                             Sockets[i].etape=3;
    1269 
    1270                             // if ( compt % 1000 == 0)
     1215                            // on réitÚre l'ordre précédent si rien ne se passe
     1216
     1217                            // On garde une trace de l'anomalie
     1218                            Sockets[i].AttenteExecution++;
     1219
     1220                            if (Sockets[i].AttenteExecution > MAXATTENTE)
    12711221                            {
     1222                                // on recommence depuis le début
     1223                                Sockets[i].etape = 0;
     1224                                Sockets[i].AttenteExecution = 0;
     1225                                Sockets[i].AnomaliesExecution++;
     1226                            }
     1227
     1228                            // Toujours rien -> plus sérieux : il faut déconnecter l'antenne
     1229                            if (Sockets[i].AnomaliesExecution > MAXANOMALIES)
     1230                            {
     1231                                OnCoordSetSP.s = IPS_ALERT;
    12721232                                IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : pas d acknowledge recu apres l ordre POSITION. \
    1273                                 Deconnexion de l antenne.", Sockets[i].IP.c_str());
    1274                                 Sockets[i].Connected=false;
     1233    Deconnexion de l antenne.", Sockets[i].IP.c_str());
     1234                                DeconnecterSocket(i);
    12751235                            }
    12761236                        }
    12771237                    }
    1278                 }
    1279                 break;
    1280 
    1281                 //Valeurs pos valides ?
    1282                 case 2 :
    1283                 {
    1284                     if (Sockets[i].PosValides)
     1238                    break;
     1239
     1240
     1241                    //Les valeurs retournées pas la commande POSITION sont-elles valides ?
     1242
     1243                    case 2 :
    12851244                    {
    1286                         Sockets[i].AttenteExecution=0;
    1287                         Sockets[i].etape++;
    1288                     }
    1289                     else
    1290                     {
    1291                         // on réitÚre l'ordre précédent si rien ne se passe
    1292 
    1293                         Sockets[i].AttenteExecution++;
    1294 
    1295                         if (Sockets[i].AttenteExecution>MAXATTENTE)
     1245                        if (Sockets[i].PosValides)
    12961246                        {
    1297                             Sockets[i].etape=2;
    1298                             Sockets[i].AttenteExecution=0;
    1299                             Sockets[i].AnomaliesExecution++;
     1247                            Sockets[i].AttenteExecution = 0;
     1248                            Sockets[i].AnomaliesExecution = 0;
     1249                            Sockets[i].etape++; // on passe à l'étape suivante
    13001250                        }
    1301 
    1302                         if (Sockets[i].AnomaliesExecution>MAXANOMALIES)
     1251                        else
    13031252                        {
    1304                             Sockets[i].etape=3;
    1305 
    1306                             // if ( compt % 1000 == 0)
     1253                            // on réitÚre l'ordre précédent si rien ne se passe
     1254                            Sockets[i].AttenteExecution++;
     1255
     1256                            if (Sockets[i].AttenteExecution > MAXATTENTE)
    13071257                            {
     1258                                // on attend davantage la réponse posvalides                               
     1259                                Sockets[i].etape = 2;
     1260                                Sockets[i].AttenteExecution = 0;
     1261                                Sockets[i].AnomaliesExecution++;
     1262                            }
     1263
     1264                            if (Sockets[i].AnomaliesExecution > MAXANOMALIES)
     1265                            {
     1266                                OnCoordSetSP.s = IPS_ALERT;
    13081267                                IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : la position retournee n est pas valide. \
    1309                                 Deconnexion de l antenne.", Sockets[i].IP.c_str());
    1310                                 Sockets[i].Connected=false;
     1268    Deconnexion de l antenne.", Sockets[i].IP.c_str());
     1269                                DeconnecterSocket(i);
    13111270                            }
    13121271                        }
    13131272                    }
    1314                 }
    1315                 break;
    1316 
    1317                 //ack goto  ?
    1318                 case 4 :
    1319                 {
    1320                     if (Sockets[i].ack_goto)
     1273                    break;
     1274
     1275
     1276                    // A-ton reçu l'acknowledge de la commande goto ?
     1277
     1278                    case 4 :
    13211279                    {
    1322                         Sockets[i].AttenteExecution=0;
    1323                         Sockets[i].AnomaliesExecution=0;
    1324                         Sockets[i].etape++;
    1325                     }
    1326                     else
    1327                     {
    1328                         // on réitÚre l'ordre précédent si rien ne se passe
    1329 
    1330                         Sockets[i].AttenteExecution++;
    1331 
    1332                         if (Sockets[i].AttenteExecution>MAXATTENTE)
     1280                        if (Sockets[i].ack_goto)
    13331281                        {
    1334                             Sockets[i].etape=4;
    1335                             Sockets[i].AttenteExecution=0;
    1336                             Sockets[i].AnomaliesExecution++;
     1282                            Sockets[i].AttenteExecution = 0;
     1283                            Sockets[i].AnomaliesExecution = 0;
     1284                            Sockets[i].etape++; // on passe à l'étape suivante
    13371285                        }
    1338 
    1339                         if (Sockets[i].AnomaliesExecution>MAXANOMALIES)
     1286                        else
    13401287                        {
    1341                             Sockets[i].etape=6;
    1342 
    1343                             // if ( compt % 1000 == 0)
     1288                            // on réitÚre l'ordre précédent si rien ne se passe
     1289                            Sockets[i].AttenteExecution++;
     1290
     1291                            if (Sockets[i].AttenteExecution > MAXATTENTE)
    13441292                            {
     1293                                // On prolonge l'attente                               
     1294                                Sockets[i].etape = 4;
     1295                                Sockets[i].AttenteExecution = 0;
     1296                                Sockets[i].AnomaliesExecution++;
     1297                            }
     1298
     1299                            if (Sockets[i].AnomaliesExecution > MAXANOMALIES)
     1300                            {
     1301                                OnCoordSetSP.s = IPS_ALERT;
    13451302                                IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : pas d acknowledge recu apres l ordre GOTO. \
    1346                                 Deconnexion de l antenne.", Sockets[i].IP.c_str());
    1347                                 Sockets[i].Connected=false;
     1303    Deconnexion de l antenne.", Sockets[i].IP.c_str());
     1304                                DeconnecterSocket(i);
    13481305                            }
    13491306                        }
    13501307                    }
    1351                 }
    1352                 break;
    1353 
    1354                 //goto ok  ?
    1355                 case 5 :
    1356                 {
    1357                     if (Sockets[i].GotoOk)
     1308                    break;
     1309
     1310
     1311                    //  Confirmation goto ok ?
     1312
     1313                    case 5 :
    13581314                    {
    1359                         Sockets[i].AttenteExecution=0;
    1360                         Sockets[i].AnomaliesExecution=0;
    1361                         Sockets[i].etape++;
    1362                     }
    1363                     else
    1364                     {
    1365                         // on réitÚre l'ordre précédent si rien ne se passe
    1366 
    1367                         Sockets[i].AttenteExecution++;
    1368 
    1369                         if (Sockets[i].AttenteExecution>MAXATTENTE)
     1315                        if (Sockets[i].GotoOk)
    13701316                        {
    1371                             Sockets[i].etape=5;
    1372                             Sockets[i].AttenteExecution=0;
    1373                             Sockets[i].AnomaliesExecution++;
     1317                            Sockets[i].AttenteExecution = 0;
     1318                            Sockets[i].AnomaliesExecution = 0;
     1319                            Sockets[i].etape++;
    13741320                        }
    1375 
    1376                         if (Sockets[i].AnomaliesExecution>MAXANOMALIESGOTO)
     1321                        else
    13771322                        {
    1378                             Sockets[i].etape=6;
    1379 
    1380                             // if ( compt % 1000 == 0)
     1323                            // on réitÚre l'ordre précédent si rien ne se passe
     1324                            Sockets[i].AttenteExecution++;
     1325
     1326                            if (Sockets[i].AttenteExecution > MAXATTENTE)
    13811327                            {
     1328                                // On prolonge l'attente
     1329                               
     1330                                Sockets[i].etape = 5;
     1331                                Sockets[i].AttenteExecution = 0;
     1332                                Sockets[i].AnomaliesExecution++;
     1333                            }
     1334
     1335                            // On déconnecte l'antenne s'il n'y a pas de coonfirmation du goto au bout de 2 minutes                       
     1336                            if (Sockets[i].AnomaliesExecution > MAXANOMALIESGOTO)
     1337                            {
     1338                                OnCoordSetSP.s = IPS_ALERT;
    13821339                                IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : l antenne n a pas renvoye GOTO/OK. \
    1383                                 Deconnexion de l antenne.", Sockets[i].IP.c_str());
    1384                                 Sockets[i].Connected=false;
    1385 
    1386 
     1340    Deconnexion de l antenne.", Sockets[i].IP.c_str());
     1341                                DeconnecterSocket(i);
    13871342                            }
    13881343                        }
    13891344                    }
    1390                 }
    1391                 break;
    1392 
     1345                    break;
     1346                    }
    13931347                }
    13941348            }
     
    13961350
    13971351
    1398 
    1399 
    1400 
    1401 
    1402         // Détection d'anomalies concernant l'envoi de trames sur la socket. déconnexion du micro-cont ?
    1403 
    1404         for (int i=1; i<SocketsNumber; i++) if (Sockets[i].Connected)
     1352        ///////////////////////////////////////
     1353        //On attend que toutes les antennes soient prêtes pour lancer l'ordre Goto -> meilleure synchronisation
     1354
     1355        int num=0;
     1356
     1357        for (int i=1; i<SocketsNumber; i++)
     1358        {
     1359            if (Sockets[i].Connected)
     1360            {
     1361                if (Sockets[i].etape == 3) num++; //fin de la procédure ActualisationPosition.
     1362                // num antennes sont prêtes à recevoir l'ordre GOTO
     1363            }
     1364        }
     1365
     1366        if ((num == AntennesConnectees()) && (num>0))
     1367        {
     1368            for (int i=1; i<SocketsNumber; i++ )
     1369            {
     1370                if (Sockets[i].Connected)
     1371                {
     1372                    Sockets[i].ack_goto = false;
     1373                    Sockets[i].AttenteExecution = 0;
     1374                    Sockets[i].AnomaliesExecution = 0;
     1375
     1376                    if (!GOTO(i, TargetPosition.x - Sockets[i].Pos.x , TargetPosition.y - Sockets[i].Pos.y )) Sockets[i].sendalertes++;
     1377
     1378                    Sockets[i].etape++;
     1379                }
     1380            }
     1381        }
     1382
     1383        ///////////////////////////////////////
     1384        // Détection d'anomalies sur la socket. Déconnexion du micro-cont ?
     1385
     1386        for (int i=1; i<SocketsNumber; i++)
     1387        {
     1388            if (Sockets[i].Connected)
    14051389            {
    14061390                if (Sockets[i].sendalertes > 0)
    14071391                {
    1408                     Sockets[i].etape=5;
    1409 
    1410                     //  if ( compt % 1000 == 0)
    1411                     {
    1412                         IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : deconnexion de l antenne.", Sockets[i].IP.c_str());
    1413 
    1414                         Sockets[i].Connected=false;
    1415                     }
     1392                    OnCoordSetSP.s = IPS_ALERT;
     1393                    IDSetSwitch(&OnCoordSetSP, "Erreur sur l antenne %s : deconnexion de l antenne.", Sockets[i].IP.c_str());
     1394
     1395                    DeconnecterSocket(i);
    14161396                }
    14171397            }
    1418 
    1419 
    1420 
    1421         //On attend que toutes les antennes soient prêtes pour lancer l'ordre Goto -> meilleure synchronisation
    1422 
    1423         int num=0;
    1424 
    1425         for (int i=1; i<SocketsNumber; i++) if (Sockets[i].Connected)
    1426             {
    1427                 if (Sockets[i].etape == 3) num++; //fin de la procédure LecturePosition. Les antennes sont prêtes
    1428                 //à recevoir l'ordre GOto
    1429             }
    1430 
    1431         if ((num == AntennesConnectees()) && (num>0))
    1432         {
    1433             for (int i=1; i<SocketsNumber; i++ ) if (Sockets[i].Connected)
    1434                 {
    1435                     Sockets[i].ack_goto=false;
    1436                     Sockets[i].AttenteExecution=0;
    1437                     Sockets[i].AnomaliesExecution=0;
    1438 
    1439                     if (!GOTO(i, Sockets[i].Pos.x - TargetPosition.x, Sockets[i].Pos.y - TargetPosition.y )) Sockets[i].sendalertes++;
    1440 
    1441                     Sockets[i].etape++;
    1442                 }
    1443         }
    1444     }
    1445 
    1446     ISPOLLRunning=false;
    1447 }
    1448 
    1449 
    1450 
    1451 /**************************************************************************************
    1452 **
    1453 ***************************************************************************************/
     1398        }
     1399    }
     1400
     1401    compt++;
     1402}
     1403
     1404
     1405
     1406/**************************************************************************************
     1407** Mode transit ou tracking
     1408***************************************************************************************/
     1409
    14541410bool BAO::process_coords()
    14551411{
     
    14591415    case BAO_TRANSIT:
    14601416
     1417        //Eteindre les voyants dans la boîte de dialogue Indi
    14611418        EquatorialCoordsWNP.s = IPS_BUSY;
     1419        AbortSlewSP.s = IPS_IDLE;
     1420        ParkSP.s = IPS_IDLE;
    14621421
    14631422        IDSetNumber (&EquatorialCoordsWNP, NULL);
     1423        IDSetSwitch (&AbortSlewSP, NULL);
     1424        IDSetSwitch (&ParkSP, NULL);
     1425
     1426        // On prépare les antennes pour le prochain goto
    14641427
    14651428        InitAntennes();
    14661429
    1467         JJAnc=JJ;
     1430        JJAnc = GetJJ();
     1431       
     1432        ADDEC2Motor(targetRA, targetDEC);
    14681433
    14691434        TrackingMode = 1;
    14701435
    1471         Goto=true;
    1472 
    1473         LastGotoOK=false;
    1474 
    1475         LecturePosition=true;
    1476 
    1477         ADDEC2Motor(targetRA, targetDEC);
     1436        Suivi = true;
     1437
     1438        UpdateGoto = false;
     1439
     1440        ActualisationPosition = true;
    14781441
    14791442        break;
     
    14821445    case BAO_TRACKING:
    14831446
     1447        //Eteindre les voyants dans la boîte de dialogue Indi
    14841448        EquatorialCoordsWNP.s = IPS_BUSY;
     1449        AbortSlewSP.s = IPS_IDLE;
     1450        ParkSP.s = IPS_IDLE;
    14851451
    14861452        IDSetNumber (&EquatorialCoordsWNP, NULL);
     1453        IDSetSwitch (&AbortSlewSP, NULL);
     1454        IDSetSwitch (&ParkSP, NULL);
    14871455
    14881456        InitAntennes();
    14891457
    1490         JJAnc=JJ;
     1458        JJAnc=GetJJ();
     1459       
     1460        ADDEC2Motor(targetRA, targetDEC);
    14911461
    14921462        TrackingMode = 2;
    14931463
    1494         Goto=true;
    1495 
    1496         LastGotoOK=false;
    1497 
    1498         LecturePosition=true;
    1499 
    1500         ADDEC2Motor(targetRA, targetDEC);
     1464        Suivi = true;
     1465
     1466        UpdateGoto = false;
     1467
     1468        ActualisationPosition = true;       
    15011469
    15021470        break;
     
    15061474}
    15071475
     1476
     1477
     1478/**************************************************************************************
     1479** Connexion / Déconnexion avec le télescope
     1480***************************************************************************************/
     1481
     1482void BAO::connect_telescope()
     1483{
     1484    switch (ConnectSP.sp[0].s)
     1485    {
     1486    case ISS_ON:
     1487
     1488        // Etats des voyants
     1489
     1490        ConnectS[0].s = ISS_ON;
     1491        ConnectS[1].s = ISS_OFF;
     1492        ConnectSP.s = IPS_OK;
     1493        IDSetSwitch (&ConnectSP, "BAORadio is online. Retrieving basic data...");
     1494
     1495        // Petit message
     1496
     1497        IDLog("\nHello BAORadio !\n");
     1498
     1499        // On lance le thread !
     1500
     1501        Exit=false;
     1502
     1503        if (pthread_create (&th1, NULL, (void*(*)(void*))LancementThread, this) < 0)
     1504        {
     1505            IDLog("pthread_create error for threadSocket\n");
     1506        }
     1507
     1508        break;
     1509
     1510    case ISS_OFF:
     1511
     1512        // On sort du thread
     1513
     1514        Exit = true;
     1515        sleep(1);
     1516        pthread_join (th1, NULL);
     1517        InitThreadOK = false;
     1518
     1519        // Etat des voyants
     1520
     1521        ConnectS[0].s = ISS_OFF;
     1522        ConnectS[1].s = ISS_ON;
     1523        ConnectSP.s = IPS_IDLE;
     1524        IDSetSwitch (&ConnectSP, "BAORadio is offline.");
     1525        IDLog("Telescope is offline.");
     1526
     1527        // On déconnecte tous les sockets
     1528
     1529        for (int i=0; i<MAXHOSTNAME; i++)
     1530        {
     1531            DeconnecterSocket(i);
     1532        }
     1533
     1534        // init
     1535
     1536        InitAntennes();
     1537
     1538        SocketsNumber = 1;
     1539
     1540        break;
     1541    }
     1542}
     1543
     1544
     1545
     1546
     1547/**************************************************************************************
     1548**  Envoie une commande sur le socket numsocket
     1549***************************************************************************************/
     1550
     1551bool BAO::COMMANDE(int numsocket, char* Commande, char* Params)
     1552{
     1553    char chaine[MAXCARACTERES];
     1554
     1555    try
     1556    {
     1557        sprintf(chaine, "%s%s\n", Commande, Params);
     1558       
     1559        Sockets[numsocket].new_sock << chaine;
     1560       
     1561        IDLog("Commande envoyée à %s: %s", Sockets[numsocket].IP.c_str(), chaine);
     1562    }
     1563    catch (SocketException& e)
     1564    {
     1565        DeconnecterSocket(numsocket);
     1566
     1567        IDLog("Indi_BAO, COMMANDE exception : ");
     1568        IDLog(e.description().c_str());
     1569        IDLog("\n");
     1570
     1571        return false;
     1572    }
     1573
     1574    return true;
     1575}
     1576
     1577
     1578/**************************************************************************************
     1579** Commande POSITION
     1580***************************************************************************************/
     1581
     1582bool BAO::POSITION(int numsocket)
     1583{
     1584    return COMMANDE(numsocket, (char*)"P", (char*)"");
     1585}
     1586
     1587/**************************************************************************************
     1588** Commande PARK
     1589***************************************************************************************/
     1590
     1591bool BAO::PARK(int numsocket)
     1592{
     1593    return COMMANDE(numsocket, (char*)"Z", (char*)"");
     1594}
     1595
     1596/**************************************************************************************
     1597** Commande ABORT
     1598***************************************************************************************/
     1599
     1600bool BAO::ABORT(int numsocket)
     1601{
     1602    return COMMANDE(numsocket, (char*)"A", (char*)"");
     1603}
     1604
     1605
     1606/**************************************************************************************
     1607** Commande GOTO
     1608***************************************************************************************/
     1609
     1610bool BAO::GOTO(int numsocket, int deltaAz, int deltaAlt)
     1611{
     1612    char Params[MAXCARACTERES];
     1613    char sensAz;
     1614    char sensAlt;
     1615
     1616    sensAlt = 1;
     1617    sensAz  = 1;
     1618
     1619    if ( deltaAz < 0 )
     1620    {
     1621        deltaAz = -deltaAz;
     1622        sensAz  = 0;
     1623    }
     1624
     1625    if ( deltaAlt < 0 )
     1626    {
     1627        deltaAlt = -deltaAlt;
     1628        sensAlt  = 0;
     1629    }
     1630
     1631    // Vérification du nombre de pas à faire au niveau de l'axe azimut
     1632    // Rappel : un tour complet autour de l'axe az fait 4000 pas codeur (#define NBREPASCODEURSAZ dans BAO.h)
     1633
     1634    // problÚme 1 : si deltaAz > à un demi-tours - soit 2000 pas alors
     1635    // on fait le trajet dans le sens inverse pour aller plus vite
     1636
     1637    // problÚme 2 : Passage au méridien
     1638    // on se situe à quelques secondes de degrés avant le sud par exemple (nb de pas 3995 par exemple)
     1639    // et on franchit le méridien (nb de pas codeur = 5 par exemple)
     1640    // On risque alors de faire un tour complet en sens inverse pour rattraper l'objet -> à éviter
     1641
     1642    // évite de faire des tours complets en Az pour rien...
     1643    while (deltaAz > NBREPASCODEURSAZ) deltaAz -= NBREPASCODEURSAZ;
     1644
     1645    // Doit résoudre tous les problÚmes...
     1646    if (deltaAz > NBREPASCODEURSAZ / 2 )
     1647    {
     1648        deltaAz = NBREPASCODEURSAZ - deltaAz;
     1649        sensAz = 1 - sensAz;
     1650    }
     1651
     1652    //on envoie les coordonnées au driver
     1653
     1654    if (sensAz == 1 )  sensAz='f';
     1655    else sensAz='b';
     1656    if (sensAlt == 1 ) sensAlt='f';
     1657    else sensAlt='b';
     1658
     1659    sprintf(Params, "%c%04i%c%04i", sensAz, deltaAz, sensAlt, deltaAlt);
     1660
     1661    return COMMANDE(numsocket, (char*)"G", Params);
     1662}
     1663
     1664
     1665
     1666/**************************************************************************************
     1667** Les fonctions qui suivent sont nécessaires pour construire un pilote Indi
     1668** Elles sont appelées par le noyau d'Indi
     1669***************************************************************************************/
     1670
     1671/**************************************************************************************
     1672** Initialisation du pilote BAO
     1673***************************************************************************************/
     1674
     1675void ISInit()
     1676{
     1677    //Il ne faut exécuter la fonction qu'une seule fois
     1678    static int isInit = 0;
     1679
     1680    if (isInit) return;
     1681
     1682    if (telescope.get() == 0) telescope.reset(new BAO());
     1683
     1684    isInit = 1;
     1685
     1686    //initialisation du timer
     1687
     1688    IEAddTimer (POLLMS, ISPoll, NULL);
     1689}
     1690
     1691
     1692void ISGetProperties (const char *dev)
     1693{
     1694    ISInit();
     1695
     1696    telescope->ISGetProperties(dev);
     1697}
     1698
     1699void ISNewSwitch (const char *dev, const char *name, ISState *states, char *names[], int n)
     1700{
     1701    ISInit();
     1702    telescope->ISNewSwitch(dev, name, states, names, n);
     1703}
     1704
     1705void ISNewText (const char *dev, const char *name, char *texts[], char *names[], int n)
     1706{
     1707    ISInit();
     1708    telescope->ISNewText(dev, name, texts, names, n);
     1709}
     1710
     1711void ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n)
     1712{
     1713    ISInit();
     1714    telescope->ISNewNumber(dev, name, values, names, n);
     1715}
     1716
     1717void ISNewBLOB (const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[], char *names[], int n)
     1718{
     1719    INDI_UNUSED(dev);
     1720    INDI_UNUSED(name);
     1721    INDI_UNUSED(sizes);
     1722    INDI_UNUSED(blobsizes);
     1723    INDI_UNUSED(blobs);
     1724    INDI_UNUSED(formats);
     1725    INDI_UNUSED(names);
     1726    INDI_UNUSED(n);
     1727}
     1728
     1729void ISSnoopDevice (XMLEle *root)
     1730{
     1731    INDI_UNUSED(root);
     1732}
     1733
     1734void ISPoll (void *p)
     1735{
     1736    INDI_UNUSED(p);
     1737
     1738    telescope->ISPoll();
     1739
     1740    IEAddTimer (POLLMS, ISPoll, NULL);
     1741}
     1742
     1743
    15081744/**************************************************************************************
    15091745**
    15101746***************************************************************************************/
     1747
    15111748int BAO::get_switch_index(ISwitchVectorProperty *sp)
    15121749{
     
    15181755}
    15191756
    1520 /**************************************************************************************
    1521 ** Activation de l'interface
    1522 ***************************************************************************************/
    1523 void BAO::connect_telescope()
    1524 {
    1525     switch (ConnectSP.sp[0].s)
    1526     {
    1527     case ISS_ON:
    1528         ConnectS[0].s = ISS_ON;
    1529         ConnectS[1].s = ISS_OFF;
    1530         IDLog("\nHello BAORadio !\n");
    1531 
    1532         ConnectSP.s = IPS_OK;
    1533         IDSetSwitch (&ConnectSP, "BAORadio is online. Retrieving basic data...");
    1534 
    1535 
    1536         break;
    1537 
    1538     case ISS_OFF:
    1539         ConnectS[0].s = ISS_OFF;
    1540         ConnectS[1].s = ISS_ON;
    1541         ConnectSP.s = IPS_IDLE;
    1542 
    1543         SocketsNumber=1;
    1544         InitThreadOK=false;
    1545 
    1546         for (int i=0; i<MAXHOSTNAME; i++)
    1547         {
    1548             Sockets[i].Connected=false;
    1549             Sockets[i].IP="";
    1550             Sockets[i].new_sock.shutdown();
    1551         }
    1552 
    1553         InitAntennes();
    1554 
    1555         IDSetSwitch (&ConnectSP, "BAORadio is offline.");
    1556         IDLog("Telescope is offline.");
    1557 
    1558         break;
    1559     }
    1560 }
    15611757
    15621758/**************************************************************************************
     
    15661762{
    15671763    //  IDSetNumber (&EquatorialCoordsRNP, NULL);
    1568 
    1569 
    15701764}
    15711765
     
    15881782**
    15891783***************************************************************************************/
    1590 void BAO::enable_simulation(bool enable)
    1591 {
    1592     simulation = enable;
    1593 
    1594     if (simulation)
    1595         IDLog("Warning: Simulation is activated.\n");
    1596     else
    1597         IDLog("Simulation is disabled.\n");
     1784
     1785bool BAO::is_connected()
     1786{
     1787    // return (ConnectSP.sp[0].s == ISS_ON);
     1788    return (ConnectSP.s == IPS_OK);
    15981789}
    15991790
     
    16051796    ConnectSP.s = IPS_IDLE;
    16061797    IDSetSwitch(&ConnectSP, "The connection to the telescope is lost.");
     1798    IDLog("arret");
    16071799    return;
    16081800}
     
    16221814
    16231815/**************************************************************************************
    1624 **  Envoi d'une commande sur le socket puis attente de l'acknowledge
    1625 ***************************************************************************************/
    1626 
    1627 bool BAO::COMMANDE(int numsocket, char* Commande, char* Params)
    1628 {
    1629     char chaine[MAXCARACTERES];
    1630 
    1631     try
    1632     {
    1633         sprintf(chaine, "%s%s\n", Commande, Params);
    1634 
    1635         Sockets[numsocket].new_sock << chaine;
    1636     }
    1637     catch (SocketException& e)
    1638     {
    1639         Sockets[numsocket].new_sock.shutdown();
    1640         Sockets[numsocket].new_sock.create();
    1641         Sockets[numsocket].Connected = Sockets[numsocket].new_sock.connect((std::string)Sockets[numsocket].IP);
    1642 
    1643         if (Sockets[numsocket].Connected)
    1644         {
    1645             Sockets[numsocket].AttenteExecution=0;
    1646             Sockets[numsocket].AnomaliesExecution=0;
    1647         }
    1648 
    1649         //  if (AntennesConnectees() == 0) { InitAntennes(); InitThreadOK=false;}
    1650 
    1651         std::string oss;
    1652         oss="COMMANDE exception : " + e.description() + "\n";
    1653         size_t size = oss.size() + 1;
    1654         char* buffer = new char[size];
    1655         strncpy(buffer, oss.c_str(), size);
    1656 
    1657         IDLog(buffer);
    1658 
    1659         delete [] buffer;
    1660 
    1661         return false;
    1662     }
    1663 
    1664     return true;
    1665 }
    1666 
    1667 
    1668 /**************************************************************************************
    1669 ** Commande POSITION
    1670 ***************************************************************************************/
    1671 
    1672 bool BAO::POSITION(int numsocket)
    1673 {
    1674     return COMMANDE(numsocket, (char*)"P", (char*)"");
    1675 }
    1676 
    1677 /**************************************************************************************
    1678 ** Commande PARK
    1679 ***************************************************************************************/
    1680 
    1681 bool BAO::PARK(int numsocket)
    1682 {
    1683     return COMMANDE(numsocket, (char*)"Z", (char*)"");
    1684 }
    1685 
    1686 /**************************************************************************************
    1687 ** Commande ABORT
    1688 ***************************************************************************************/
    1689 
    1690 bool BAO::ABORT(int numsocket)
    1691 {
    1692     return COMMANDE(numsocket, (char*)"A", (char*)"");
    1693 }
    1694 
    1695 
    1696 /**************************************************************************************
    1697 ** Commande GOTO
    1698 ***************************************************************************************/
    1699 
    1700 bool BAO::GOTO(int numsocket, int deltaAz, int deltaAlt)
    1701 {
    1702     char Params[MAXCARACTERES];
    1703     char sensAz;
    1704     char sensAlt;
    1705 
    1706     sensAlt='b';
    1707     sensAz='b';
    1708 
    1709     if (deltaAz<0)
    1710     {
    1711         deltaAz=-deltaAz;
    1712         sensAz='f';
    1713     }
    1714 
    1715     if (deltaAlt<0)
    1716     {
    1717         deltaAlt=-deltaAlt;
    1718         sensAlt='f';
    1719     }
    1720 
    1721     sprintf(Params, "%c%04i%c%04i", sensAz, deltaAz, sensAlt, deltaAlt);
    1722 
    1723     return COMMANDE(numsocket, (char*)"G", Params);
    1724 }
    1725 
    1726 
    1727 
     1816** GÚre les erreurs de communication avec la boîte Indi
     1817***************************************************************************************/
     1818/*
     1819void BAO::handle_error(INumberVectorProperty *nvp, int err, const char *msg)
     1820{
     1821    nvp->s = IPS_ALERT;
     1822
     1823    // If the error is a time out, then the device doesn't support this property
     1824    if (err == -2)
     1825    {
     1826        nvp->s = IPS_ALERT;
     1827        IDSetNumber(nvp, "Device timed out. Current device may be busy or does not support %s. Will retry again.", msg);
     1828    }
     1829    else
     1830        // Changing property failed, user should retry.
     1831        IDSetNumber( nvp , "%s failed.", msg);
     1832
     1833    fault = true;
     1834}*/
     1835
     1836
     1837/**************************************************************************************
     1838**
     1839***************************************************************************************/
     1840/*
     1841void BAO::correct_fault()
     1842{
     1843    fault = false;
     1844    IDMessage(mydev, "Telescope is online.");
     1845}*/
     1846
     1847
     1848
  • BAORadio/libindi/libindi/drivers/telescope/BAO.h

    r498 r504  
    11/*
    2     LX200 Basic Driver
    3     Copyright (C) 2005 Jasem Mutlaq (mutlaqja@ikarustech.com)
    4 
    5     This library is free software; you can redistribute it and/or
    6     modify it under the terms of the GNU Lesser General Public
    7     License as published by the Free Software Foundation; either
    8     version 2.1 of the License, or (at your option) any later version.
    9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
    18 
     2 Pilote Indi BAORadio
     3 franckrichard033@gmail.com
     4 Juin 2011
    195*/
    206
     
    228#define BAO_H
    239
     10#include <stdio.h>
     11#include <stdlib.h>
     12#include <string.h>
     13#include <stdarg.h>
     14#include <math.h>
     15#include <unistd.h>
     16#include <time.h>
     17#include <memory>
     18#include <pthread.h>
     19#include <iostream>
     20#include <time.h>
     21#include <unistd.h>
     22#include <sys/time.h>
     23
     24#include <config.h>
     25
     26#include "indicom.h"
     27
     28#include "Socket.h"
    2429#include "indidevapi.h"
    2530#include "indicom.h"
     
    2833#include "astro.h"
    2934
     35
    3036#define MAXCARACTERES 1024
    3137
    32 #define MAXATTENTE 80                //Si une commande ne recoit pas d'acknowledge. Alors refaire 80 tentatives en renvoyant la commande
    33 #define MAXANOMALIES 2               //Si pas de réponse au bout de 80 tentatives -> erreur critique -> socket perdu ?
     38#define MAXATTENTE 80                // Si une commande ne recoit pas d'acknowledge. Alors refaire 80 tentatives en renvoyant la commande
     39#define MAXANOMALIES 2               // Si pas de réponse au bout de 80 tentatives -> erreur critique -> socket perdu ?
    3440#define MAXANOMALIESGOTO 1500
     41
     42#define NBREPASCODEURSAZ  4000
     43   
     44
     45using namespace std;
    3546
    3647struct Position
    3748{
    38     int x;
    39     int y;
     49    long int x;
     50    long int y;
    4051};
    4152
    4253struct DefSocket
    4354{
    44     ServerSocket new_sock;
    45    
    46     std::string IP;              //IP de l'antenne
    47    
    48     bool Connected;              //le micro-contrÃŽleur est-il connecté ?
    49     bool PosValides;             //le micro-contrÃŽleur a-t-il donné une position valide ?
    50     char status;                 //status='B' pour busy  'R' pour READY
    51     int sendalertes;             //une requête "send" a généré une erreur sur le réseau
    52     int AttenteExecution;        //L'antenne parvient-elle à executer un cycle de commandes ?
    53     int AnomaliesExecution;      //Erreur critique. L'antenne ne répond plus !
    54                    
    55     Position Pos;                //derniÚre position retournée par le microcontrÃŽleur   
    56     int etape;
    57    
    58     bool ack_status;             //Etat des acknowledges ?
    59     bool ack_pos;
    60     bool ack_park;
    61     bool ack_abort;
    62     bool ack_goto;
    63     bool GotoOk;                 //Est-ce que le dernier goto est OK ?
     55    ServerSocket new_sock;           // socket permettant de gérer la connexion avec une antennes
     56
     57    string IP;                       // IP de l'antenne
     58
     59    bool Connected;                  // le micro-contrÃŽleur est-il connecté ?
     60    bool PosValides;                 // le micro-contrÃŽleur a-t-il donné une position des moteurs valide ?
     61    char status;                     // status='B' pour busy  'R' pour READY
     62    int sendalertes;                 // une requête 'send' a généré une erreur sur le réseau
     63    int AttenteExecution;            // L'antenne parvient-elle à executer un cycle de commandes ?
     64    int AnomaliesExecution;          // Erreur critique. L'antenne ne répond plus !
     65
     66    Position Pos;                    // derniÚre position retournée par le microcontrÃŽleur
     67    int etape;                       //étape dans le cycle de commandes/réponses entre PC et microcontroleurs
     68
     69    bool ack_status;                 // Etat des acknowledges ?
     70    bool ack_pos;                    // le PC a reçu une confirmation du microcont aprÚs un ordre POSITION
     71    bool ack_park;                   // le PC a reçu une confirmation du microcont aprÚs un ordre PARK
     72    bool ack_abort;                  // le PC a reçu une confirmation du microcont aprÚs un ordre ABORT
     73    bool ack_goto;                   // le PC a reçu une confirmation du microcont aprÚs un ordre GOTO
     74    bool GotoOk;                     // Est-ce que le dernier goto est OK ?
    6475};
    6576
    66 ServerSocket server( 8000 );
    67 int SocketsNumber;
    68 bool InitThreadOK;
    69 DefSocket Sockets[MAXHOSTNAME + 1];
    70 pthread_t th1;
     77
     78ServerSocket server( 8000 );         // Le PC et les antennes communiquent par le biais du port 8000 sur le réseau tcp
    7179
    7280class BAO : public Astro
     
    7583    BAO();
    7684    ~BAO();
    77    
     85
    7886    void ISGetProperties (const char *dev);
    7987    void ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n);
     
    8189    void ISNewSwitch (const char *dev, const char *name, ISState *states, char *names[], int n);
    8290    void ISPoll ();
    83     void InitThread();
    84  
     91
     92    void *pThreadSocket ();
     93    void *pThreadExit ();
     94
    8595    bool COMMANDE(int numsocket, char* Commande, char* Params);
    86     Position ExtractPosition(std::string str);
    87  
     96    bool ExtractPosition(string str, Position *result);
     97
    8898    void connection_lost();
    8999    void connection_resumed();
    90    
     100
    91101    bool STATUS(int numsocket);
    92102    bool POSITION(int numsocket);
     
    96106    void ADDEC2Motor(double newRA, double newDEC);
    97107    int  AntennesConnectees();
     108    void DeconnecterSocket(int num);
    98109    void InitAntennes();
    99    
    100        
    101    
     110
     111    /*******************************************************/
     112    /* Connection Routines
     113    ********************************************************/
     114    void init_properties();
     115    void get_initial_data();
     116    void connect_telescope();
     117    bool is_connected(void);
     118
     119    /*******************************************************/
     120    /* Misc routines
     121    ********************************************************/
     122    bool process_coords();
     123    int get_switch_index(ISwitchVectorProperty *sp);
     124
     125    /*******************************************************/
     126    /* Simulation Routines
     127    ********************************************************/
     128    void enable_simulation(bool enable);
     129
     130    /*******************************************************/
     131    /* Error handling routines
     132    ********************************************************/
     133    void slew_error(int slewCode);
     134    void reset_all_properties();
     135    void handle_error(INumberVectorProperty *nvp, int err, const char *msg);
     136    void correct_fault();
     137
     138
     139
    102140private:
    103141
     
    120158    INumber ActualisationN1[1];
    121159    INumber ActualisationN2[1];
    122    
     160
    123161    //INumber SlewAccuracyN[2];
    124162    //INumber TrackAccuracyN[2];
     
    138176    INumberVectorProperty ActualisationNP1;
    139177    INumberVectorProperty ActualisationNP2;
    140    
     178
    141179
    142180    /* Text Vectors */
     
    144182    ITextVectorProperty ObjectTP;
    145183
    146     /*******************************************************/
    147     /* Connection Routines
    148     ********************************************************/
    149     void init_properties();
    150     void get_initial_data();
    151     void connect_telescope();
    152     bool is_connected(void);
    153 
    154     /*******************************************************/
    155     /* Misc routines
    156     ********************************************************/
    157     bool process_coords();
    158     int get_switch_index(ISwitchVectorProperty *sp);
    159 
    160     /*******************************************************/
    161     /* Simulation Routines
    162     ********************************************************/
    163     void enable_simulation(bool enable);
    164 
    165     /*******************************************************/
    166     /* Error handling routines
    167     ********************************************************/
    168     void slew_error(int slewCode);
    169     void reset_all_properties();
    170     void handle_error(INumberVectorProperty *nvp, int err, const char *msg);
    171     void correct_fault();
     184
    172185
    173186protected:
    174 
    175     double JD;                          /* Julian Date */
    176     double lastRA;
     187    int SocketsNumber;                   // nbre de sockets utilisés pour connecter les antennes
     188    bool InitThreadOK;                   // Le thread est bien actif
     189    DefSocket Sockets[MAXHOSTNAME + 1];  // Etat de chaque socket. Un socket permet la communication avec une antenne
     190    pthread_t th1;                       // le pointeur du thread
     191
     192    double JD;                           // Jour julien
     193    double lastRA;                       // Sauvegarde de la derniÚre position avant actualisation
    177194    double lastDEC;
    178     double JJAnc;                       // Sauvegarde du jour julien de la derniÚre actualisation de la position (fct Goto)
    179     double ActualisationTM1;
     195    double JJAnc;                        // Sauvegarde du jour julien lors de la derniÚre actualisation de la position (fct Goto)
     196    double ActualisationTM1;             // Délais entre deux actualisations dans les modes transit et tracking
    180197    double ActualisationTM2;
    181     bool   simulation;
    182     bool   fault;
    183     bool   LecturePosition;             // étape dans le processus d'actualisation de la position
    184     bool   Abort;
    185     bool   Park;
    186     bool   Goto;
    187     bool   BAOConnected;
    188     bool   LastGotoOK;
    189    
    190     int    fd;                          /* Telescope tty file descriptor */
    191     int    currentSet;
    192     int    lastSet;
    193     int    TrackingMode;                //1 : Transit           2: Tracking
    194      
    195     Position TargetPosition;            //Position à atteindre en coordonnées équatoriales
     198    double Longitude;                    // Longitude et latitude du lieu d'observation
     199    double Latitude;
     200    bool   ActualisationPosition;        // Permet de faire les étapes nécessaires pour réaliser un mouvement
     201    bool   Abort;                        // Annulation du mouvement en cours
     202    bool   Park;                         // On place les antennes dans une position de repos
     203    bool   Suivi;                        // Suivi d'un objet en cours...
     204    bool   UpdateGoto;                   // On peut exécuter un Goto
     205    bool   Exit;                         // On ferme le driver
     206
     207    int    currentSet;                   // Variable interne de l'interface indi
     208    int    lastSet;                      // Variable interne de l'interface indi
     209    int    TrackingMode;                 //1 : Transit           2: Tracking
     210
     211    Position TargetPosition;             //Position à atteindre en coordonnées équatoriales
    196212};
    197213
  • BAORadio/libindi/libindi/drivers/telescope/astro.cpp

    r490 r504  
     1////////////////////////////////
     2// Classe Astro               //
     3// Franck RICHARD             //
     4// franckrichard033@gmail.com //
     5// BAORadio                   //
     6// juin 2011                  //
     7////////////////////////////////
     8
     9
    110#include "astro.h"
    211
    3 ////////////////////
    4 // Routines Astro //
    5 ////////////////////
     12
     13/**************************************************************************************
     14** Constructeur de la classe Astro
     15***************************************************************************************/
    616
    717Astro::Astro()
    818{
    9     Longitude=0.0;
    10     Latitude=0.0;
    11     Lst=0.0;
    12     JJ=0.0;
    13     CorP=0.0;
    14     CorEP=0.0;
    15     Annee=0.0;
    16     Mois=0.0;
    17     Jour=0.0;
    18     Heu=0.0;
    19     Min=0.0;
    20     Sec=0.0;
    21     ep=0.0;
    22     hs=0.0;
    23     UTCP=0.0;
    24     tsl=0.0;
     19    //Initialisation des variables
     20   
     21    Longitude = 0.0;                     // Cordonnées du lieu d'observation
     22    Latitude  = 0.0;
     23   
     24    Annee     = 0.0;                     // Date et heure de l'observation
     25    Mois      = 0.0;
     26    Jour      = 0.0;
     27    Heure     = 0.0;
     28    Min       = 0.0;
     29    Sec       = 0.0;
     30    UTCP      = 0.0;                     // permet de gérer le fuseau horaire
     31                                         // mais semble inutile sous Linux
     32   
     33    hs        = 0.0;                     // fraction du jour en cours hs=(heure+min/60+secs/3600)/24.
     34    ep        = 0.0;                     // obliquité de l'écliptique
     35    tsl       = 0.0;                     // temps sidéral local
     36    JJ        = 0.0;                     // Jour Julien
     37   
     38    CorP      = 0.0;                     // Nutation en longitude
     39    CorEP     = 0.0;                     // Nutation en inclinaison
     40     
     41    LongitudeSoleil = 0.0;
    2542}
    2643
     
    3047
    3148
    32 //0<=Angle<=2*PI
     49/**************************************************************************************
     50** Initialisation des variables globales de la classe Astro
     51***************************************************************************************/
     52
     53void Astro::DefinirDateHeure(double A, double M, double J, double H, double Mi, double S)
     54{
     55    Annee = A;
     56    Mois = M;
     57    Jour = J;
     58    Heure = H;
     59    Min = Mi;
     60    Sec = S;
     61}
     62
     63void Astro::DefinirPressionTemp(double P, double T)
     64{
     65    Pression = P;
     66    Temp = T;
     67}
     68
     69void Astro::DefinirLongitudeLatitude(double log, double lat)
     70{
     71    Longitude = log;
     72    Latitude = lat;
     73}
     74
     75
     76
     77/**************************************************************************************
     78** ParamÚtre : angle en radians
     79** retourne angle dans un intervalle 0 <= Angle <= 2*PI
     80***************************************************************************************/
     81
    3382double Astro::VerifAngle(double Angle)
    3483{
     
    4089
    4190
    42 //////////////////////////////////////////////////////////////////////
    43 //Nutation
     91
     92/**************************************************************************************
     93** retourne l'arrondi du nombre donné en paramÚtre
     94** Exemples: Arrondi(5.7) =  6
     95**           Arrondi(-5.7)= -6
     96***************************************************************************************/
     97
     98double Astro::Arrondi(double a)
     99{
     100    double b;
     101
     102    if (a>=0.0)
     103    {
     104        b=a-floor(a);
     105        if (b>=0.5) return ceil(a);
     106        else return floor(a);
     107    }
     108    else
     109    {
     110        b=ceil(a)-a;
     111        if (b>=0.5) return floor(a);
     112        else return ceil(a);
     113    }
     114}
     115
     116
     117
     118/**************************************************************************************
     119** converti un angle (exprimé en degrés) dans le format hh:mm:ss ou deg:mm:ss
     120** selon la valeur de HMS
     121***************************************************************************************/
     122
     123string Astro::DHMS(double mema, bool HMS)
     124{
     125    double d, m, s, a;
     126
     127    a=mema;
     128
     129    if (HMS) a=a / 15.0;
     130    a=fabs(a * 3600.0);
     131    s=Arrondi(fmod(a, 60.0) * 10.0) / 10.0;
     132    a=floor(a / 60.0);
     133    m=fmod(a, 60.0);
     134    d=floor(a / 60.0);
     135
     136    if (s == 60.0)
     137    {
     138        s=0.0;
     139        m+=1.0;
     140        if (m==60.0)
     141        {
     142            m=0.0;
     143            d+=1.0;
     144
     145            if (HMS && d>23.0) d=0.0;
     146        }
     147    }
     148
     149    stringstream strsTemp;
     150
     151    if (mema < 0) strsTemp << '-';
     152
     153    strsTemp << setfill('0') << setw(2) << d << ":" << m << ":" << s;
     154
     155    return (strsTemp.str());
     156}
     157
     158
     159/**************************************************************************************
     160** Calcul de la longitude du Soleil
     161** La quantité PS n'est pas indispensable. Elle permet d'améliorer la précision
     162***************************************************************************************/
     163
     164double Astro::CalculLongitudeSoleil()
     165{
     166    double T = (JJ - 2415020.0) / 36525.0;
     167
     168    double A = 153.23 + 22518.7541 * T;
     169    double B = 216.57 + 44037.5082 * T;
     170    double C = 312.69 + 32964.3577 * T;
     171    double D = 350.74 + ( 445267.1142 - 0.00144 * T ) * T;
     172    double E = 231.19 + 20.2 * T;
     173
     174
     175    double L = 279.69668 + ( 36000.76892 + 0.0003025 * T ) * T;
     176    double M = 358.47583 + (((( -0.0000033 * T) -0.00015 )  * T ) + 35999.04975 ) * T;
     177
     178    double CC =   (1.919460 + ((-0.000014 * T) - 0.004789 ) * T ) * sin(M * Pidiv180)
     179                  + (0.020094 - 0.0001 * T) * sin(2.0 * M * Pidiv180)
     180                  + 0.000293 * sin(3.0 * M * Pidiv180);
     181
     182    double PS =  0.00134 * cos(A * Pidiv180)
     183                +0.00154 * cos(B * Pidiv180)
     184                +0.00200 * cos(C * Pidiv180)
     185                +0.00179 * sin(D * Pidiv180)
     186                +0.00178 * sin(E * Pidiv180);
     187
     188
     189    double LS = VerifAngle( (L + CC + PS) * Pidiv180);
     190   
     191    return LS;
     192}
     193
     194
     195
     196/**************************************************************************************
     197** Calcul de l'AD et la déclinaison du Soleil
     198** indispensable pour exécuter la commande "goto sun"
     199***************************************************************************************/
     200
     201void Astro::CalculARDecSoleil(Coordonnees *Soleil)
     202{
     203    double ar;
     204    double de;
     205   
     206    ar = atan( cos(ep) * sin(LongitudeSoleil) / cos(LongitudeSoleil));
     207   
     208    if ( cos(LongitudeSoleil) < 0.0) ar += Pi;
     209   
     210    de = asin( sin(ep) * sin(LongitudeSoleil));
     211
     212    Soleil->ar = DHMS( VerifAngle(ar) * N180divPi, true );
     213   
     214    Soleil->dec = DHMS( de * N180divPi, false );
     215}
     216   
     217
     218
     219
     220/**************************************************************************************
     221** Calcul de la nutation en longitude et en inclinaison
     222** Nécessaire pour calculer la position apparente d'un objet (étoile, galaxie etc...)
     223***************************************************************************************/
    44224
    45225void Astro::Nutation()
    46226{
    47     double T,L,LP,M,MP,O,L2,LP2,O2;
    48 
    49     T=(JJ-2415020.0)/36525.0;
    50 
    51     L=(279.6967+(36000.7689+0.000303*T)*T)*Pidiv180;
    52     LP=(270.4342+(481267.8831-0.001133*T)*T)*Pidiv180;
    53     M=(358.4758+(35999.0498-0.000150*T)*T)*Pidiv180;
    54     MP=(296.1046+(477198.8491+0.009192*T)*T)*Pidiv180;
    55     O=(259.1833+(-1934.1420+0.002078*T)*T)*Pidiv180;
    56 
    57     L2=2.0*L;
    58     LP2=2.0*LP;
    59     O2=2.0*O;
    60 
    61     CorP=-(17.2327+0.01737*T)*sin(O)
    62          -(1.2729+0.00013*T)*sin(L2)
    63          +0.2088*sin(O2)
    64          -0.2037*sin(LP2)
    65          +(0.1261-0.00031*T)*sin(M)
    66          +0.0675*sin(MP)
    67          -(0.0497-0.00012*T)*sin(L2+M)
    68          -0.0342*sin(LP2-O)
    69          -0.0261*sin(LP2+MP)
    70          +0.0214*sin(L2-M)
    71          -0.0149*sin(L2-LP2+MP)
    72          +0.0124*sin(L2-O)
    73          +0.0114*sin(LP2-MP);
    74 
    75     CorEP=(9.2100+0.00091*T)*cos(O)
    76           +(0.5522-0.00029*T)*cos(L2)
    77           -0.0904*cos(O2)
    78           +0.0884*cos(LP2)
    79           +0.0216*cos(L2+M)
    80           +0.0183*cos(LP2-O)
    81           +0.0113*cos(LP2+MP)
    82           -0.0093*cos(L2-M)
    83           -0.0066*cos(L2-O);
    84 
    85     CorP=CorP/3600.0*Pidiv180;
    86     CorEP=CorEP/3600.0*Pidiv180;
    87 }
    88 
    89 
    90 //////////////////////////////////////////////////////////////////////
    91 // calcul Jour julien
     227    double T = (JJ-2415020.0) / 36525.0;
     228
     229    double L  = (279.6967 + (36000.7689 + 0.000303 * T ) * T ) * Pidiv180;
     230    double LP = (270.4342 + (481267.8831 - 0.001133 * T ) * T ) * Pidiv180;
     231    double M  = (358.4758 + (35999.0498 - 0.000150 * T ) * T ) * Pidiv180;
     232    double MP = (296.1046 + (477198.8491 + 0.009192 * T ) * T ) * Pidiv180;
     233    double O  = (259.1833 + (-1934.1420 + 0.002078 * T ) * T ) * Pidiv180;
     234
     235    double L2  = 2.0 * L;
     236    double LP2 = 2.0 * LP;
     237    double O2  = 2.0 * O;
     238   
     239    // Nutation en longitude
     240
     241    CorP = -(17.2327 + 0.01737 * T) * sin(O)
     242           -(1.2729+0.00013 * T) * sin(L2)
     243           +0.2088 * sin(O2)
     244           -0.2037 * sin(LP2)
     245           +(0.1261 - 0.00031 * T) * sin(M)
     246           +0.0675 * sin(MP)
     247           -(0.0497 - 0.00012 * T) * sin(L2 + M)
     248           -0.0342 * sin(LP2 - O)
     249           -0.0261 * sin(LP2 + MP)
     250           +0.0214 * sin(L2 - M)
     251           -0.0149 * sin(L2 - LP2 + MP)
     252           +0.0124 * sin(L2 - O)
     253           +0.0114 * sin(LP2 - MP);
     254           
     255    //Nutation en inclinaison
     256
     257    CorEP = (9.2100 + 0.00091 * T) * cos(O)
     258            +(0.5522 - 0.00029 * T) * cos(L2)
     259            -0.0904 * cos(O2)
     260            +0.0884 * cos(LP2)
     261            +0.0216 * cos(L2+M)
     262            +0.0183 * cos(LP2-O)
     263            +0.0113 * cos(LP2+MP)
     264            -0.0093 * cos(L2-M)
     265            -0.0066 * cos(L2-O);
     266
     267    CorP  = CorP / 3600.0 * Pidiv180;
     268    CorEP = CorEP / 3600.0 * Pidiv180;
     269}
     270
     271
     272
     273/**************************************************************************************
     274** Nutation des étoiles - on utilise les quantités calculées précédemment
     275** ar et de sont exprimés en radians
     276***************************************************************************************/
     277
     278void Astro::NutationEtoile(double *ar, double *de)
     279{
     280    double a = (cos(ep) + sin(ep) * sin(*ar) * tan(*de)) * CorP - (cos(*ar) * tan(*de)) * CorEP;
     281    double b = (sin(ep) * cos(*ar)) * CorP + sin(*ar) * CorEP;
     282
     283    *ar = VerifAngle(*ar+a);
     284    *de += b;
     285}
     286
     287
     288/**************************************************************************************
     289** Précession des équinoxes
     290** ar et de sont exprimés en radians
     291***************************************************************************************/
     292
     293void Astro::Precession(double *ar, double *de)
     294{
     295    double t = (JJ - 2451544.5) / 36524.2199;
     296
     297    double ze = ((((0.018 * t) + 0.302) * t + 2304.948) * t) / 3600.0 * Pidiv180;
     298    double z = ((((0.019 * t) + 1.093) * t + 2304.948) * t) / 3600.0 * Pidiv180;
     299    double delta = ((((-0.042 * t) - 0.426) * t + 2004.255) * t) / 3600.0 * Pidiv180;
     300
     301
     302    double A = cos(*de) * sin(*ar + ze);
     303    double B = cos(delta) * cos(*de) * cos (*ar + ze) - sin(delta) * sin(*de);
     304    double C = sin(delta) * cos(*de) * cos (*ar + ze) + cos(delta) * sin(*de);
     305
     306    double AMZ = atan(A / B);
     307
     308    if (B<0.0) AMZ += Pi;
     309
     310    *ar=VerifAngle(AMZ + z);
     311    *de=asin(C);
     312}
     313
     314
     315
     316/**************************************************************************************
     317** Obliquité
     318** calcul de l'inclinaison de l'axe terrestre par rapport à au plan de l'écliptique
     319** Quantité indispensable pour calculer le temps sidéral local et les coordonnées
     320** horaires du soleil
     321***************************************************************************************/
     322
     323void Astro::Obliquite(double JJ)
     324{
     325    double T;
     326
     327    T = (JJ - 2415020.0) / 36525.0;
     328
     329    ep = (23.452294+ (((0.000000503 * T ) - 0.00000164 ) * T - 0.0130125 ) * T ) * Pidiv180;
     330}
     331
     332
     333
     334
     335/**************************************************************************************
     336** Aberration annuelle des étoiles
     337** ar et de sont exprimés en radians
     338***************************************************************************************/
     339
     340void Astro::AberrationAnnuelle(double *ar, double *de)
     341{
     342    double c = -20.49 / 3600.0 * Pidiv180;
     343    double a = c * ( cos(*ar) * cos(LongitudeSoleil) * cos(ep)
     344                     + sin(*ar) * sin(LongitudeSoleil)
     345                   ) / cos(*de);
     346
     347    double b = c * ( cos(LongitudeSoleil) * cos(ep) * (tan(ep) * cos(*de) - sin(*ar) * sin(*de))
     348                     + cos(*ar) * sin(*de) * sin(LongitudeSoleil));
     349
     350    *ar = VerifAngle(*ar + a);
     351    *de += b;
     352}
     353
     354
     355/**************************************************************************************
     356** calcul Jour julien
     357***************************************************************************************/
    92358
    93359void Astro::CalculJJ(double Heure)
    94360{
    95 
     361    JJ = CalculJJ(Annee, Mois, Jour, Heure);   
     362}
     363
     364double Astro::CalculJJ(double A, double M, double J, double Heure)
     365{
    96366    long y, a, b, c, e, m;
    97367
    98     long year = (long)Annee;
    99     int month = (int)Mois;
    100     double day = Jour + Heure;
    101 
     368    long year = (long)A;
     369    int month = (int)M;
     370    double day = J + Heure;
    102371
    103372    y = year + 4800;
     
    131400
    132401gregor:
    133         b = (a/4) - a;
     402        b = (a / 4) - a;
    134403    }
    135404
    136     c = (36525L * y)/100;
    137 
    138     JJ = b + c + e + day - 32167.5;
    139 }
    140 
    141 
    142 ///////////////////////////////////////////////////////////////////////
    143 //Obliquité
    144 
    145 void Astro::Obliquite(double JJ)
    146 {
    147     double T;
    148 
    149     T = (JJ-2415020.0) / 36525.0;
    150 
    151     ep = (23.452294+ (((0.000000503 * T ) - 0.00000164 ) * T - 0.0130125 ) * T ) * Pidiv180;
    152 }
    153 
    154 ///////////////////////////////////////////////////////////////////////
    155 //Temps sidéral local
     405    c = (36525L * y) / 100;
     406   
     407    return b + c + e + day - 32167.5;
     408}
     409
     410
     411
     412/**************************************************************************************
     413** Temps sidéral local
     414***************************************************************************************/
    156415
    157416double Astro::TSL(double JJ, double HeureSiderale, double Longitude)
    158417{
    159     double rd,T;
    160 
    161     T = (JJ - 2415020.0 ) / 36525.0;
    162     rd = 0.276919398 + ( 100.0021359 + 0.000001075 * T ) * T;
     418    double T = (JJ - 2415020.0 ) / 36525.0;
     419    double rd = 0.276919398 + ( 100.0021359 + 0.000001075 * T ) * T;
    163420    rd += HeureSiderale;
    164421    rd *= Pi2;
     422    // temps sidéral apparent
    165423    rd += CorP * cos(ep);
    166424    rd -= Longitude;
     
    170428
    171429
     430/**************************************************************************************
     431** routine principale des calculs
     432***************************************************************************************/
     433
    172434void Astro::CalculTSL()
    173435{
    174     hs=(Heu+Min/60.0+Sec/3600.0)/24.0;
    175 
    176     hs-=UTCP/24.0;
     436    hs = (Heure + Min / 60.0 + Sec / 3600.0) / 24.0;
     437
     438    hs -= UTCP / 24.0;
    177439
    178440    CalculJJ(hs);
     
    182444    Nutation();
    183445
    184     tsl=TSL(JJ, hs, Longitude);
    185 }
    186 
    187 
    188 ///////////////////////////////////////////////////////////////////////
    189 //Azimut et hauteur à partir de AR et Dec
    190 
    191 void Astro::Azimut(double ts, double Latitude, double Ar, double De, double *azi, double *hau)
    192 {
    193     double ah, ht, a1, az, zc, ac;
    194 
    195     ah=ts-Ar;
    196 
    197     zc=sin(Latitude)*sin(De)+cos(Latitude)*cos(De)*cos(ah);
    198     ht=atan(zc/sqrt((-zc*zc)+1.0));
    199 
    200     a1=cos(De)*sin(ah)/cos(ht);
    201     ac=(-cos(Latitude)*sin(De)+sin(Latitude)*cos(De)*cos(ah))/cos(ht);
    202     az=atan(a1/sqrt((-a1*a1)+1.0));
     446    tsl = TSL(JJ, hs, Longitude);
     447
     448    LongitudeSoleil = CalculLongitudeSoleil();
     449}
     450
     451
     452
     453/**************************************************************************************
     454** Calcule la hauteur et l'azimut des étoiles en fct du lieu d'observation
     455***************************************************************************************/
     456
     457void Astro::Azimut(double Ar, double De, double *azi, double *hau)
     458{
     459    double ah = tsl - Ar;
     460
     461    double zc = sin(Latitude) * sin(De) + cos(Latitude) * cos(De) * cos(ah);
     462    double ht = atan(zc / sqrt((-zc * zc) + 1.0));
     463
     464    double a1 = cos(De) * sin(ah) / cos(ht);
     465    double ac = (-cos(Latitude) * sin(De) + sin(Latitude) * cos(De) * cos(ah)) / cos(ht);
     466    double az = atan(a1 / sqrt((-a1*a1)+1.0));
     467
    203468    if (ac<0.0) az=Pi-az;
    204469
    205     az=VerifAngle(Pi+az);
    206 
    207     *azi=az;
     470    *azi=VerifAngle(Pi+az);
    208471    *hau=ht;
    209472}
    210473
     474
     475/**************************************************************************************
     476** réfraction atmosphérique : formule simple de Jean Meeus
     477** la hauteur ht est exprimée en radians
     478***************************************************************************************/
     479
     480double Astro::RefractionAtmospherique(double ht)
     481{
     482    double gamma, R0, a, b, PressionTempCalc, tanHT;
     483
     484    if (Pression!=0.0)
     485    {
     486        PressionTempCalc = (Pression / 1013.25) * 273.0 / (273.0 + Temp);
     487
     488        if (ht <= 15.0 * Pidiv180)
     489        {
     490            gamma = 2.6;
     491            a = 7.5262;
     492            b = -2.2204;
     493
     494            if (ht >= 4.0 * Pidiv180)
     495            {
     496                gamma=-1.1;
     497                a=4.4010;
     498                b=-0.9603;
     499            }
     500
     501            R0 = (pow((a+b*log(ht*N180divPi+gamma)), 2.0)) / 60.0 * Pidiv180;
     502            ht += R0 * PressionTempCalc;
     503        }
     504        else
     505        {
     506            tanHT = fabs(tan(Pidiv2 - ht));
     507            R0 = (0.0161877777777777777777-0.000022888888888888888 * tanHT * tanHT)
     508                 * tanHT * Pidiv180;
     509            ht += R0 * PressionTempCalc;
     510        }
     511    }
     512
     513    return ht;
     514}
     515
     516
     517
     518
     519double Astro::slaDrange(double angle )
     520{
     521    return fmod(angle, Pi);
     522}
     523
     524float  Astro::slaRange(float angle )
     525{
     526    return fmodf(angle, Pi);
     527}
     528
     529void Astro::slaRefro ( double zobs, double hm, double tdk, double pmb,
     530                       double rh, double wl, double phi, double tlr,
     531                       double eps, double *ref )
     532/*
     533**  - - - - - - - - -
     534**   s l a R e f r o
     535**  - - - - - - - - -
     536**
     537**  Atmospheric refraction for radio and optical wavelengths.
     538**
     539**  Given:
     540**    zobs    double  observed zenith distance of the source (radian)
     541**    hm      double  height of the observer above sea level (metre)
     542**    tdk     double  ambient temperature at the observer (deg K)
     543**    pmb     double  pressure at the observer (millibar)
     544**    rh      double  relative humidity at the observer (range 0-1)
     545**    wl      double  effective wavelength of the source (micrometre)
     546**    phi     double  latitude of the observer (radian, astronomical)
     547**    tlr     double  temperature lapse rate in the troposphere (degK/met
     548**    eps     double  precision required to terminate iteration (radian)
     549**
     550**  Returned:
     551**    ref     double  refraction: in vacuo ZD minus observed ZD (radian)
     552**
     553**  Notes:
     554**
     555**  1  A suggested value for the tlr argument is 0.0065D0.  The
     556**     refraction is significantly affected by tlr, and if studies
     557**     of the local atmosphere have been carried out a better tlr
     558**     value may be available.
     559**
     560**  2  A suggested value for the eps argument is 1e-8.  The result is
     561**     usually at least two orders of magnitude more computationally
     562**     precise than the supplied eps value.
     563**
     564**  3  The routine computes the refraction for zenith distances up
     565**     to and a little beyond 90 deg using the method of Hohenkerk
     566**     and Sinclair (NAO Technical Notes 59 and 63, subsequently adopted
     567**     in the Explanatory Supplement, 1992 edition - see section 3.281).
     568**
     569**  4  The C code is an adaptation of the Fortran optical refraction
     570**     subroutine AREF of C.Hohenkerk (HMNAO, September 1984), with
     571**     extensions to support the radio case.  The following modifications
     572**     to the original HMNAO optical refraction algorithm have been made:
     573**
     574**     .  The angle arguments have been changed to radians.
     575**
     576**     .  Any value of zobs is allowed (see note 6, below).
     577**
     578**     .  Other argument values have been limited to safe values.
     579**
     580**     .  Murray's values for the gas constants have been used
     581**        (Vectorial Astrometry, Adam Hilger, 1983).
     582**
     583**     .  The numerical integration phase has been rearranged for
     584**        extra clarity.
     585**
     586**     .  A better model for Ps(T) has been adopted (taken from
     587**        Gill, Atmosphere-Ocean Dynamics, Academic Press, 1982).
     588**
     589**     .  More accurate expressions for Pwo have been adopted
     590**        (again from Gill 1982).
     591**
     592**     .  Provision for radio wavelengths has been added using
     593**        expressions devised by A.T.Sinclair, RGO (private
     594**        communication 1989), based on the Essen & Froome
     595**        refractivity formula adopted in Resolution 1 of the
     596**        13th International Geodesy Association General Assembly
     597**        (Bulletin Geodesique 1963 p390).
     598**
     599**     .  Various small changes have been made to gain speed.
     600**
     601**     None of the changes significantly affects the optical results
     602**     with respect to the algorithm given in the 1992 Explanatory
     603**     Supplement.  For example, at 70 deg zenith distance the present
     604**     routine agrees with the ES algorithm to better than 0.05 arcsec
     605**     for any reasonable combination of parameters.  However, the
     606**     improved water-vapour expressions do make a significant difference
     607**     in the radio band, at 70 deg zenith distance reaching almost
     608**     4 arcsec for a hot, humid, low-altitude site during a period of
     609**     low pressure.
     610**
     611**  5  The radio refraction is chosen by specifying wl > 100 micrometres.
     612**     Because the algorithm takes no account of the ionosphere, the
     613**     accuracy deteriorates at low frequencies, below about 30 MHz.
     614**
     615**  6  Before use, the value of zobs is expressed in the range +/- pi.
     616**     If this ranged zobs is -ve, the result ref is computed from its
     617**     absolute value before being made -ve to match.  In addition, if
     618**     it has an absolute value greater than 93 deg, a fixed ref value
     619**     equal to the result for zobs = 93 deg is returned, appropriately
     620**     signed.
     621**
     622**  7  As in the original Hohenkerk and Sinclair algorithm, fixed values
     623**     of the water vapour polytrope exponent, the height of the
     624**     tropopause, and the height at which refraction is negligible are
     625**     used.
     626**
     627**  8  The radio refraction has been tested against work done by
     628**     Iain Coulson, JACH, (private communication 1995) for the
     629**     James Clerk Maxwell Telescope, Mauna Kea.  For typical conditions,
     630**     agreement at the 0.1 arcsec level is achieved for moderate ZD,
     631**     worsening to perhaps 0.5-1.0 arcsec at ZD 80 deg.  At hot and
     632**     humid sea-level sites the accuracy will not be as good.
     633**
     634**  9  It should be noted that the relative humidity rh is formally
     635**     defined in terms of "mixing ratio" rather than pressures or
     636**     densities as is often stated.  It is the mass of water per unit
     637**     mass of dry air divided by that for saturated air at the same
     638**     temperature and pressure (see Gill 1982).
     639**
     640**  Called:  slaDrange, atmt, atms
     641**
     642**  Defined in slamac.h:  TRUE, FALSE
     643**
     644**  Last revision:   30 January 1997
     645**
     646**  Copyright P.T.Wallace.  All rights reserved.
     647*/
     648{
     649    /* Fixed parameters */
     650
     651    static double d93 = 1.623156204; /* 93 degrees in radians        */
     652    static double gcr = 8314.32;     /* Universal gas constant       */
     653    static double dmd = 28.9644;     /* Molecular weight of dry air  */
     654    static double dmw = 18.0152;     /* Molecular weight of water
     655                                                             vapour */
     656    static double s = 6378120.0;     /* Mean Earth radius (metre)    */
     657    static double delta = 18.36;     /* Exponent of temperature
     658                                         dependence of water vapour
     659                                                           pressure */
     660    static double ht = 11000.0;      /* Height of tropopause (metre) */
     661    static double hs = 80000.0;      /* Upper limit for refractive
     662                                                    effects (metre) */
     663
     664    /* Variables used when calling the internal routine atmt */
     665    double robs;   /* height of observer from centre of Earth (metre) */
     666    double tdkok;  /* temperature at the observer (deg K) */
     667    double alpha;  /* alpha          |        */
     668    double gamm2;  /* gamma minus 2  | see ES */
     669    double delm2;  /* delta minus 2  |        */
     670    double c1,c2,c3,c4,c5,c6;  /* various */
     671
     672    /* Variables used when calling the internal routine atms */
     673    double rt;     /* height of tropopause from centre of Earth (metre) */
     674    double tt;     /* temperature at the tropopause (deg k) */
     675    double dnt;    /* refractive index at the tropopause */
     676    double gamal;  /* constant of the atmospheric model = g*md/r */
     677
     678    int is, k, n, i, j, optic;
     679    double zobs1, zobs2, hmok, pmbok, rhok, wlok, tol, wlsq, gb,
     680    a, gamma, tdc, psat, pwo, w, tempo, dn0, rdndr0, sk0,
     681    f0, rdndrt, zt, ft, dnts, rdndrp, zts, fts, rs,
     682    dns, rdndrs, zs, fs, refold, z0, zrange, fb, ff, fo,
     683    fe, h, r, sz, rg, dr, tg, dn, rdndr, t, f, refp, reft;
     684
     685    /* The refraction integrand */
     686#define refi(R,DN,RDNDR) ((RDNDR)/(DN+RDNDR));
     687
     688
     689
     690    /* Transform zobs into the normal range */
     691    zobs1 = slaDrange ( zobs );
     692    zobs2 = fabs ( zobs1 );
     693    zobs2 = gmin ( zobs2, d93 );
     694
     695    /* Keep other arguments within safe bounds */
     696    hmok = gmax ( hm, -1000.0 );
     697    hmok = gmin ( hmok, 10000.0 );
     698    tdkok = gmax ( tdk, 100.0 );
     699    tdkok = gmin ( tdkok, 500.0 );
     700    pmbok = gmax ( pmb, 0.0 );
     701    pmbok = gmin ( pmbok, 10000.0 );
     702    rhok  = gmax ( rh, 0.0 );
     703    rhok  = gmin ( rhok, 1.0 );
     704    wlok  = gmax ( wl, 0.1 );
     705    alpha = fabs ( tlr );
     706    alpha = gmax ( alpha, 0.001 );
     707    alpha = gmin ( alpha, 0.01 );
     708
     709    /* Tolerance for iteration */
     710    w = fabs ( eps );
     711    tol = gmin ( w, 0.1 ) / 2.0;
     712
     713    /* Decide whether optical or radio case - switch at 100 micron */
     714    optic = ( wlok <= 100.0 );
     715
     716    /* Set up model atmosphere parameters defined at the observer */
     717    wlsq = wlok * wlok;
     718    gb = 9.784 * ( 1.0 - 0.0026 * cos ( 2.0 * phi ) - 2.8e-7 * hmok );
     719    a = ( optic ) ?
     720        ( ( 287.604 + 1.6288 / wlsq + 0.0136 / ( wlsq * wlsq ) )
     721          * 273.15 / 1013.25 ) * 1e-6
     722        :
     723        77.624e-6;
     724    gamal = gb * dmd / gcr;
     725    gamma = gamal / alpha;
     726    gamm2 = gamma - 2.0;
     727    delm2 = delta - 2.0;
     728    tdc = tdkok - 273.15;
     729    psat = pow ( 10.0, ( 0.7859 + 0.03477 * tdc ) /
     730                 ( 1.0 + 0.00412 * tdc ) ) *
     731           ( 1.0 + pmbok * ( 4.5e-6 + 6e-10 * tdc * tdc ) );
     732    pwo = ( pmbok > 0.0 ) ?
     733          rhok * psat / ( 1.0 - ( 1.0 - rhok ) * psat / pmbok ) :
     734          0.0;
     735    w = pwo * ( 1.0 - dmw / dmd ) * gamma / ( delta - gamma );
     736    c1 = a * ( pmbok + w ) / tdkok;
     737    c2 = ( a * w + ( optic ? 11.2684e-6 : 12.92e-6 ) * pwo ) / tdkok;
     738    c3 = ( gamma - 1.0 ) * alpha * c1 / tdkok;
     739    c4 = ( delta - 1.0 ) * alpha * c2 / tdkok;
     740    c5 = optic ? 0.0 : 371897e-6 * pwo / tdkok;
     741    c6 = c5 * delm2 * alpha / ( tdkok * tdkok );
     742
     743    /* Conditions at the observer */
     744    robs = s + hmok;
     745    atmt ( robs, tdkok, alpha, gamm2, delm2, c1, c2, c3, c4, c5, c6, robs,
     746           &tempo, &dn0, &rdndr0 );
     747    sk0 = dn0 * robs * sin ( zobs2 );
     748    f0 = refi ( robs, dn0, rdndr0 );
     749
     750    /* Conditions at the tropopause in the troposphere */
     751    rt = s + ht;
     752    atmt ( robs, tdkok, alpha, gamm2, delm2, c1, c2, c3, c4, c5, c6, rt,
     753           &tt, &dnt, &rdndrt );
     754    zt = asin ( sk0 / ( rt * dnt ) );
     755    ft = refi ( rt, dnt, rdndrt );
     756
     757    /* Conditions at the tropopause in the stratosphere */
     758    atms ( rt, tt, dnt, gamal, rt, &dnts, &rdndrp );
     759    zts = asin ( sk0 / ( rt * dnts ) );
     760    fts = refi ( rt, dnts, rdndrp );
     761
     762    /* At the stratosphere limit */
     763    rs = s + hs;
     764    atms ( rt, tt, dnt, gamal, rs, &dns, &rdndrs );
     765    zs = asin ( sk0 / ( rs * dns ) );
     766    fs = refi ( rs, dns, rdndrs );
     767
     768    /*
     769    ** Integrate the refraction integral in two parts;  first in the
     770    ** troposphere (k=1), then in the stratosphere (k=2).
     771    */
     772
     773    /* Initialize previous refraction to ensure at least two iterations */
     774    refold = 1e6;
     775
     776    /*
     777    ** Start off with 8 strips for the troposphere integration, and then
     778    ** use the final troposphere value for the stratosphere integration,
     779    ** which tends to need more strips.
     780    */
     781    is = 8;
     782
     783    /* Troposphere then stratosphere */
     784    for ( k = 1; k <= 2; k++ ) {
     785
     786        /* Start z, z range, and start and end values */
     787        if ( k == 1 ) {
     788            z0 = zobs2;
     789            zrange = zt - z0;
     790            fb = f0;
     791            ff = ft;
     792        } else {
     793            z0 = zts;
     794            zrange = zs - z0;
     795            fb = fts;
     796            ff = fs;
     797        }
     798
     799        /* Sums of odd and even values */
     800        fo = 0.0;
     801        fe = 0.0;
     802
     803        /* First time through loop we have to do every point */
     804        n = 1;
     805
     806        /* Start of iteration loop (terminates at specified precision) */
     807        for ( ; ; ) {
     808
     809            /* Strip width */
     810            h = zrange / (double) is;
     811
     812            /* Initialize distance from Earth centre for quadrature pass */
     813            r = ( k == 1 ) ? robs : rt;
     814
     815            /* One pass (no need to compute evens after first time) */
     816            for ( i = 1; i < is; i += n ) {
     817
     818                /* Sine of observed zenith distance */
     819                sz = sin ( z0 + h * (double) i );
     820
     821                /* Find r (to nearest metre, maximum four iterations) */
     822                if ( sz > 1e-20 ) {
     823                    w = sk0 / sz;
     824                    rg = r;
     825                    j = 0;
     826                    do {
     827                        if ( k == 1 ) {
     828                            atmt ( robs, tdkok, alpha, gamm2, delm2,
     829                                   c1, c2, c3, c4, c5, c6, rg,
     830                                   &tg, &dn, &rdndr );
     831                        } else {
     832                            atms ( rt, tt, dnt, gamal, rg, &dn, &rdndr );
     833                        }
     834                        dr = ( rg * dn - w ) / ( dn + rdndr );
     835                        rg -= dr;
     836                    } while ( fabs ( dr ) > 1.0 && j++ <= 4 );
     837                    r = rg;
     838                }
     839
     840                /* Find refractive index and integrand at r */
     841                if ( k == 1 ) {
     842                    atmt ( robs, tdkok, alpha, gamm2, delm2,
     843                           c1, c2, c3, c4, c5, c6, r,
     844                           &t, &dn, &rdndr );
     845                } else {
     846                    atms ( rt, tt, dnt, gamal, r, &dn, &rdndr );
     847                }
     848                f = refi ( r, dn, rdndr );
     849
     850                /* Accumulate odd and (first time only) even values */
     851                if ( n == 1 && i % 2 == 0 ) {
     852                    fe += f;
     853                } else {
     854                    fo += f;
     855                }
     856            }
     857
     858            /* Evaluate the integrand using Simpson's Rule */
     859            refp = h * ( fb + 4.0 * fo + 2.0 * fe + ff ) / 3.0;
     860
     861            /* Has the required precision been reached? */
     862            if ( fabs ( refp - refold ) > tol ) {
     863
     864                /* No: prepare for next iteration */
     865                refold = refp;   /* Save current value for convergence test */
     866                is += is;        /* Double the number of strips */
     867                fe += fo;        /* Sum of all = sum of evens next time */
     868                fo = 0.0;        /* Reset odds accumulator */
     869                n = 2;           /* Skip even values next time */
     870
     871            } else {
     872
     873                /* Yes: save troposphere component and terminate loop */
     874                if ( k == 1 ) reft = refp;
     875                break;
     876            }
     877        }
     878    }
     879
     880    /* Result */
     881    *ref = reft + refp;
     882    if ( zobs1 < 0.0 ) *ref = - ( *ref );
     883
     884    *ref+=Pidiv2-zobs1;
     885}
     886
     887/*--------------------------------------------------------------------------*/
     888
     889void Astro::atmt ( double robs, double tdkok, double alpha, double gamm2,
     890                   double delm2, double c1, double c2, double c3,
     891                   double c4, double c5, double c6, double r,
     892                   double *t, double *dn, double *rdndr )
     893/*
     894**  - - - - -
     895**   a t m t
     896**  - - - - -
     897**
     898**  Internal routine used by slaRefro:
     899**
     900**    refractive index and derivative with respect to height for the
     901**    troposphere.
     902**
     903**  Given:
     904**    robs    double   height of observer from centre of the Earth (metre)
     905**    tdkok   double   temperature at the observer (deg K)
     906**    alpha   double   alpha          )
     907**    gamm2   double   gamma minus 2  ) see ES
     908**    delm2   double   delta minus 2  )
     909**    c1      double   useful term  )
     910**    c2      double   useful term  )
     911**    c3      double   useful term  ) see source of
     912**    c4      double   useful term  ) slaRefro main routine
     913**    c5      double   useful term  )
     914**    c6      double   useful term  )
     915**    r       double   current distance from the centre of the Earth (metre)
     916**
     917**  Returned:
     918**    *t      double   temperature at r (deg K)
     919**    *dn     double   refractive index at r
     920**    *rdndr  double   r * rate the refractive index is changing at r
     921**
     922**  This routine is derived from the ATMOSTRO routine (C.Hohenkerk,
     923**  HMNAO), with enhancements specified by A.T.Sinclair (RGO) to
     924**  handle the radio case.
     925**
     926**  Note that in the optical case c5 and c6 are zero.
     927*/
     928{
     929    double w, tt0, tt0gm2, tt0dm2;
     930
     931    w = tdkok - alpha * ( r - robs );
     932    w = gmin ( w, 320.0 );
     933    w = gmax ( w, 200.0 );
     934    tt0 = w / tdkok;
     935    tt0gm2 = pow ( tt0, gamm2 );
     936    tt0dm2 = pow ( tt0, delm2 );
     937    *t = w;
     938    *dn = 1.0 + ( c1 * tt0gm2 - ( c2 - c5 / w ) * tt0dm2 ) * tt0;
     939    *rdndr = r * ( - c3 * tt0gm2 + ( c4 - c6 / tt0 ) * tt0dm2 );
     940}
     941
     942/*--------------------------------------------------------------------------*/
     943
     944void Astro::atms ( double rt, double tt, double dnt, double gamal, double r,
     945                   double *dn, double *rdndr )
     946/*
     947**  - - - - -
     948**   a t m s
     949**  - - - - -
     950**
     951**  Internal routine used by slaRefro:
     952**
     953**   refractive index and derivative with respect to height for the
     954**   stratosphere.
     955**
     956**  Given:
     957**    rt      double   height of tropopause from centre of the Earth (metre)
     958**    tt      double   temperature at the tropopause (deg k)
     959**    dnt     double   refractive index at the tropopause
     960**    gamal   double   constant of the atmospheric model = g*md/r
     961**    r       double   current distance from the centre of the Earth (metre)
     962**
     963**  Returned:
     964**    *dn     double   refractive index at r
     965**    *rdndr  double   r * rate the refractive index is changing at r
     966**
     967**  This routine is derived from the ATMOSSTR routine (C.Hohenkerk, HMNAO).
     968*/
     969{
     970    double b, w;
     971
     972    b = gamal / tt;
     973    w = ( dnt - 1.0 ) * exp ( - b * ( r - rt ) );
     974    *dn = 1.0 + w;
     975    *rdndr = - r * b * w;
     976}
     977
     978
     979
  • BAORadio/libindi/libindi/drivers/telescope/astro.h

    r490 r504  
    1 // Definition of the Astro class
    2 // Franck RICHARD
    3 // BAORadio
     1////////////////////////////////
     2// Classe Astro               //
     3// Franck RICHARD             //
     4// BAORadio                   //
     5// franckrichard033@gmail.com //
     6// juin 2011                  //
     7////////////////////////////////
    48
    59#ifndef Astro_class
     
    711
    812#include "math.h"
     13#include "stdio.h"
     14#include <iostream>
     15#include <string.h>
     16#include <sstream>
     17#include <iomanip>
     18
     19using namespace std;
    920
    1021//////////////////////////////
     
    1829#define Pidiv2          1.57079632679489661923132169163
    1930
     31#define gmax(A,B) ((A)>(B)?(A):(B))
    2032
    21 class Astro
     33#define gmin(A,B) ((A)<(B)?(A):(B))
     34
     35
     36struct Coordonnees
     37{
     38    string ar;                          // Coordonnées horaires d'un objet
     39    string dec;
     40};
     41
     42class Astro
    2243{
    2344public:
     
    2546    ~Astro();
    2647
     48    void   DefinirDateHeure(double Annee, double Mois, double Jour, double Heu, double Min, double Sec);
     49    void   DefinirPressionTemp(double P, double T);
     50    void   DefinirLongitudeLatitude(double log, double lat);
    2751    double VerifAngle(double Angle);
    28     void  Azimut(double ts, double Latitude, double Ar, double De, double *azi, double *hau);
    29     void  CalculJJ(double Heure);
     52    double Arrondi(double a);
     53    string DHMS(double mema, bool HMS);
     54    void   Azimut(double Ar, double De, double *azi, double *hau);
     55    void   Precession(double *ar, double *de);
     56    void   NutationEtoile(double *ar, double *de);
     57    void   AberrationAnnuelle(double *ar, double *de);
     58    void   CalculJJ(double Heure);
     59    double CalculJJ(double A, double M, double J, double Heure);
     60    void   CalculTSL(); 
     61    double RefractionAtmospherique(double ht);
     62    double CalculLongitudeSoleil();
    3063    double TSL(double JJ,double HeureSiderale,double Longitude);
    31     void Nutation();
    32     void Obliquite(double JJ);
    33     void CalculTSL();
     64    void   Nutation();
     65    void   Obliquite(double JJ);
     66    void   atms ( double rt, double tt, double dnt, double gamal, double r,
     67                   double *dn, double *rdndr );
     68    void   atmt ( double robs, double tdkok, double alpha, double gamm2,
     69                   double delm2, double c1, double c2, double c3,
     70                   double c4, double c5, double c6, double r,
     71                   double *t, double *dn, double *rdndr );
     72    void   slaRefro ( double zobs, double hm, double tdk, double pmb,
     73                double rh, double wl, double phi, double tlr,
     74                double eps, double *ref );
     75    float  slaRange(float angle );
     76    double slaDrange(double angle );
     77    void   CalculARDecSoleil(Coordonnees *Soleil);
    3478   
     79   
     80    double GetAnnee() { return Annee; }
     81    double GetMois()  { return Mois;  }
     82    double GetJour()  { return Jour;  }
     83    double GetHeure() { return Heure; }
     84    double GetMin()   { return Min;   }
     85    double GetSec()   { return Sec;   }
     86    double GetJJ()    { return JJ;    } 
     87
     88 
     89   
     90   
     91private:
    3592    double Longitude;
    3693    double Latitude;
    37     double Lst;
    3894    double JJ;
    3995    double CorP;
     
    4298    double Mois;
    4399    double Jour;
    44     double Heu;
     100    double Heure;
    45101    double Min;
    46102    double Sec;
     
    49105    double UTCP;
    50106    double tsl;
     107    double LongitudeSoleil;
     108    double Pression;
     109    double Temp;
    51110};
    52111
  • BAORadio/libindi/libindi/drivers/telescope/lx200generic.cpp

    r501 r504  
    165165 Property: Movement (Arrow keys on handset). West/East
    166166*********************************************/
    167 
    168167static ISwitch MovementWES[]       = {{"MOTION_WEST", "West", ISS_OFF, 0, 0}, {"MOTION_EAST", "East", ISS_OFF, 0, 0}};
    169168ISwitchVectorProperty MovementWESP      = { mydev, "TELESCOPE_MOTION_WE", "West/East", MOTION_GROUP, IP_RW, ISR_1OFMANY, 0, IPS_IDLE, MovementWES, NARRAY(MovementWES), "", 0};
     
    315314  strcpy(TimeTP.device , newName );
    316315  strcpy(UTCOffsetNP.device , newName );
    317 
    318316  strcpy(SDTimeNP.device , newName );
    319317
  • BAORadio/libindi/libindi/examples/README

    r490 r504  
    1616tutorial_one: We construct a most basic (and useless) device driver to illustate basic INDI structures.
    1717tutorial_two:  We create a simple simulator. We will use a few handy utility functions provided by INDI like timers, string <---> number conversion, and more.
    18 tutorial_three:  We create a simple device, and establish a data channel with the client to transmit a FITS file.
     18tutorial_three:  We create a simple CCD simulator, and establish a data channel with the client to transmit a FITS file.
    1919
    2020tutorial_dome and tutorial_rain are part of the inter-driver communication tutorial.
     21
     22tutorial_client: We create a simple client to set the temperature of a CCD simulator (tutorial_three).
    2123
    2224Usage
     
    4547where num is the tutorial number (tutorial_one, tutorial_two, or tutorial_three).
    4648
     49------------------------------------------------------------------------------------------
     50
    4751For the inter-driver communications tutorial, type instead:
    4852
    4953$ indiserver -v -p 8000 ./tutorial_dome ./tutorial_rain
     54
     55------------------------------------------------------------------------------------------
     56
     57For tutorial_client. Run tutorial_three first:
     58
     59$ indiserver -v ./tutorial_three
     60
     61Then open another console tab, and run the client:
     62
     63$ ./tutorial_client
     64
     65You can connect to tutorial_three via a GUI client (e.g. KStars) before running tutorial_client. This will enable you to watch
     66changes in the driver as they occur from tutorial_client. Make sure to set the port to 7624 in KStars.
    5067
    5168------------------------------------------------------------------------------------------
  • BAORadio/libindi/libindi/examples/tutorial_four.cpp

    r501 r504  
    133133    IDLog("Initilizing from My Scope device...\n");
    134134
    135     init_properties();
     135    //init_properties();
    136136
    137137 }
     
    147147/**************************************************************************************
    148148** Initialize all properties & set default values.
    149 ***************************************************************************************/
    150 void MyScope::init_properties()
    151 {
     149**************************************************************************************/
     150bool MyScope::initProperties()
     151{
     152    DefaultDriver::initProperties();
    152153    // This is the default driver skeleton file location
    153154    // Convention is: drivername_sk_xml
     
    169170    addAuxControls();
    170171
     172    return true;
     173
    171174}
    172175
     
    247250            return false;
    248251
    249         // Are we update CONNECTION?
     252        /* Are we update CONNECTION?
    250253        if (!strcmp(svp->name, "CONNECTION"))
    251254        {
     
    253256            connect_telescope();
    254257            return true;
    255         }
    256 
    257 
    258 }
    259 
    260 
    261 /**************************************************************************************
    262 **
    263 ***************************************************************************************/
    264 void MyScope::connect_telescope()
    265 {
    266     ISwitchVectorProperty *svp = getSwitch("CONNECTION");
    267 
    268     ISwitch *sp = IUFindOnSwitch(svp);
    269 
    270     if (!sp)
    271         return;
    272 
    273     // Are we connecting?
    274     if (!strcmp(sp->name, "CONNECT"))
    275     {
    276         // Make sure to call setConnected(true) before informing client about successful connection
    277         setConnected(true);
    278         IDSetSwitch(svp, "Connecting.... telescope is online.");
    279         IDLog("Connecting.... telescope is online.\n");
    280 
    281 
    282     }
    283     // Are we disconnecting?
    284     else
    285     {
    286         setConnected(false);
    287         IDSetSwitch(svp, "Disconnecting... telescope is offline.");
    288         IDLog("Disconnecting... telescope is offline.\n");
    289     }
    290 }
    291 
    292 
     258        }*/
     259
     260
     261}
     262
     263
     264/**************************************************************************************
     265**
     266***************************************************************************************/
     267bool MyScope::Connect()
     268{
     269    return true;
     270}
     271
     272bool MyScope::Disconnect()
     273{
     274    return true;
     275}
     276
     277const char * MyScope::getDefaultName()
     278{
     279    return "My Scope";
     280}
     281
     282
     283
     284
     285
     286
     287
  • BAORadio/libindi/libindi/examples/tutorial_four.h

    r501 r504  
    3838
    3939private:
    40  void init_properties();
    41  void connect_telescope();
     40 const char *getDefaultName();
     41 virtual bool initProperties();
     42 virtual bool Connect();
     43 virtual bool Disconnect();
    4244
    4345};
  • BAORadio/libindi/libindi/examples/tutorial_three.c

    r490 r504  
    6666
    6767/* BLOB for sending image */
    68 static IBLOB imageB = {"CCD1", "Feed", "", 0, 0, 0, 0, 0, 0, 0};
    69 static IBLOBVectorProperty imageBP = {mydev, "Video", "Video", COMM_GROUP,
    70   IP_RO, 0, IPS_IDLE, &imageB, 1, "", 0};
     68static IBLOB imagePrimaryB = {"CCD1", "Primary", "", 0, 0, 0, 0, 0, 0, 0};
     69static IBLOBVectorProperty imagePrimaryBP = {mydev, "CCD1", "", COMM_GROUP,
     70  IP_RO, 0, IPS_IDLE, &imagePrimaryB, 1, "", 0};
     71
     72static IBLOB imageGuideB = {"CCD2", "Guide", "", 0, 0, 0, 0, 0, 0, 0};
     73static IBLOBVectorProperty imageGuideBP = {mydev, "CCD2", "", COMM_GROUP,
     74  IP_RO, 0, IPS_IDLE, &imageGuideB, 1, "", 0};
    7175
    7276void ISGetProperties (const char *dev)
     
    8084  IDDefNumber(&ExposeTimeNP, NULL);
    8185  IDDefNumber(&TemperatureNP, NULL);
    82   IDDefBLOB(&imageBP, NULL);
     86  IDDefBLOB(&imagePrimaryBP, NULL);
     87  IDDefBLOB(&imageGuideBP, NULL);
    8388
    8489  IEAddTimer(1000, ISPoll, NULL);
     
    236241   
    237242   /* #6 Send it */
    238    imageB.blob = compressedData;
    239    imageB.bloblen = compressedBytes;
    240    imageB.size = totalBytes;
    241    strcpy(imageB.format, ".fits.z");
     243
     244   if (!strcmp(filename, "ngc1316o.fits"))
     245   {
     246   imagePrimaryB.blob = compressedData;
     247   imagePrimaryB.bloblen = compressedBytes;
     248   imagePrimaryB.size = totalBytes;
     249   strcpy(imagePrimaryB.format, ".fits.z");
    242250
    243251   /* #7 Set BLOB state to Ok */
    244    imageBP.s = IPS_OK;
    245    IDSetBLOB (&imageBP, NULL);
     252   imagePrimaryBP.s = IPS_OK;
     253   IDSetBLOB (&imagePrimaryBP, NULL);
     254   }
     255   else
     256   {
     257       imageGuideB.blob = compressedData;
     258       imageGuideB.bloblen = compressedBytes;
     259       imageGuideB.size = totalBytes;
     260       strcpy(imageGuideB.format, ".fits.z");
     261
     262       /* #7 Set BLOB state to Ok */
     263       imageGuideBP.s = IPS_OK;
     264       IDSetBLOB (&imageGuideBP, NULL);
     265   }
    246266
    247267   /* #8 Set Exposure status to Ok */
     
    274294
    275295        /* Are we done yet? */
    276         if (ExposeTimeN[0].value == 0)
     296        if (ExposeTimeN[0].value <= 0)
    277297        {
     298          ExposeTimeN[0].value = 0;
     299
    278300          /* Let's set the state of OK and report that to the client */
    279301          ExposeTimeNP.s = IPS_OK;
     
    281303          /* Upload a sample FITS file */
    282304          uploadFile("ngc1316o.fits");
     305          uploadFile("x0cj010ct_d0h.fit");
    283306
    284307          IDSetNumber(&ExposeTimeNP, NULL);
  • BAORadio/libindi/libindi/examples/tutorial_two.c

    r501 r504  
    102102static INumber eqNR[] = {{"RA" ,"RA  H:M:S" , "%10.6m" ,0. , 24., 0., 0., 0, 0, 0},
    103103                         {"DEC", "Dec D:M:S", "%10.6m", -90., 90., 0., 0., 0, 0, 0}};
    104 static INumberVectorProperty eqNPR = {  mydev, "EQUATORIAL_EOD_COORD_REQUEST", "Equatorial Request",  MAIN_GROUP , IP_RW, 0, IPS_IDLE,  eqNR, NARRAY(eqNR), "", 0};
     104static INumberVectorProperty eqNPR = {  mydev, "EQUATORIAL_EOD_COORD_REQUEST", "Equatorial Request",  MAIN_GROUP , IP_WO, 0, IPS_IDLE,  eqNR, NARRAY(eqNR), "", 0};
    105105
    106106/* Property naming convention. All property names are lower case with a postfix to indicate their type. connectS is a switch,
     
    122122ISwitchVectorProperty MovementWESP      = { mydev, "TELESCOPE_MOTION_WE", "West/East", MAIN_GROUP, IP_RW, ISR_ATMOST1, 0, IPS_IDLE, MovementWES, NARRAY(MovementWES), "", 0};
    123123
     124static ISwitch OnCoordSetS[] = {{"TRACK", "Track", ISS_ON, 0, 0}};
     125static ISwitchVectorProperty OnCoordSetSP = {mydev, "ON_COORD_SET", "On Set", MAIN_GROUP, IP_RW, ISR_1OFMANY, 0, IPS_OK, OnCoordSetS, NARRAY(OnCoordSetS), "", 0};
     126
     127
    124128/* Initlization routine */
    125129static void mountInit()
     
    149153        IDDefSwitch (&MovementNSSP, NULL);
    150154        IDDefSwitch (&MovementWESP, NULL);
     155        IDDefSwitch(&OnCoordSetSP, NULL);
    151156       
    152157}
     
    276281                }
    277282        }
     283        else if (! strcmp(name, OnCoordSetSP.name))
     284        {
     285            OnCoordSetSP.s = IPS_OK;
     286            IDSetSwitch(&OnCoordSetSP, NULL);
     287        }
    278288       
    279289       
  • BAORadio/libindi/libindi/indiapi.h

    r501 r504  
    7575
    7676/* INDI Library version */
    77 #define INDI_LIBV       0.7
     77#define INDI_LIBV       0.8
    7878
    7979/*******************************************************************************
  • BAORadio/libindi/libindi/indidriver.c

    r501 r504  
    323323void IUFillBLOB(IBLOB *bp, const char *name, const char * label, const char *format)
    324324{
     325    memset(bp, 0, sizeof(IBLOB));
    325326    strncpy(bp->name, name, MAXINDINAME);
    326327    strncpy(bp->label, label, MAXINDILABEL);
     
    341342  strncpy(svp->label, label, MAXINDILABEL);
    342343  strncpy(svp->group, group, MAXINDIGROUP);
    343   strcpy(svp->timestamp, "");
    344344 
    345345  svp->p        = p;
     
    399399void IUFillBLOBVector(IBLOBVectorProperty *bvp, IBLOB *bp, int nbp, const char * dev, const char *name, const char *label, const char* group, IPerm p, double timeout, IPState s)
    400400{
     401    memset(bvp, 0, sizeof(IBLOBVectorProperty));
    401402    strncpy(bvp->device, dev, MAXINDIDEVICE);
    402403    strncpy(bvp->name, name, MAXINDINAME);
     
    405406    strcpy(bvp->timestamp, "");
    406407
    407   bvp->p        = p;
    408   bvp->timeout  = timeout;
    409   bvp->s        = s;
    410   bvp->bp       = bp;
    411   bvp->nbp      = nbp;
    412 
     408    bvp->p      = p;
     409    bvp->timeout        = timeout;
     410    bvp->s      = s;
     411    bvp->bp     = bp;
     412    bvp->nbp    = nbp;
    413413}
    414414
  • BAORadio/libindi/libindi/indiserver.c

    r501 r504  
    8484    char dev[MAXINDIDEVICE];
    8585    char name[MAXINDINAME];
     86    BLOBHandling blob;                  /* when to snoop BLOBs */
    8687} Property;
    8788
    88 /* record of each snooped property */
     89
     90/* record of each snooped property
    8991typedef struct {
    9092    Property prop;
    91     BLOBHandling blob;                  /* when to snoop BLOBs */
    92 } Snoopee;
     93    BLOBHandling blob;
     94} Property;
     95*/
    9396
    9497struct
     
    119122    char dev[MAXINDIDEVICE];            /* device served by this driver */
    120123    int active;                         /* 1 when this record is in use */
    121     Snoopee *sprops;                    /* malloced array of props we snoop */
     124    Property *sprops;                   /* malloced array of props we snoop */
    122125    int nsprops;                        /* n entries in sprops[] */
    123126    int pid;                            /* process id or REMOTEDVR if remote */
     
    163166    Msg *mp, XMLEle *root);
    164167static void addSDevice (DvrInfo *dp, const char *dev, const char *name);
    165 static Snoopee *findSDevice (DvrInfo *dp, const char *dev, const char *name);
    166 static void addClDevice (ClInfo *cp, const char *dev, const char *name);
     168static Property *findSDevice (DvrInfo *dp, const char *dev, const char *name);
     169static void addClDevice (ClInfo *cp, const char *dev, const char *name, int isblob);
    167170static int findClDevice (ClInfo *cp, const char *dev, const char *name);
    168171static int readFromDriver (DvrInfo *dp);
     
    175178static int sendClientMsg (ClInfo *cp);
    176179static int sendDriverMsg (DvrInfo *cp);
    177 static void crackBLOB (char *enableBLOB, BLOBHandling *bp);
     180static void crackBLOB (const char *enableBLOB, BLOBHandling *bp);
     181static void crackBLOBHandling(const char *dev, const char *name, const char *enableBLOB, ClInfo *cp);
    178182static void traceMsg (XMLEle *root);
    179183static char *indi_tstamp (char *s);
     
    433437        dp->lp = newLilXML();
    434438        dp->msgq = newFQ(1);
    435         dp->sprops = (Snoopee*) malloc (1);     /* seed for realloc */
     439        dp->sprops = (Property*) malloc (1);    /* seed for realloc */
    436440        dp->nsprops = 0;
    437441        dp->nsent = 0;
     
    484488        dp->lp = newLilXML();
    485489        dp->msgq = newFQ(1);
    486         dp->sprops = (Snoopee*) malloc (1);     /* seed for realloc */
     490        dp->sprops = (Property*) malloc (1);    /* seed for realloc */
    487491        dp->nsprops = 0;
    488492        dp->nsent = 0;
     
    737741    static char *envDev=NULL, *envConfig=NULL;
    738742    const char *delm = " ";
    739     char *token, *cp;
     743    char *token, *cp, *tp;
    740744    DvrInfo *dp = NULL;
    741745    int startCmd=0;
     
    748752    while ( fgets (line, MAXRBUF, fifo.fs) != NULL)
    749753    {
    750         //fprintf(stderr, "FIFO: %s\n", line);
     754        fprintf(stderr, "FIFO: %s\n", line);
     755
    751756        tDev[0] = '\0', tDriver[0] = '\0', tConfig[0] = '\0', envDev[0] = '\0', envConfig[0] = '\0';
    752757        cp = strdup(line);
     
    756761        if (!strcmp(token, "start") || !strcmp(token, "stop"))
    757762        {
     763            //fprintf(stderr, "TOKEN: %s\n", token);
     764
    758765                if (!strcmp(token, "start"))
    759766                    startCmd = 1;
     
    765772
    766773               strncpy(tDriver, token, MAXRBUF);
     774               if (tp = strchr(tDriver, '\n'))
     775                   *tp = '\0';
    767776
    768777               if (verbose)
     
    785794                     strcat(tDev, " ");
    786795                     strncat(tDev, token, MAXRBUF);
    787                      if (strstr(token, "\"") || strstr(token, "'"))
     796                     if ( (tp=strchr(tDev, '\"')) || (tp=strchr(tDev, '\'')))
    788797                     {
    789                          tDev[strlen(tDev)-1] = '\0';
     798                         //tDev[strlen(tDev)-1] = '\0';
     799                         *tp='\0';
    790800                         break;
    791801                     }
     
    793803                 }
    794804                 else
     805                {
    795806                     strncpy(tDev, token, MAXRBUF);
     807                     if (tp = strchr(tDev, '\n'))
     808                         *tp = '\0';
     809                 }
    796810
    797811                  /* Find config, if there is any */
     
    808822                          strncat(tConfig, token, MAXRBUF);
    809823
    810                           if (strstr(token, "\"") || strstr(token, "'"))
     824                          if ( (tp=strchr(tConfig, '\"')) || (tp=strchr(tConfig, '\'')))
    811825                          {
    812                                  tConfig[strlen(tConfig)-1] = '\0';
    813                                  break;
     826                                 //tConfig[strlen(tConfig)-1] = '\0';
     827                              *tp = '\0';
     828                              break;
    814829                          }
    815830                       }
    816831                      }
    817832                       else
     833                      {
    818834                           strncpy(tConfig, token, MAXRBUF);
     835                           if (tp = strchr(tConfig, '\n'))
     836                               *tp = '\0';
     837                       }
    819838                  }
    820839              }
     
    824843               {
    825844                 snprintf(envDev, MAXRBUF, "INDIDEV=%s", tDev);
    826                  //fprintf(stderr, "With name: %s\n", envDev);
     845
     846                 if (verbose)
     847                    fprintf(stderr, "With name: %s\n", envDev);
     848
    827849                 putenv(envDev);
    828850
     
    834856               {
    835857                   snprintf(envConfig, MAXRBUF, "INDICONFIG=%s", tConfig);
    836                    //fprintf(stderr, "With config: %s\n", envConfig);
     858
     859                   if (verbose)
     860                    fprintf(stderr, "With config: %s\n", envConfig);
     861
    837862                   putenv(envConfig);
    838863               }
     
    9781003                 */
    9791004                if (dev[0])
    980                     addClDevice (cp, dev, name);
     1005                    addClDevice (cp, dev, name, isblob);
    9811006                else if (!strcmp (roottag, "getProperties") && !cp->nprops)
    9821007                    cp->allprops = 1;
     
    9841009                /* snag enableBLOB -- send to remote drivers too */
    9851010                if (!strcmp (roottag, "enableBLOB"))
    986                     crackBLOB (pcdataXMLEle(root), &cp->blob);
     1011                   // crackBLOB (pcdataXMLEle(root), &cp->blob);
     1012                     crackBLOBHandling (dev, name, pcdataXMLEle(root), cp);
    9871013
    9881014                /* build a new message -- set content iff anyone cares */
     
    10731099                /* that's all if driver is just registering a BLOB mode */
    10741100                if (!strcmp (roottag, "enableBLOB")) {
    1075                     Snoopee *sp = findSDevice (dp, dev, name);
     1101                    Property *sp = findSDevice (dp, dev, name);
    10761102                    if (sp)
    10771103                        crackBLOB (pcdataXMLEle (root), &sp->blob);
     
    10941120
    10951121                /* send to interested clients */
    1096                 if (q2Clients (NULL, isblob, dev, name, mp, root) < 0)
     1122                if (q2Clients (NULL, isblob, dev, name, mp, root) < 0)
    10971123                    shutany++;
    10981124
     
    12441270        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) {
    12451271            int isremote = (dp->pid == REMOTEDVR);
     1272            if (dp->active == 0)
     1273                continue;
    12461274            if (dev[0] && dp->dev[0] && strcmp (dev, dp->dev))
    12471275                continue;       /* driver known to not support this dev */
     
    12711299
    12721300        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) {
    1273             Snoopee *sp = findSDevice (dp, dev, name);
     1301            Property *sp = findSDevice (dp, dev, name);
    12741302
    12751303            /* nothing for dp if not snooping for dev/name or wrong BLOB mode */
     
    12971325addSDevice (DvrInfo *dp, const char *dev, const char *name)
    12981326{
    1299         Snoopee *sp;
     1327        Property *sp;
    13001328        char *ip;
    13011329
     
    13061334
    13071335        /* add dev to sdevs list */
    1308         dp->sprops = (Snoopee*) realloc (dp->sprops,
    1309                                             (dp->nsprops+1)*sizeof(Snoopee));
     1336        dp->sprops = (Property*) realloc (dp->sprops,
     1337                                            (dp->nsprops+1)*sizeof(Property));
    13101338        sp = &dp->sprops[dp->nsprops++];
    13111339
    1312         ip = sp->prop.dev;
     1340        ip = sp->dev;
    13131341        strncpy (ip, dev, MAXINDIDEVICE-1);
    13141342        ip[MAXINDIDEVICE-1] = '\0';
    13151343
    1316         ip = sp->prop.name;
     1344        ip = sp->name;
    13171345        strncpy (ip, name, MAXINDINAME-1);
    13181346        ip[MAXINDINAME-1] = '\0';
     
    13251353}
    13261354
    1327 /* return Snoopee if dp is snooping dev/name, else NULL.
    1328  */
    1329 static Snoopee *
     1355/* return Property if dp is snooping dev/name, else NULL.
     1356 */
     1357static Property *
    13301358findSDevice (DvrInfo *dp, const char *dev, const char *name)
    13311359{
     
    13331361
    13341362        for (i = 0; i < dp->nsprops; i++) {
    1335             Snoopee *sp = &dp->sprops[i];
    1336             Property *pp = &sp->prop;
    1337             if (!strcmp (pp->dev, dev) &&
    1338                     (!pp->name[0] || !strcmp(pp->name, name)))
     1363            Property *sp = &dp->sprops[i];
     1364            if (!strcmp (sp->dev, dev) &&
     1365                    (!sp->name[0] || !strcmp(sp->name, name)))
    13391366                return (sp);
    13401367        }
     
    13421369        return (NULL);
    13431370}
     1371
    13441372
    13451373/* put Msg mp on queue of each client interested in dev/name, except notme.
     
    13521380        int shutany = 0;
    13531381        ClInfo *cp;
    1354         int ql;
     1382        int ql,i=0;
    13551383
    13561384        /* queue message to each interested client */
     
    13591387            if (!cp->active || cp == notme)
    13601388                continue;
    1361             if (findClDevice (cp, dev, name) < 0)
     1389            if (findClDevice (cp, dev, name) < 0)
    13621390                continue;
    1363             if ((isblob && cp->blob==B_NEVER) || (!isblob && cp->blob==B_ONLY))
    1364                 continue;
     1391
     1392            //if ((isblob && cp->blob==B_NEVER) || (!isblob && cp->blob==B_ONLY))
     1393            if (!isblob && cp->blob==B_ONLY)
     1394                continue;
     1395
     1396            if (isblob)
     1397            {
     1398                if (cp->nprops > 0)
     1399                {
     1400                Property *pp = NULL;
     1401                int blob_found=0;
     1402                for (i = 0; i < cp->nprops; i++)
     1403                {
     1404                    pp = &cp->props[i];
     1405                    if (!strcmp (pp->dev, dev) && (!strcmp(pp->name, name)))
     1406                    {
     1407                        blob_found = 1;
     1408                        break;
     1409                    }
     1410                }
     1411
     1412                if ( (blob_found && pp->blob == B_NEVER) || (blob_found==0 && cp->blob == B_NEVER) )
     1413                    continue;
     1414               }
     1415               else if (cp->blob == B_NEVER)
     1416                   continue;
     1417           }
    13651418
    13661419            /* shut down this client if its q is already too large */
     
    15681621        int i;
    15691622
    1570         if (cp->allprops || !dev[0])
     1623        if (cp->allprops || !dev[0])
    15711624            return (0);
    1572         for (i = 0; i < cp->nprops; i++) {
    1573             Property *pp = &cp->props[i];
    1574             if (!strcmp (pp->dev, dev) &&
    1575                                     (!pp->name[0] || !strcmp(pp->name, name)))
     1625        for (i = 0; i < cp->nprops; i++)
     1626        {
     1627            Property *pp = &cp->props[i];
     1628            if (!strcmp (pp->dev, dev) && (!pp->name[0] || !strcmp(pp->name, name)))
    15761629                return (0);
    15771630        }
     
    15821635 */
    15831636static void
    1584 addClDevice (ClInfo *cp, const char *dev, const char *name)
     1637addClDevice (ClInfo *cp, const char *dev, const char *name, int isblob)
    15851638{
    15861639        Property *pp;
    15871640        char *ip;
    1588 
     1641        int i=0;
     1642
     1643        if (isblob)
     1644        {
     1645            for (i = 0; i < cp->nprops; i++)
     1646            {
     1647                Property *pp = &cp->props[i];
     1648                if (!strcmp (pp->dev, dev) && (!pp->name[0] || !strcmp(pp->name, name)))
     1649                    return;
     1650            }
     1651        }
    15891652        /* no dups */
    1590         if (!findClDevice (cp, dev, name))
     1653        else if (!findClDevice (cp, dev, name))
    15911654            return;
    15921655
    15931656        /* add */
    15941657        cp->props = (Property *) realloc (cp->props,
    1595                                             (cp->nprops+1)*sizeof(Property));
     1658                                            (cp->nprops+1)*sizeof(Property));
    15961659        pp = &cp->props[cp->nprops++];
    15971660
    1598         ip = pp->dev;
     1661        /*ip = pp->dev;
    15991662        strncpy (ip, dev, MAXINDIDEVICE-1);
    16001663        ip[MAXINDIDEVICE-1] = '\0';
     
    16021665        ip = pp->name;
    16031666        strncpy (ip, name, MAXINDINAME-1);
    1604         ip[MAXINDINAME-1] = '\0';
     1667        ip[MAXINDINAME-1] = '\0';*/
     1668
     1669        strncpy (pp->dev, dev, MAXINDIDEVICE);
     1670        strncpy (pp->name, name, MAXINDINAME);
     1671        pp->blob = B_NEVER;
    16051672}
    16061673
     
    16321699 */
    16331700static void
    1634 crackBLOB (char *enableBLOB, BLOBHandling *bp)
     1701crackBLOB (const char *enableBLOB, BLOBHandling *bp)
    16351702{
    16361703        if (!strcmp (enableBLOB, "Also"))
     
    16401707        else if (!strcmp (enableBLOB, "Never"))
    16411708            *bp = B_NEVER;
     1709}
     1710
     1711/* Update the client property BLOB handling policy */
     1712static void crackBLOBHandling(const char *dev, const char *name, const char *enableBLOB, ClInfo *cp)
     1713{
     1714    int i=0;
     1715
     1716    /* If we have EnableBLOB with property name, we add it to Client device list */
     1717    if (name[0])
     1718        addClDevice (cp, dev, name, 1);
     1719    else
     1720    /* Otherwise, we set the whole client blob handling to what's passed (enableBLOB) */
     1721        crackBLOB(enableBLOB, &cp->blob);
     1722
     1723    /* If whole client blob handling policy was updated, we need to pass that also to all children
     1724       and if the request was for a specific property, then we apply the policy to it */
     1725    for (i = 0; i < cp->nprops; i++)
     1726    {
     1727        Property *pp = &cp->props[i];
     1728        if (!name[0])           
     1729            crackBLOB(enableBLOB, &pp->blob);
     1730        else if (!strcmp (pp->dev, dev) && (!strcmp(pp->name, name)))
     1731        {
     1732            crackBLOB(enableBLOB, &pp->blob);
     1733            return;
     1734        }
     1735    }
    16421736}
    16431737
  • BAORadio/libindi/libindi/libs/indibase/baseclient.cpp

    r502 r504  
    2020    cServer = "localhost";
    2121    cPort   = 7624;
     22    svrwfp = NULL;   
     23    sConnected = false;
    2224
    2325}
     
    2628INDI::BaseClient::~BaseClient()
    2729{
    28 
    29     disconnect();
    30 
     30    close(sockfd);
    3131}
    3232
     
    4343}
    4444
    45 bool INDI::BaseClient::connect()
     45bool INDI::BaseClient::connectServer()
    4646{
    4747    struct sockaddr_in serv_addr;
     
    7676    /* prepare for line-oriented i/o with client */
    7777    svrwfp = fdopen (sockfd, "w");
    78     svrrfp = fdopen (sockfd, "r");
    7978
    8079    int result = pthread_create( &listen_thread, NULL, &INDI::BaseClient::listenHelper, this);
     
    8685    }
    8786
     87    serverConnected();
     88    sConnected = true;
     89
    8890    return true;
    8991}
    9092
    91 void INDI::BaseClient::disconnect()
    92 {
    93     char errmsg[MAXRBUF];
    94     removeDevice(NULL, errmsg);
    95     if (lillp)
    96         delLilXML(lillp);
    97     lillp = NULL;
    98     pthread_cancel(listen_thread);
    99     close(sockfd);
    100     if (svrwfp)
     93bool INDI::BaseClient::disconnectServer()
     94{
     95    if (sConnected == false)
     96        return true;
     97
     98    if (svrwfp != NULL)
    10199        fclose(svrwfp);
    102     svrwfp = NULL;
    103     if (svrrfp)
    104         fclose(svrrfp);
    105     svrrfp = NULL;
    106 }
    107 
    108 INDI::BaseDriver * INDI::BaseClient::getDevice(const char * deviceName)
    109 {
    110     vector<INDI::BaseDriver *>::const_iterator devi;
     100   svrwfp = NULL;
     101
     102   close(sockfd);
     103
     104    serverDisconnected();
     105
     106    sConnected = false;
     107
     108    return true;
     109}
     110
     111
     112void INDI::BaseClient::setDriverConnection(bool status, const char *deviceName)
     113{
     114    INDI::BaseDriver *drv = getDriver(deviceName);
     115    ISwitchVectorProperty *drv_connection = NULL;
     116
     117    if (drv == NULL)
     118    {
     119        IDLog("INDI::BaseClient: Error. Unable to find driver %s\n", deviceName);
     120        return;
     121    }
     122
     123    drv_connection = drv->getSwitch("CONNECTION");
     124
     125    if (drv_connection == NULL)
     126        return;
     127
     128    // If we need to connect
     129    if (status)
     130    {
     131        // If there is no need to do anything, i.e. already connected.
     132        if (drv_connection->sp[0].s == ISS_ON)
     133            return;
     134
     135        IUResetSwitch(drv_connection);
     136        drv_connection->s = IPS_BUSY;
     137        drv_connection->sp[0].s = ISS_ON;
     138        drv_connection->sp[1].s = ISS_OFF;
     139
     140        sendNewSwitch(drv_connection, &(drv_connection->sp[0]));
     141    }
     142    else
     143    {
     144        // If there is no need to do anything, i.e. already disconnected.
     145        if (drv_connection->sp[1].s == ISS_ON)
     146            return;
     147
     148        IUResetSwitch(drv_connection);
     149        drv_connection->s = IPS_BUSY;
     150        drv_connection->sp[0].s = ISS_OFF;
     151        drv_connection->sp[1].s = ISS_ON;
     152
     153        sendNewSwitch(drv_connection, &(drv_connection->sp[1]));
     154
     155    }
     156}
     157
     158
     159INDI::BaseDriver * INDI::BaseClient::getDriver(const char * deviceName)
     160{
     161    vector<devicePtr>::const_iterator devi;
    111162    for ( devi = cDevices.begin(); devi != cDevices.end(); devi++)
    112163        if (!strcmp(deviceName, (*devi)->deviceName()))
    113             return (*devi);
     164            return (*devi).get();
    114165
    115166    return NULL;
     
    141192
    142193    /* read from server, exit if find all requested properties */
    143     while (1)
    144     {
    145         n = fread(buffer, 1, MAXINDIBUF, svrrfp);
     194    while (sConnected)
     195    {
     196        n = read(sockfd, buffer, MAXINDIBUF);
    146197
    147198        if (n ==0)
    148199        {
    149             if (ferror(svrrfp))
    150                 perror ("read");
    151             else
    152                 fprintf (stderr,"INDI server %s/%d disconnected\n", cServer.c_str(), cPort);
    153 
     200            perror ("read");
     201            fprintf (stderr,"INDI server %s/%d disconnected\n", cServer.c_str(), cPort);
    154202            serverDisconnected();
    155203            return;
     
    180228        }
    181229    }
     230
    182231}
    183232
     
    242291int INDI::BaseClient::removeDevice( const char * devName, char * errmsg )
    243292{
    244     std::vector<INDI::BaseDriver *>::iterator devicei = cDevices.begin();
     293    std::vector<devicePtr>::iterator devicei = cDevices.begin();
    245294
    246295    while (devicei != cDevices.end())
    247296    {
    248       if (devName == NULL || !strcmp(devName, (*devicei)->deviceName()))
     297      if (strcmp(devName, (*devicei)->deviceName()))
    249298      {
    250299          cDevices.erase(devicei);
    251           delete (*devicei);
     300          //delete (*devicei);
    252301          return 0;
    253302      }
     
    263312{
    264313
    265     std::vector<INDI::BaseDriver *>::const_iterator devicei;
     314    std::vector<devicePtr>::const_iterator devicei;
    266315
    267316    for (devicei = cDevices.begin(); devicei != cDevices.end(); devicei++)
    268317    {
    269318        if (!strcmp(devName, (*devicei)->deviceName()))
    270          return (*devicei);
     319         return (*devicei).get();
    271320
    272321    }
     
    279328INDI::BaseDriver * INDI::BaseClient::addDevice (XMLEle *dep, char * errmsg)
    280329{
    281     INDI::BaseDriver *dp;
     330    devicePtr dp(new INDI::BaseDriver());
    282331    XMLAtt *ap;
    283332    char * device_name;
     
    293342    device_name = valuXMLAtt(ap);
    294343
    295     dp = new INDI::BaseDriver();
    296344    dp->setMediator(this);
    297345    dp->setDeviceName(device_name);
     
    299347    cDevices.push_back(dp);
    300348
    301     newDevice();
     349    newDevice(device_name);
    302350
    303351    /* ok */
    304     return dp;
     352    return dp.get();
    305353}
    306354
     
    467515void INDI::BaseClient::setBLOBMode(BLOBHandling blobH, const char *dev, const char *prop)
    468516{
    469     char blobOpenTag[64];
    470 
    471     if (dev)
    472     {
    473         if (prop)
    474             snprintf(blobOpenTag, 64, "<enableBLOB device='%s' name='%s'>", dev, prop);
    475         else
    476             snprintf(blobOpenTag, 64, "<enableBLOB device='%s'>", dev);
    477     }
    478     else
    479         snprintf(blobOpenTag, 64, "<enableBLOB>", dev, prop);
    480 
     517    char blobOpenTag[MAXRBUF];
     518
     519    if (!dev[0])
     520        return;
     521
     522   if (prop != NULL)
     523           snprintf(blobOpenTag, MAXRBUF, "<enableBLOB device='%s' name='%s'>", dev, prop);
     524   else
     525          snprintf(blobOpenTag, MAXRBUF, "<enableBLOB device='%s'>", dev);
    481526
    482527    switch (blobH)
  • BAORadio/libindi/libindi/libs/indibase/baseclient.h

    r502 r504  
    44#include <vector>
    55#include <map>
     6#include <boost/shared_ptr.hpp>
    67#include <string>
    78
     
    3233public:
    3334    enum { INDI_DEVICE_NOT_FOUND=-1, INDI_PROPERTY_INVALID=-2, INDI_PROPERTY_DUPLICATED = -3, INDI_DISPATCH_ERROR=-4 };
     35    typedef boost::shared_ptr<INDI::BaseDriver> devicePtr;
    3436
    3537    BaseClient();
    36     virtual ~BaseClient();
     38    ~BaseClient();
    3739
    3840    /** \brief Set the server host name and port
     
    5759        \note This function blocks until connection is either successull or unsuccessful.
    5860    */
    59     bool connect();
     61    bool connectServer();
    6062
    6163    /** \brief Disconnect from INDI server.
    6264
    6365        Disconnects from INDI servers. Any devices previously created will be deleted and memory cleared.
     66        \return True if disconnection is successful, false otherwise.
    6467    */
    65     void disconnect();
     68    bool disconnectServer();
    6669
     70    /** \brief Connect/Disconnect to INDI driver
     71        \param status If true, the client will attempt to turn on CONNECTION property within the driver (i.e. turn on the device).
     72         Otherwise, CONNECTION will be turned off.
     73        \param deviceName Name of the device to connect to.
     74    */
     75    void setDriverConnection(bool status, const char *deviceName);
    6776
    6877    /** \param deviceName Name of device to search for in the list of devices owned by INDI server,
    6978         \returns If \e deviceName exists, it returns an instance of the device. Otherwise, it returns NULL.
    7079    */
    71     INDI::BaseDriver * getDevice(const char * deviceName);
     80    INDI::BaseDriver * getDriver(const char * deviceName);
    7281
    7382    /** \returns Returns a vector of all devices created in the client.
    7483    */
    75     const vector<INDI::BaseDriver *> & getDevices() const { return cDevices; }
     84    const vector<devicePtr> & getDrivers() const { return cDevices; }
    7685
    7786    /** \brief Set Binary Large Object policy mode
     
    8695      If \e dev and \e prop are supplied, then the BLOB handling policy is set for this particular device and property.
    8796      if \e prop is NULL, then the BLOB policy applies to the whole device.
    88       if \e dev is NULL, then the BLOB policy applies to all devices owned by INDI server.
     97
    8998
    9099      \param blobH BLOB handling policy
    91       \param dev name of device
    92       \param prop name of property
     100      \param dev name of device, required.
     101      \param prop name of property, optional.
    93102    */
    94     void setBLOBMode(BLOBHandling blobH, const char *dev = NULL, const char *prop = NULL);
     103    void setBLOBMode(BLOBHandling blobH, const char *dev, const char *prop = NULL);
    95104
    96105    // Update
     
    143152    pthread_t listen_thread;
    144153
    145     vector<INDI::BaseDriver *> cDevices;
     154    vector<devicePtr> cDevices;
    146155    vector<string> cDeviceNames;
    147156
    148157    string cServer;
    149158    unsigned int cPort;
     159    bool sConnected;
    150160
    151161    // Parse & FILE buffers for IO
     
    153163    LilXML *lillp;                      /* XML parser context */
    154164    FILE *svrwfp;                       /* FILE * to talk to server */
    155     FILE *svrrfp;                       /* FILE * to read from server */
    156165
    157166};
  • BAORadio/libindi/libindi/libs/indibase/basedriver.cpp

    r502 r504  
    1313    mediator = NULL;
    1414    lp = newLilXML();
     15
     16    if (getenv("INDIDEV") != NULL)
     17    {
     18        strncpy(deviceID, getenv("INDIDEV"), MAXINDINAME);
     19        putenv("INDIDEV=");
     20    }
    1521}
    1622
     
    1824INDI::BaseDriver::~BaseDriver()
    1925{
    20     std::vector<INumberVectorProperty *>::const_iterator numi;
    21     std::vector<ISwitchVectorProperty *>::const_iterator switchi;
    22     std::vector<ITextVectorProperty *>::const_iterator texti;
    23     std::vector<ILightVectorProperty *>::const_iterator lighti;
    24     std::vector<IBLOBVectorProperty *>::const_iterator blobi;
    25 
    2626    delLilXML (lp);
    27     pAll.clear();
    28 
    29     for ( numi = pNumbers.begin(); numi != pNumbers.end(); numi++)
    30         delete (*numi);
    31 
    32    for ( switchi = pSwitches.begin(); switchi != pSwitches.end(); switchi++)
    33         delete (*switchi);
    34 
    35    for ( texti = pTexts.begin(); texti != pTexts.end(); texti++)
    36         delete (*texti);
    37 
    38    for ( lighti = pLights.begin(); lighti != pLights.end(); lighti++)
    39         delete (*lighti);
    40 
    41    for ( blobi = pBlobs.begin(); blobi != pBlobs.end(); blobi++)
    42         delete (*blobi);
    4327}
    4428
    4529INumberVectorProperty * INDI::BaseDriver::getNumber(const char *name)
    4630{
    47     std::vector<INumberVectorProperty *>::const_iterator numi;
    48 
    49     for ( numi = pNumbers.begin(); numi != pNumbers.end(); numi++)
    50         if (!strcmp(name, (*numi)->name))
    51             return *numi;
    52 
    53     return NULL;
    54 
     31    INumberVectorProperty * nvp = NULL;
     32
     33    nvp = static_cast<INumberVectorProperty *> (getProperty(name, INDI_NUMBER));
     34
     35    return nvp;
    5536}
    5637
    5738ITextVectorProperty * INDI::BaseDriver::getText(const char *name)
    5839{
    59     std::vector<ITextVectorProperty *>::const_iterator texti;
    60 
    61     for ( texti = pTexts.begin(); texti != pTexts.end(); texti++)
    62         if (!strcmp(name, (*texti)->name))
    63             return *texti;
    64 
    65     return NULL;
     40    ITextVectorProperty * tvp = NULL;
     41
     42    tvp = static_cast<ITextVectorProperty *> (getProperty(name, INDI_TEXT));
     43
     44    return tvp;
    6645}
    6746
    6847ISwitchVectorProperty * INDI::BaseDriver::getSwitch(const char *name)
    6948{
    70     std::vector<ISwitchVectorProperty *>::const_iterator switchi;
    71 
    72     for ( switchi = pSwitches.begin(); switchi != pSwitches.end(); switchi++)
    73         if (!strcmp(name, (*switchi)->name))
    74             return *switchi;
    75 
    76     return NULL;
    77 
     49    ISwitchVectorProperty * svp = NULL;
     50
     51    svp = static_cast<ISwitchVectorProperty *> (getProperty(name, INDI_SWITCH));
     52
     53    return svp;
    7854}
    7955
    8056ILightVectorProperty * INDI::BaseDriver::getLight(const char *name)
    8157{
    82     std::vector<ILightVectorProperty *>::const_iterator lighti;
    83 
    84     for ( lighti = pLights.begin(); lighti != pLights.end(); lighti++)
    85         if (!strcmp(name, (*lighti)->name))
    86             return *lighti;
    87 
    88     return NULL;
    89 
     58    ILightVectorProperty * lvp = NULL;
     59
     60    lvp = static_cast<ILightVectorProperty *> (getProperty(name, INDI_LIGHT));
     61
     62    return lvp;
    9063}
    9164
    9265IBLOBVectorProperty * INDI::BaseDriver::getBLOB(const char *name)
    93 {
    94     std::vector<IBLOBVectorProperty *>::const_iterator blobi;
    95 
    96     for ( blobi = pBlobs.begin(); blobi != pBlobs.end(); blobi++)
    97         if (!strcmp(name, (*blobi)->name))
    98             return *blobi;
    99 
    100     return NULL;
    101 }
    102 
    103 void * INDI::BaseDriver::getProperty(const char *name, INDI_TYPE & type)
    104 {
    105     std::vector<pOrder>::const_iterator orderi;
     66{       
     67  IBLOBVectorProperty * bvp = NULL;
     68
     69  bvp = static_cast<IBLOBVectorProperty *> (getProperty(name, INDI_BLOB));
     70
     71  return bvp;
     72}
     73
     74void * INDI::BaseDriver::getProperty(const char *name, INDI_TYPE type)
     75{
     76    std::map< boost::shared_ptr<void>, INDI_TYPE>::iterator orderi;
    10677
    10778    INumberVectorProperty *nvp;
     
    11081    ILightVectorProperty *lvp;
    11182    IBLOBVectorProperty *bvp;
    112     int i=0;
    113 
    114     for (i=0, orderi = pAll.begin(); orderi != pAll.end(); orderi++, i++)
    115     {
    116         switch ( (*orderi).type)
     83
     84    for (orderi = pAll.begin(); orderi != pAll.end(); orderi++)
     85    {
     86        if (type != INDI_UNKNOWN &&  orderi->second != type)
     87            continue;
     88
     89        switch (orderi->second)
    11790        {
    11891        case INDI_NUMBER:
    119             nvp = static_cast<INumberVectorProperty *>((*orderi).p);
     92            nvp = static_cast<INumberVectorProperty *>((orderi->first).get());
    12093            if (!strcmp(name, nvp->name))
    121             {
    122                 type = INDI_NUMBER;
    123                 return (*orderi).p;
    124             }
    125 
     94                return (orderi->first).get();
    12695             break;
    12796        case INDI_TEXT:
    128              tvp = static_cast<ITextVectorProperty *>((*orderi).p);
     97             tvp = static_cast<ITextVectorProperty *>((orderi->first).get());
    12998             if (!strcmp(name, tvp->name))
    130              {
    131                  type = INDI_TEXT;
    132                  return (*orderi).p;
    133              }
     99                return (orderi->first).get();
    134100             break;
    135101        case INDI_SWITCH:
    136              svp = static_cast<ISwitchVectorProperty *>((*orderi).p);
     102             svp = static_cast<ISwitchVectorProperty *>((orderi->first).get());
    137103             if (!strcmp(name, svp->name))
    138              {
    139                  type = INDI_SWITCH;
    140                  return (*orderi).p;
    141              }
     104                 return (orderi->first).get();
    142105             break;
    143106        case INDI_LIGHT:
    144              lvp = static_cast<ILightVectorProperty *>((*orderi).p);
     107             lvp = static_cast<ILightVectorProperty *>((orderi->first).get());
    145108             if (!strcmp(name, lvp->name))
    146              {
    147                  type = INDI_LIGHT;
    148                  return (*orderi).p;
    149              }
     109                 return (orderi->first).get();
    150110             break;
    151111        case INDI_BLOB:
    152              bvp = static_cast<IBLOBVectorProperty *>((*orderi).p);
     112             bvp = static_cast<IBLOBVectorProperty *>((orderi->first).get());
    153113             if (!strcmp(name, bvp->name))
    154              {
    155                  type = INDI_BLOB;
    156                  return (*orderi).p;
    157              }
     114                 return (orderi->first).get();
    158115             break;
    159116        }
     117
    160118    }
    161119
     
    165123int INDI::BaseDriver::removeProperty(const char *name)
    166124{
    167     std::vector<pOrder>::iterator orderi;
     125    std::map< boost::shared_ptr<void>, INDI_TYPE>::iterator orderi;
    168126
    169127    INumberVectorProperty *nvp;
     
    175133    for (orderi = pAll.begin(); orderi != pAll.end(); orderi++)
    176134    {
    177         switch ( (*orderi).type)
     135        switch (orderi->second)
    178136        {
    179137        case INDI_NUMBER:
    180             nvp = static_cast<INumberVectorProperty *>((*orderi).p);
     138            nvp = static_cast<INumberVectorProperty *>((orderi->first).get());
    181139            if (!strcmp(name, nvp->name))
    182140            {
    183141                 pAll.erase(orderi);
    184                  delete (nvp);
    185142                 return 0;
    186143             }
    187144             break;
    188145        case INDI_TEXT:
    189              tvp = static_cast<ITextVectorProperty *>((*orderi).p);
     146             tvp = static_cast<ITextVectorProperty *>((orderi->first).get());
    190147             if (!strcmp(name, tvp->name))
    191148             {
    192149                  pAll.erase(orderi);
    193                   delete (tvp);
    194150                  return 0;
    195151              }
    196152             break;
    197153        case INDI_SWITCH:
    198              svp = static_cast<ISwitchVectorProperty *>((*orderi).p);
     154             svp = static_cast<ISwitchVectorProperty *>((orderi->first).get());
    199155             if (!strcmp(name, svp->name))
    200156             {
    201157                  pAll.erase(orderi);
    202                   delete (svp);
    203158                  return 0;
    204159              }
    205160             break;
    206161        case INDI_LIGHT:
    207              lvp = static_cast<ILightVectorProperty *>((*orderi).p);
     162             lvp = static_cast<ILightVectorProperty *>((orderi->first).get());
    208163             if (!strcmp(name, lvp->name))
    209164             {
    210165                  pAll.erase(orderi);
    211                   delete (lvp);
    212166                  return 0;
    213167              }
    214168             break;
    215169        case INDI_BLOB:
    216              bvp = static_cast<IBLOBVectorProperty *>((*orderi).p);
     170             bvp = static_cast<IBLOBVectorProperty *>((orderi->first).get());
    217171             if (!strcmp(name, bvp->name))
    218172             {
    219173                  pAll.erase(orderi);
    220                   delete (bvp);
    221174                  return 0;
    222175              }
     
    255208            buildProp(root, errmsg);
    256209
    257 
    258 
    259210    /**************************************************************************/
    260 
    261211}
    262212
     
    268218    XMLEle *ep = NULL;
    269219    char *rtag, *rname, *rdev;
    270     INDI_TYPE type;
     220    //INDI_TYPE type;
    271221    double timeout=0;
    272222
     
    277227        return -1;
    278228
    279     if (!deviceID[0])
     229   /* if (!deviceID[0])
    280230    {
    281231        if (getenv("INDIDEV"))
     
    283233        else
    284234            strncpy(deviceID, rdev, MAXINDINAME);
    285     }
    286 
    287     if (getProperty(rname, type) != NULL)
     235    }*/
     236
     237    if (!deviceID[0])
     238        strncpy(deviceID, rdev, MAXINDINAME);
     239
     240    //if (getProperty(rname, type) != NULL)
     241    if (getProperty(rname) != NULL)
    288242        return INDI::BaseClient::INDI_PROPERTY_DUPLICATED;
    289243
    290     if (crackIPerm(findXMLAttValu(root, "perm"), &perm) < 0)
    291     {
    292         IDLog("Error extracting %s permission (%s)", rname, findXMLAttValu(root, "perm"));
     244    if (strcmp (rtag, "defLightVector") && crackIPerm(findXMLAttValu(root, "perm"), &perm) < 0)
     245    {
     246        IDLog("Error extracting %s permission (%s)\n", rname, findXMLAttValu(root, "perm"));
    293247        return -1;
    294248    }
     
    298252    if (crackIPState (findXMLAttValu(root, "state"), &state) < 0)
    299253    {
    300         IDLog("Error extracting %s state (%s)", rname, findXMLAttValu(root, "state"));
     254        IDLog("Error extracting %s state (%s)\n", rname, findXMLAttValu(root, "state"));
    301255        return -1;
    302256    }
     
    305259    {
    306260
    307         INumberVectorProperty *nvp = new INumberVectorProperty;
     261        numberPtr nvp(new INumberVectorProperty);
     262        //INumberVectorProperty *nvp = new INumberVectorProperty;
     263        //INumberVectorProperty *nvp = (INumberVectorProperty *) malloc(sizeof(INumberVectorProperty));
    308264        INumber *np = NULL;
    309265        int n=0;
     
    325281            np = (INumber *) realloc(np, (n+1) * sizeof(INumber));
    326282
    327             np[n].nvp = nvp;
     283            np[n].nvp = nvp.get();
    328284
    329285            XMLAtt *na = findXMLAtt (ep, "name");
     
    364320        nvp->nnp = n;
    365321        nvp->np  = np;
    366         pNumbers.push_back(nvp);
    367         pOrder o = { INDI_NUMBER, nvp };
    368         pAll.push_back(o);
    369         IDLog("Adding number property %s to list.\n", nvp->name);
     322        //orderPtr o(new pOrder);
     323        //o->p = &nvp;
     324        //o->type = INDI_NUMBER;
     325        //pAll.push_back(o);
     326        pAll[nvp] = INDI_NUMBER;
     327        //IDLog("Adding number property %s to list.\n", nvp->name);
     328        if (mediator)
     329            mediator->newProperty(nvp->device, nvp->name);
    370330    }
    371331    else
     
    374334  else if (!strcmp (rtag, "defSwitchVector"))
    375335        {
    376             ISwitchVectorProperty *svp = new ISwitchVectorProperty;
     336            switchPtr svp(new ISwitchVectorProperty);
     337            //ISwitchVectorProperty *svp = new ISwitchVectorProperty;
     338            //ISwitchVectorProperty *svp = (ISwitchVectorProperty *) malloc(sizeof(ISwitchVectorProperty));
    377339            ISwitch *sp = NULL;
    378340            int n=0;
     
    398360                sp = (ISwitch *) realloc(sp, (n+1) * sizeof(ISwitch));
    399361
    400                 sp[n].svp = svp;
     362                sp[n].svp = svp.get();
    401363
    402364                XMLAtt *na = findXMLAtt (ep, "name");
     
    418380            svp->nsp = n;
    419381            svp->sp  = sp;
    420             pSwitches.push_back(svp);
    421             pOrder o = { INDI_SWITCH, svp };
    422             pAll.push_back(o);
    423             IDLog("Adding Switch property %s to list.\n", svp->name);
     382            //orderPtr o(new pOrder);
     383            //o->p = &svp;
     384            //o->type = INDI_SWITCH;
     385            //pAll.push_back(o);
     386            pAll[svp] = INDI_SWITCH;
     387            //IDLog("Adding Switch property %s to list.\n", svp->name);
     388            if (mediator)
     389                mediator->newProperty(svp->device, svp->name);
    424390        }
    425391        else
     
    430396    {
    431397
    432         ITextVectorProperty *tvp = new ITextVectorProperty;
     398        //ITextVectorProperty *tvp = new ITextVectorProperty;
     399        //ITextVectorProperty *tvp = (ITextVectorProperty *) malloc(sizeof(ITextVectorProperty));
     400        textPtr tvp(new ITextVectorProperty);
    433401        IText *tp = NULL;
    434402        int n=0;
     
    450418            tp = (IText *) realloc(tp, (n+1) * sizeof(IText));
    451419
    452             tp[n].tvp = tvp;
     420            tp[n].tvp = tvp.get();
    453421
    454422            XMLAtt *na = findXMLAtt (ep, "name");
     
    471439        tvp->ntp = n;
    472440        tvp->tp  = tp;
    473         pTexts.push_back(tvp);
    474         pOrder o = { INDI_TEXT, tvp };
    475         pAll.push_back(o);
    476         IDLog("Adding Text property %s to list.\n", tvp->name);
     441        //orderPtr o(new pOrder);
     442        //o->p = &tvp;
     443        //o->type = INDI_TEXT;
     444        //pAll.push_back(o);
     445        pAll[tvp] = INDI_TEXT;
     446        //IDLog("Adding Text property %s to list.\n", tvp->name);
     447        if (mediator)
     448            mediator->newProperty(tvp->device, tvp->name);
    477449    }
    478450    else
     
    482454    {
    483455
    484         ILightVectorProperty *lvp = new ILightVectorProperty;
     456        //ILightVectorProperty *lvp = new ILightVectorProperty;
     457        //ILightVectorProperty *lvp = (ILightVectorProperty *) malloc(sizeof(ILightVectorProperty));
     458        lightPtr lvp(new ILightVectorProperty);
    485459        ILight *lp = NULL;
    486460        int n=0;
     
    500474            lp = (ILight *) realloc(lp, (n+1) * sizeof(ILight));
    501475
    502             lp[n].lvp = lvp;
     476            lp[n].lvp = lvp.get();
    503477
    504478            XMLAtt *na = findXMLAtt (ep, "name");
     
    521495        lvp->nlp = n;
    522496        lvp->lp  = lp;
    523         pLights.push_back(lvp);
    524         pOrder o = { INDI_LIGHT, lvp };
    525         pAll.push_back(o);
    526         IDLog("Adding Light property %s to list.\n", lvp->name);
     497        //orderPtr o(new pOrder);
     498        //o->p = &lvp;
     499        //o->type = INDI_LIGHT;
     500        //pAll.push_back(o);
     501        pAll[lvp] = INDI_LIGHT;
     502        //IDLog("Adding Light property %s to list.\n", lvp->name);
     503        if (mediator)
     504            mediator->newProperty(lvp->device, lvp->name);
    527505    }
    528506    else
     
    532510    {
    533511
    534         IBLOBVectorProperty *bvp = new IBLOBVectorProperty;
     512        //IBLOBVectorProperty *bvp = new IBLOBVectorProperty;
     513        //IBLOBVectorProperty *bvp = (IBLOBVectorProperty *) malloc(sizeof(IBLOBVectorProperty));
     514        blobPtr bvp(new IBLOBVectorProperty);
    535515        IBLOB *bp = NULL;
    536516        int n=0;
     
    550530            bp = (IBLOB *) realloc(bp, (n+1) * sizeof(IBLOB));
    551531
    552             bp[n].bvp = bvp;
     532            bp[n].bvp = bvp.get();
    553533
    554534            XMLAtt *na = findXMLAtt (ep, "name");
     
    580560        bvp->nbp = n;
    581561        bvp->bp  = bp;
    582         pBlobs.push_back(bvp);
    583         pOrder o = { INDI_BLOB, bvp };
    584         pAll.push_back(o);
    585         IDLog("Adding BLOB property %s to list.\n", bvp->name);
     562        //orderPtr o(new pOrder);
     563        //o->p = &bvp;
     564        //o->type = INDI_BLOB;
     565        //pAll.push_back(o);
     566        pAll[bvp] = INDI_BLOB;
     567        //IDLog("Adding BLOB property %s to list.\n", bvp->name);
     568        if (mediator)
     569            mediator->newProperty(bvp->device, bvp->name);
    586570    }
    587571    else
     
    609593        return false;
    610594
    611 }
    612 
    613 void INDI::BaseDriver::setConnected(bool status)
    614 {
    615     ISwitch *sp = NULL;
    616     ISwitchVectorProperty *svp = getSwitch("CONNECTION");
    617     if (!svp)
    618         return;
    619 
    620     IUResetSwitch(svp);
    621 
    622     // Connect
    623     if (status)
    624     {
    625         sp = IUFindSwitch(svp, "CONNECT");
    626         if (!sp)
    627             return;
    628         sp->s = ISS_ON;
    629     }
    630     // Disconnect
    631     else
    632     {
    633         sp = IUFindSwitch(svp, "DISCONNECT");
    634         if (!sp)
    635             return;
    636         sp->s = ISS_ON;
    637     }
    638 
    639     svp->s = IPS_OK;
    640595}
    641596
     
    958913}
    959914
     915void INDI::BaseDriver::registerProperty(void *p, INDI_TYPE type)
     916{
     917
     918
     919    if (type == INDI_NUMBER)
     920    {
     921        INumberVectorProperty *nvp = static_cast<INumberVectorProperty *> (p);
     922        if (getProperty(nvp->name, INDI_NUMBER) != NULL)
     923            return;
     924
     925        numberPtr ovp(nvp);
     926
     927        pAll[ovp] = INDI_NUMBER;
     928    }
     929    else if (type == INDI_TEXT)
     930    {
     931       ITextVectorProperty *tvp = static_cast<ITextVectorProperty *> (p);
     932       if (getProperty(tvp->name, INDI_TEXT) != NULL)
     933           return;
     934
     935       textPtr ovp(tvp);
     936       //o->p = &ovp;
     937
     938       pAll[ovp] = INDI_TEXT;
     939   }
     940    else if (type == INDI_SWITCH)
     941    {
     942       ISwitchVectorProperty *svp = static_cast<ISwitchVectorProperty *> (p);
     943       if (getProperty(svp->name, INDI_SWITCH) != NULL)
     944           return;
     945
     946       switchPtr ovp(svp);
     947       //o->p = &ovp;
     948
     949       IDLog("Registering switch %s\n", svp->name);
     950
     951       pAll[ovp] = INDI_SWITCH;
     952    }
     953    else if (type == INDI_LIGHT)
     954    {
     955       ILightVectorProperty *lvp = static_cast<ILightVectorProperty *> (p);
     956       if (getProperty(lvp->name, INDI_LIGHT) != NULL)
     957           return;
     958
     959       lightPtr ovp(lvp);
     960       //o->p = &ovp;
     961       pAll[ovp] = INDI_LIGHT;
     962   }
     963    else if (type == INDI_BLOB)
     964    {
     965       IBLOBVectorProperty *bvp = static_cast<IBLOBVectorProperty *> (p);
     966       if (getProperty(bvp->name, INDI_BLOB) != NULL)
     967           return;
     968
     969       blobPtr ovp(bvp);
     970       //o->p = &ovp;
     971
     972       pAll[ovp] = INDI_BLOB;
     973    }
     974
     975}
     976
  • BAORadio/libindi/libindi/libs/indibase/basedriver.h

    r502 r504  
    22#define INDIBASEDRIVER_H
    33
    4 #include <vector>
     4#include <boost/shared_ptr.hpp>
    55#include <map>
    66#include <string>
     
    2626public:
    2727    BaseDriver();
    28     virtual ~BaseDriver();
     28    ~BaseDriver();
    2929
    3030    /*! INDI error codes. */
     
    3838
    3939    /*! INDI property type */
    40     enum INDI_TYPE
     40    typedef enum
    4141    {
    4242        INDI_NUMBER, /*!< INumberVectorProperty. */
     
    4444        INDI_TEXT,   /*!< ITextVectorProperty. */
    4545        INDI_LIGHT,  /*!< ILightVectorProperty. */
    46         INDI_BLOB    /*!< IBLOBVectorProperty. */
    47     };
     46        INDI_BLOB,    /*!< IBLOBVectorProperty. */
     47        INDI_UNKNOWN
     48    } INDI_TYPE;
    4849
    4950    /** \return Return vector number property given its name */
     
    5758    /** \return Return vector BLOB property given its name */
    5859    IBLOBVectorProperty * getBLOB(const char *name);
     60
     61    void registerProperty(void *p, INDI_TYPE type);
    5962
    6063    /** \brief Remove a property
     
    7477
    7578    */
    76     void * getProperty(const char *name, INDI_TYPE & type);
     79    void * getProperty(const char *name, INDI_TYPE type = INDI_UNKNOWN);
    7780
    7881    /** \brief Build driver properties from a skeleton file.
     
    9093    /** \return True if the device is connected (CONNECT=ON), False otherwise */
    9194    bool isConnected();
    92     /** \brief Connect or Disconnect a device.
    93       \param status If true, the driver will attempt to connect to the device (CONNECT=ON). If false, it will attempt
    94 to disconnect the device.
    95     */
    96     virtual void setConnected(bool status);
     95
    9796
    9897    /** \brief Set the device name
     
    10099      */
    101100    void setDeviceName(const char *dev);
     101
    102102    /** \return Returns the device name */
    103103    const char *deviceName();
     
    107107    */
    108108    void addMessage(const char *msg);
    109     //** \returns Returns the contents of the driver's message queue. *;
     109
     110    /** \return Returns the contents of the driver's message queue. */
    110111    const char *message() { return messageQueue.c_str(); }
    111112
    112113    /** \brief Set the driver's mediator to receive notification of news devices and updated property values. */
    113114    void setMediator(INDI::BaseMediator *med) { mediator = med; }
     115
    114116    /** \returns Get the meditator assigned to this driver */
    115117    INDI::BaseMediator * getMediator() { return mediator; }
     118
    116119
    117120protected:
     
    120123      \param root XML element to parse and build.
    121124      \param errmsg buffer to store error message in parsing fails.
    122 
    123125      \return 0 if parsing is successful, -1 otherwise and errmsg is set */
    124126    int buildProp(XMLEle *root, char *errmsg);
     
    133135    char deviceID[MAXINDINAME];
    134136
     137    typedef boost::shared_ptr<INumberVectorProperty> numberPtr;
     138    typedef boost::shared_ptr<ITextVectorProperty> textPtr;
     139    typedef boost::shared_ptr<ISwitchVectorProperty> switchPtr;
     140    typedef boost::shared_ptr<ILightVectorProperty> lightPtr;
     141    typedef boost::shared_ptr<IBLOBVectorProperty> blobPtr;
     142
    135143private:
    136144
    137     typedef struct
    138     {
    139         INDI_TYPE type;
    140         void *p;
    141     } pOrder;
    142 
    143     std::vector<INumberVectorProperty *> pNumbers;
    144     std::vector<ITextVectorProperty *> pTexts;
    145     std::vector<ISwitchVectorProperty *> pSwitches;
    146     std::vector<ILightVectorProperty *> pLights;
    147     std::vector<IBLOBVectorProperty *> pBlobs;
     145    std::map< boost::shared_ptr<void>, INDI_TYPE> pAll;
    148146
    149147    LilXML *lp;
    150 
    151     std::vector<pOrder> pAll;
    152148
    153149    std::string messageQueue;
  • BAORadio/libindi/libindi/libs/indibase/defaultdriver.cpp

    r502 r504  
    88#include "base64.h"
    99
     10void timerfunc(void *t)
     11{
     12    //fprintf(stderr,"Got a timer hit with %x\n",t);
     13    INDI::DefaultDriver *devPtr = static_cast<INDI::DefaultDriver *> (t);
     14    if (devPtr != NULL)
     15    {
     16        //  this was for my device
     17        //  but we dont have a way of telling
     18        //  WHICH timer was hit :(
     19        devPtr->TimerHit();
     20    }
     21    return;
     22}
     23
    1024
    1125INDI::DefaultDriver::DefaultDriver()
     
    1327    pDebug = false;
    1428    pSimulation = false;
     29
     30    //switchPtr conSw(new ISwitchVectorProperty);
     31    ConnectionSP = new ISwitchVectorProperty;
     32
     33    IUFillSwitch(&ConnectionS[0],"CONNECT","Connect",ISS_OFF);
     34    IUFillSwitch(&ConnectionS[1],"DISCONNECT","Disconnect",ISS_ON);
     35    IUFillSwitchVector(ConnectionSP,ConnectionS,2,deviceName(),"CONNECTION","Connection","Main Control",IP_RW,ISR_1OFMANY,60,IPS_IDLE);
     36
     37    registerProperty(ConnectionSP, INDI_SWITCH);
     38
    1539}
    1640
     
    3256bool INDI::DefaultDriver::saveConfig()
    3357{
    34     std::vector<pOrder>::const_iterator orderi;
     58    //std::vector<orderPtr>::iterator orderi;
     59
     60    std::map< boost::shared_ptr<void>, INDI_TYPE>::iterator orderi;
     61
    3562    ISwitchVectorProperty *svp=NULL;
     63    INumberVectorProperty *nvp=NULL;
     64    ITextVectorProperty   *tvp=NULL;
     65    IBLOBVectorProperty   *bvp=NULL;
    3666    char errmsg[MAXRBUF];
    3767    FILE *fp = NULL;
     
    4979    for (orderi = pAll.begin(); orderi != pAll.end(); orderi++)
    5080    {
    51         switch ( (*orderi).type)
     81
     82        switch (orderi->second)
    5283        {
    5384        case INDI_NUMBER:
    54              IUSaveConfigNumber(fp, static_cast<INumberVectorProperty *> ((*orderi).p));
     85             nvp = static_cast<INumberVectorProperty *>((orderi->first).get());
     86             IDLog("Trying to save config for number %s\n", nvp->name);
     87             IUSaveConfigNumber(fp, nvp);
    5588             break;
    5689        case INDI_TEXT:
    57              IUSaveConfigText(fp, static_cast<ITextVectorProperty *> ((*orderi).p));
     90             tvp = static_cast<ITextVectorProperty *>((orderi->first).get());
     91             IUSaveConfigText(fp, tvp);
    5892             break;
    5993        case INDI_SWITCH:
    60              svp = static_cast<ISwitchVectorProperty *> ((*orderi).p);
     94             svp = static_cast<ISwitchVectorProperty *>((orderi->first).get());
    6195             /* Never save CONNECTION property. Don't save switches with no switches on if the rule is one of many */
    6296             if (!strcmp(svp->name, "CONNECTION") || (svp->r == ISR_1OFMANY && !IUFindOnSwitch(svp)))
     
    6599             break;
    66100        case INDI_BLOB:
    67              IUSaveConfigBLOB(fp, static_cast<IBLOBVectorProperty *> ((*orderi).p));
     101             bvp = static_cast<IBLOBVectorProperty *>((orderi->first).get());
     102             IUSaveConfigBLOB(fp, bvp);
    68103             break;
    69104        }
     
    116151    if (!svp)
    117152        return false;
     153
     154     if(!strcmp(svp->name,ConnectionSP->name))
     155     {
     156        bool rc;
     157       
     158      for (int i=0; i < n; i++)
     159      {
     160        if ( !strcmp(names[i], "CONNECT") && (states[i] == ISS_ON))
     161        {
     162            // If not connected, attempt to connect
     163            if (isConnected() == false)
     164            {
     165                rc = Connect();
     166
     167                // If connection is successful, set it thus
     168                if (rc)
     169                  setConnected(true);
     170                else
     171                  setConnected(false, IPS_ALERT);
     172
     173                updateProperties();
     174            }
     175            else
     176                // Just tell client we're connected yes
     177                setConnected(true);
     178        }
     179        else if ( !strcmp(names[i], "DISCONNECT") && (states[i] == ISS_ON))
     180        {
     181            // If connected, then true to disconnect.
     182            if (isConnected() == true)
     183                rc = Disconnect();
     184            else
     185                rc = true;
     186
     187            if (rc)
     188                setConnected(false, IPS_IDLE);
     189            else
     190                setConnected(true, IPS_ALERT);
     191
     192            updateProperties();
     193        }
     194    }
     195
     196        return true;
     197    }
     198
    118199
    119200    if (!strcmp(svp->name, "DEBUG"))
     
    174255}
    175256
    176 void INDI::DefaultDriver::addAuxControls()
     257void INDI::DefaultDriver::addDebugControl()
    177258{
    178259    /**************************************************************************/
     
    180261    if (!DebugSP)
    181262    {
    182         DebugSP = new ISwitchVectorProperty;
     263        switchPtr debSw(new ISwitchVectorProperty);
     264        DebugSP = debSw.get();
    183265        IUFillSwitch(&DebugS[0], "ENABLE", "Enable", ISS_OFF);
    184266        IUFillSwitch(&DebugS[1], "DISABLE", "Disable", ISS_ON);
    185267        IUFillSwitchVector(DebugSP, DebugS, NARRAY(DebugS), deviceID, "DEBUG", "Debug", "Options", IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
    186         pSwitches.push_back(DebugSP);
    187         pOrder debo = {INDI_SWITCH, DebugSP};
    188         pAll.push_back(debo);
     268        pAll[debSw] = INDI_SWITCH;
    189269    }
    190270    else
     
    197277    /**************************************************************************/
    198278
     279}
     280
     281void INDI::DefaultDriver::addSimulationControl()
     282{
    199283    /**************************************************************************/
    200284    SimulationSP = getSwitch("SIMULATION");
    201285    if (!SimulationSP)
    202286    {
    203         SimulationSP = new ISwitchVectorProperty;
     287        switchPtr simSw(new ISwitchVectorProperty);
     288        SimulationSP = simSw.get();
    204289        IUFillSwitch(&SimulationS[0], "ENABLE", "Enable", ISS_OFF);
    205290        IUFillSwitch(&SimulationS[1], "DISABLE", "Disable", ISS_ON);
    206291        IUFillSwitchVector(SimulationSP, SimulationS, NARRAY(SimulationS), deviceID, "SIMULATION", "Simulation", "Options", IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
    207         pSwitches.push_back(SimulationSP);
    208         pOrder simo = {INDI_SWITCH, SimulationSP};
    209         pAll.push_back(simo);
     292        pAll[simSw] = INDI_SWITCH;
    210293    }
    211294    else
     
    216299                pSimulation = true;
    217300    }
    218 
     301}
     302
     303void INDI::DefaultDriver::addConfigurationControl()
     304{
    219305    /**************************************************************************/
    220306    ConfigProcessSP = getSwitch("CONFIG_PROCESS");
    221307    if (!ConfigProcessSP)
    222308    {
    223         ConfigProcessSP = new ISwitchVectorProperty;
     309        switchPtr configSw(new ISwitchVectorProperty);
     310        ConfigProcessSP = configSw.get();
    224311        IUFillSwitch(&ConfigProcessS[0], "CONFIG_LOAD", "Load", ISS_OFF);
    225312        IUFillSwitch(&ConfigProcessS[1], "CONFIG_SAVE", "Save", ISS_OFF);
    226313        IUFillSwitch(&ConfigProcessS[2], "CONFIG_DEFAULT", "Default", ISS_OFF);
    227314        IUFillSwitchVector(ConfigProcessSP, ConfigProcessS, NARRAY(ConfigProcessS), deviceID, "CONFIG_PROCESS", "Configuration", "Options", IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
    228         pSwitches.push_back(ConfigProcessSP);
    229         pOrder cpono = {INDI_SWITCH, ConfigProcessSP};
    230         pAll.push_back(cpono);
     315        pAll[configSw] = INDI_SWITCH;
    231316    }
    232317    /**************************************************************************/
     
    234319}
    235320
     321void INDI::DefaultDriver::addAuxControls()
     322{
     323   addDebugControl();
     324   addSimulationControl();
     325   addConfigurationControl();
     326}
     327
    236328void INDI::DefaultDriver::setDebug(bool enable)
    237329{
     330    if (!DebugSP)
     331        return;
     332
    238333    if (pDebug == enable)
    239334    {
     
    242337        return;
    243338    }
    244 
    245     if (!DebugSP)
    246         return;
    247339
    248340    IUResetSwitch(DebugSP);
     
    275367void INDI::DefaultDriver::setSimulation(bool enable)
    276368{
     369    if (!SimulationSP)
     370        return;
     371
    277372   if (pSimulation == enable)
    278373   {
     
    281376       return;
    282377   }
    283 
    284    if (!SimulationSP)
    285        return;
    286378
    287379   IUResetSwitch(SimulationSP);
     
    324416void INDI::DefaultDriver::ISGetProperties (const char *dev)
    325417{
    326     std::vector<pOrder>::const_iterator orderi;
     418    std::map< boost::shared_ptr<void>, INDI_TYPE>::iterator orderi;
     419    static int isInit = 0;
     420
     421    //fprintf(stderr,"Enter ISGetProperties '%s'\n",dev);
     422    if(isInit == 0)
     423    {
     424        if(dev != NULL)
     425             setDeviceName(dev);
     426        else
     427        {
     428            char *envDev = getenv("INDIDEV");
     429            if (envDev != NULL)
     430                setDeviceName(envDev);
     431            else
     432               setDeviceName(getDefaultName());
     433        }
     434
     435        strncpy(ConnectionSP->device, deviceName(), MAXINDIDEVICE);
     436        initProperties();
     437        addConfigurationControl();
     438
     439        isInit = 1;
     440    }
    327441
    328442    for (orderi = pAll.begin(); orderi != pAll.end(); orderi++)
    329443    {
    330         switch ( (*orderi).type)
     444        switch (orderi->second)
    331445        {
    332446        case INDI_NUMBER:
    333              IDDefNumber(static_cast<INumberVectorProperty *>((*orderi).p) , NULL);
     447             IDDefNumber(static_cast<INumberVectorProperty *>((orderi->first).get()) , NULL);
    334448             break;
    335449        case INDI_TEXT:
    336              IDDefText(static_cast<ITextVectorProperty *>((*orderi).p) , NULL);
     450             IDDefText(static_cast<ITextVectorProperty *>((orderi->first).get()) , NULL);
    337451             break;
    338452        case INDI_SWITCH:
    339              IDDefSwitch(static_cast<ISwitchVectorProperty *>((*orderi).p) , NULL);
     453             IDDefSwitch(static_cast<ISwitchVectorProperty *>((orderi->first).get()) , NULL);
    340454             break;
    341455        case INDI_LIGHT:
    342              IDDefLight(static_cast<ILightVectorProperty *>((*orderi).p) , NULL);
     456             IDDefLight(static_cast<ILightVectorProperty *>((orderi->first).get()) , NULL);
    343457             break;
    344458        case INDI_BLOB:
    345              IDDefBLOB(static_cast<IBLOBVectorProperty *>((*orderi).p) , NULL);
     459             IDDefBLOB(static_cast<IBLOBVectorProperty *>((orderi->first).get()) , NULL);
    346460             break;
    347461        }
    348462    }
    349 
    350463}
    351464
    352465void INDI::DefaultDriver::resetProperties()
    353466{
    354     std::vector<INumberVectorProperty *>::const_iterator numi;
    355     std::vector<ISwitchVectorProperty *>::const_iterator switchi;
    356     std::vector<ITextVectorProperty *>::const_iterator texti;
    357     std::vector<ILightVectorProperty *>::const_iterator lighti;
    358     std::vector<IBLOBVectorProperty *>::const_iterator blobi;
     467    /*std::vector<numberPtr>::const_iterator numi;
     468    std::vector<switchPtr>::const_iterator switchi;
     469    std::vector<textPtr>::const_iterator texti;
     470    std::vector<lightPtr>::const_iterator lighti;
     471    std::vector<blobPtr>::const_iterator blobi;
    359472
    360473    for ( numi = pNumbers.begin(); numi != pNumbers.end(); numi++)
    361474    {
    362475        (*numi)->s = IPS_IDLE;
    363         IDSetNumber( (*numi), NULL);
     476        IDSetNumber( (*numi).get(), NULL);
    364477    }
    365478
     
    367480   {
    368481       (*switchi)->s = IPS_IDLE;
    369        IDSetSwitch( (*switchi), NULL);
     482       IDSetSwitch( (*switchi).get(), NULL);
    370483   }
    371484
     
    373486   {
    374487      (*texti)->s = IPS_IDLE;
    375       IDSetText( (*texti), NULL);
     488      IDSetText( (*texti).get(), NULL);
    376489   }
    377490
     
    379492   {
    380493       (*lighti)->s = IPS_IDLE;
    381        IDSetLight( (*lighti), NULL);
     494       IDSetLight( (*lighti).get(), NULL);
    382495   }
    383496
     
    385498   {
    386499       (*blobi)->s = IPS_IDLE;
    387        IDSetBLOB( (*blobi), NULL);
    388    }
    389 }
     500       IDSetBLOB( (*blobi).get(), NULL);
     501   }*/
     502}
     503
     504void INDI::DefaultDriver::setConnected(bool status, IPState state, const char *msg)
     505{
     506    ISwitch *sp = NULL;
     507    ISwitchVectorProperty *svp = getSwitch("CONNECTION");
     508    if (!svp)
     509        return;
     510
     511    IUResetSwitch(svp);
     512
     513    // Connect
     514    if (status)
     515    {
     516        sp = IUFindSwitch(svp, "CONNECT");
     517        if (!sp)
     518            return;
     519        sp->s = ISS_ON;
     520    }
     521    // Disconnect
     522    else
     523    {
     524        sp = IUFindSwitch(svp, "DISCONNECT");
     525        if (!sp)
     526            return;
     527        sp->s = ISS_ON;
     528    }
     529
     530    svp->s = state;
     531
     532    IDSetSwitch(svp, msg, NULL);
     533}
     534
     535//  This is a helper function
     536//  that just encapsulates the Indi way into our clean c++ way of doing things
     537int INDI::DefaultDriver::SetTimer(int t)
     538{
     539    return IEAddTimer(t,timerfunc,this);
     540}
     541
     542//  Just another helper to help encapsulate indi into a clean class
     543void INDI::DefaultDriver::RemoveTimer(int t)
     544{
     545    IERmTimer(t);
     546    return;
     547}
     548
     549//  This is just a placeholder
     550//  This function should be overriden by child classes if they use timers
     551//  So we should never get here
     552void INDI::DefaultDriver::TimerHit()
     553{
     554    return;
     555}
     556
     557
     558bool INDI::DefaultDriver::updateProperties()
     559{
     560    //  The base device has no properties to update
     561    return true;
     562}
     563
     564
     565bool INDI::DefaultDriver::initProperties()
     566{
     567   return true;
     568}
     569
     570bool INDI::DefaultDriver::deleteProperty(const char *propertyName)
     571{
     572    removeProperty(propertyName);
     573    IDDelete(deviceName(), propertyName ,NULL);
     574    return true;
     575}
     576
     577void INDI::DefaultDriver::defineNumber(INumberVectorProperty *nvp)
     578{
     579    registerProperty(nvp, INDI_NUMBER);
     580    IDDefNumber(nvp, NULL);
     581}
     582
     583void INDI::DefaultDriver::defineText(ITextVectorProperty *tvp)
     584{
     585    registerProperty(tvp, INDI_TEXT);
     586    IDDefText(tvp, NULL);
     587}
     588
     589void INDI::DefaultDriver::defineSwitch(ISwitchVectorProperty *svp)
     590{
     591    registerProperty(svp, INDI_SWITCH);
     592    IDDefSwitch(svp, NULL);
     593}
     594
     595void INDI::DefaultDriver::defineLight(ILightVectorProperty *lvp)
     596{
     597    registerProperty(lvp, INDI_LIGHT);
     598    IDDefLight(lvp, NULL);
     599}
     600
     601void INDI::DefaultDriver::defineBLOB(IBLOBVectorProperty *bvp)
     602{
     603    registerProperty(bvp, INDI_BLOB);
     604    IDDefBLOB(bvp, NULL);
     605}
  • BAORadio/libindi/libindi/libs/indibase/defaultdriver.h

    r502 r504  
    2626    void addAuxControls();
    2727
     28    /** \brief Add Debug control to the driver */
     29    void addDebugControl();
     30
     31    /** \brief Add Simulation control to the driver */
     32    void addSimulationControl();
     33
     34    /** \brief Add Configuration control to the driver */
     35    void addConfigurationControl();
     36
    2837    /** \brief Set all properties to IDLE state */
    2938    void resetProperties();
    3039
     40    /** \brief Define number vector to client & register it. Alternatively, IDDefNumber can be used but the property will not
     41               get registered and the driver will not be able to save configuration files.
     42         \param nvp The number vector property to be defined
     43    */
     44    void defineNumber(INumberVectorProperty *nvp);
     45
     46    /** \brief Define text vector to client & register it. Alternatively, IDDefText can be used but the property will not
     47               get registered and the driver will not be able to save configuration files.
     48         \param tvp The text vector property to be defined
     49    */
     50    void defineText(ITextVectorProperty *tvp);
     51
     52    /** \brief Define switch vector to client & register it. Alternatively, IDDefswitch can be used but the property will not
     53               get registered and the driver will not be able to save configuration files.
     54         \param svp The switch vector property to be defined
     55    */
     56    void defineSwitch(ISwitchVectorProperty *svp);
     57
     58    /** \brief Define light vector to client & register it. Alternatively, IDDeflight can be used but the property will not
     59               get registered and the driver will not be able to save configuration files.
     60         \param lvp The light vector property to be defined
     61    */
     62    void defineLight(ILightVectorProperty *lvp);
     63
     64    /** \brief Define BLOB vector to client & register it. Alternatively, IDDefBLOB can be used but the property will not
     65               get registered and the driver will not be able to save configuration files.
     66         \param bvp The BLOB vector property to be defined
     67    */
     68    void defineBLOB(IBLOBVectorProperty *bvp);
     69
     70
     71    /** \brief Delete a property and unregister it. It will also be deleted from all clients.
     72        \param propertyName name of property to be deleted.
     73    */
     74    virtual bool deleteProperty(const char *propertyName);
     75
     76    /** \brief Connect or Disconnect a device.
     77      \param status If true, the driver will attempt to connect to the device (CONNECT=ON). If false, it will attempt
     78to disconnect the device.
     79      \param msg A message to be sent along with connect/disconnect command.
     80    */
     81    virtual void setConnected(bool status, IPState state=IPS_OK, const char *msg = NULL);
     82
     83    int SetTimer(int);
     84    void RemoveTimer(int);
     85    virtual void TimerHit();
     86
    3187protected:
    3288
     
    95151    /** \return True if Simulation is on, False otherwise. */
    96152    bool isSimulation();
     153
     154    //  These are the properties we define, that are generic to pretty much all devices
     155    //  They are public to make them available to all dervied classes and thier children
     156    ISwitchVectorProperty *ConnectionSP;
     157    ISwitch ConnectionS[2];
     158
     159
     160    /** \brief Initilize properties initial state and value. The child class must implement this function.
     161        \return True if initilization is successful, false otherwise.
     162    */
     163    virtual bool initProperties();
     164
     165    /** \brief updateProperties is called whenever there is a change in the CONNECTION status of the driver.
     166        This will enable the driver to react to changes of switching ON/OFF a device. For example, a driver
     167        may only define a set of properties after a device is connected, but not before.
     168        \return True if update is successful, false otherwise.
     169    */
     170    virtual bool updateProperties();
     171
     172    /** \brief Connect to a device. Child classes must implement this function and perform the connection
     173        routine in the function.
     174        \return True if connection to device is successful, false otherwise.
     175    */
     176    virtual bool Connect()=0;
     177
     178    /** \brief Disconnect from a device. Child classes must implement this function and perform the disconnection
     179        routine in the function.
     180        \return True if disconnection from a device is successful, false otherwise.
     181    */
     182    virtual bool Disconnect()=0;
     183
     184    /** \return Default name of the device. */
     185    virtual const char *getDefaultName()=0;
     186
     187
    97188
    98189private:
  • BAORadio/libindi/libindi/libs/indibase/indibase.h

    r502 r504  
    2626    class BaseDriver;
    2727    class DefaultDriver;
     28    class CCD;
     29    class Telescope;
     30    class FilterWheel;
     31    class Focuser;
     32    class USBDevice;
    2833}
    2934
     
    3136/**
    3237 * \class INDI::BaseMediator
    33    \brief Meditates event notification as generated by devices and passed to clients.
     38   \brief Meditates event notification as generated by driver and passed to clients.
    3439*/
    3540class INDI::BaseMediator
     
    3843
    3944    /** \brief Emmited when a new device is created from INDI server.
     45        \param device_name Name of the new device
    4046    */
    41     virtual void newDevice()  =0;
     47    virtual void newDevice(const char *device_name)  =0;
     48
     49    /** \brief Emmited when a new property is created for an INDI driver.
     50        \param device_name Name of the device
     51        \param property_name Name of the new property
     52    */
     53    virtual void newProperty(const char *device_name, const char *property_name)  =0;
    4254
    4355    /** \brief Emmited when a new BLOB value arrives from INDI server.
     
    6678    virtual void newLight(ILightVectorProperty *lvp) =0;
    6779
     80    /** \brief Emmited when the server is connected.
     81    */
     82    virtual void serverConnected() =0;
     83
    6884    /** \brief Emmited when the server gets disconnected.
    6985    */
  • BAORadio/libindi/libindi/libs/indicom.c

    r501 r504  
    3434#include <sys/param.h>
    3535
    36 //#include <config.h>
     36#include <config.h>
    3737
    3838#ifdef HAVE_NOVA_H
     
    248248int tty_timeout(int fd, int timeout)
    249249{
     250 if (fd == -1)
     251        return TTY_ERRNO;
     252
    250253  struct timeval tv;
    251254  fd_set readout;
     
    276279int tty_write(int fd, const char * buf, int nbytes, int *nbytes_written)
    277280{
     281    if (fd == -1)
     282           return TTY_ERRNO;
     283
    278284  int bytes_w = 0;   
    279285  *nbytes_written = 0;
     
    297303int tty_write_string(int fd, const char * buf, int *nbytes_written)
    298304{
     305    if (fd == -1)
     306           return TTY_ERRNO;
     307
    299308  unsigned int nbytes;
    300309  int bytes_w = 0;
     
    321330int tty_read(int fd, char *buf, int nbytes, int timeout, int *nbytes_read)
    322331{
     332    if (fd == -1)
     333           return TTY_ERRNO;
    323334
    324335 int bytesRead = 0;
     
    349360int tty_read_section(int fd, char *buf, char stop_char, int timeout, int *nbytes_read)
    350361{
     362    if (fd == -1)
     363           return TTY_ERRNO;
    351364
    352365 int bytesRead = 0;
     
    496509                        break;
    497510                default:
    498                         if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid bit rate.", bit_rate) 0)
     511                        if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid bit rate.", bit_rate) < 0)
    499512                                perror(NULL);
    500513                        else
     
    521534
    522535                        fprintf( stderr, "Default\n") ;
    523                         if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid data bit count.", word_size) 0)
     536                        if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid data bit count.", word_size) < 0)
    524537                                perror(NULL);
    525538                        else
     
    542555
    543556                        fprintf( stderr, "Default1\n") ;
    544                         if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid parity selection value.", parity) 0)
     557                        if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid parity selection value.", parity) < 0)
    545558                                perror(NULL);
    546559                        else
     
    559572                default:
    560573                        fprintf( stderr, "Default2\n") ;
    561                         if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid stop bit count.", stop_bits) 0)
     574                        if (snprintf(msg, sizeof(msg), "tty_connect: %d is not a valid stop bit count.", stop_bits) < 0)
    562575                                perror(NULL);
    563576                        else
     
    651664    {
    652665        close(t_fd);
     666        *fd = -1;
    653667    }
    654668
     
    662676
    663677#else
    664  int t_fd=0;
     678 int t_fd=-1;
    665679 char msg[80];
    666680 int bps;
     
    668682
    669683 if ( (t_fd = open(device, O_RDWR | O_NOCTTY )) == -1)
     684 {
     685     *fd = -1;
    670686    return TTY_PORT_FAILURE;
     687 }
    671688
    672689    /* Control Modes
     
    853870int tty_disconnect(int fd)
    854871{
     872    if (fd == -1)
     873           return TTY_ERRNO;
     874
    855875#ifdef _WIN32
    856876        return TTY_ERRNO;
  • BAORadio/libindi/libindi/tools/setINDIproperty.c

    r490 r504  
    7171static int readServerChar (FILE *fp);
    7272static void findSet (XMLEle *root, FILE *fp);
    73 static void scanEV (SetSpec *sp, char e[], char v[]);
     73static void scanEV (SetSpec *specp, char ev[]);
     74static void scanEEVV (SetSpec *specp, char *ep, char ev[]);
     75static void scanEVEV (SetSpec *specp, char ev[]);
    7476static void sendNew (FILE *fp, INDIDef *dp, SetSpec *sp);
    7577static void sendSpecs(FILE *wfp);
     
    205207{
    206208        fprintf(stderr, "Purpose: set one or more writable INDI properties\n");
    207         fprintf(stderr, "%s\n", "$Revision: 1.4 $");
    208         fprintf(stderr, "Usage: %s [options] {[type] device.property.e1[;e2...]=v1[;v2...]} ...\n",
    209                                                                             me);
     209        fprintf(stderr, "%s\n", "$Revision: 1.6 $");
     210        fprintf(stderr, "Usage: %s [options] {[type] spec} ...\n", me);
    210211        fprintf(stderr, "Options:\n");
    211212        fprintf(stderr, "  -d f  : use file descriptor f already open to server\n");
     
    213214        fprintf(stderr, "  -p p  : alternate port, default is %d\n", INDIPORT);
    214215        fprintf(stderr, "  -t t  : max time to wait, default is %d secs\n",TIMEOUT);
    215         fprintf(stderr, "  -v    : verbose (cumulative)\n");
    216         fprintf(stderr, "Each property optionally preceded by its type is sent without first confirming\n");
     216        fprintf(stderr, "  -v    : verbose (more are cumulative)\n");
     217        fprintf(stderr, "Each spec optionally preceded by its type is sent without first confirming\n");
    217218        fprintf(stderr, "its structure. This is much more efficient but there is no error checking.\n");
    218219        fprintf(stderr, "Types are indicated with the following flags:\n");
     
    220221        fprintf(stderr, "  -n    : Number\n");
    221222        fprintf(stderr, "  -s    : Switch\n");
     223        fprintf(stderr, "Spec may be either:\n");
     224        fprintf(stderr, "    device.property.e1[;e2...]=v1[;v2...]\n");
     225        fprintf(stderr, "  or\n");
     226        fprintf(stderr, "    device.property.e1=v1[;e2=v2...]\n");
    222227        fprintf(stderr, "Exit status:\n");
    223228        fprintf(stderr, "  0: all settings successful\n");
     
    234239crackSpec (int *acp, char **avp[])
    235240{
    236         char d[1024], p[1024], e[2048], v[2048];
     241        char d[128], p[128], ev[2048];
    237242        char *spec = *avp[0];
    238243        INDIDef *dp = NULL;
     
    254259
    255260        /* then scan arg for property spec */
    256         if (sscanf (spec, "%[^.].%[^.].%[^.=]=%s", d, p, e, v) != 4) {
    257             fprintf (stderr, "Bad property format: %s\n", spec);
     261        if (sscanf (spec, "%[^.].%[^.].%s", d, p, ev) != 3) {
     262            fprintf (stderr, "Malformed property spec: %s\n", spec);
    258263            usage();
    259264        }
     
    268273        sets[nsets].ev = (SetEV *) malloc (1);          /* seed realloc */
    269274        sets[nsets].nev = 0;
    270         scanEV (&sets[nsets++], e, v);
     275        scanEV (&sets[nsets++], ev);
    271276
    272277        /* update caller's pointers */
     
    466471}
    467472
    468 /* scan e1[;e2...] v1[;v2,...] from e[] and v[] and add to spec sp.
     473/* scan ev for element definitions in either of two forms and add to sp:
     474 *    e1[;e2...]=v1[;v2...]
     475 *  or
     476 *    e1=v1[;e2=v2...]
     477 * exit if nothing sensible found.
     478 */
     479static void
     480scanEV (SetSpec *specp, char ev[])
     481{
     482        char *ep, *sp;          /* pointers to = and ; */
     483
     484        if (verbose > 1)
     485            fprintf (stderr, "Scanning assignments %s\n", ev);
     486
     487        ep = strchr (ev, '=');
     488        sp = strchr (ev, ';');
     489
     490        if (!ep) {
     491            fprintf (stderr, "Malformed assignment: %s\n", ev);
     492            usage();
     493        }
     494
     495        if (sp < ep)
     496            scanEEVV (specp, ep, ev);   /* including just one E=V */
     497        else
     498            scanEVEV (specp, ev);
     499}
     500
     501/* add specs of the form e1[;e2...]=v1[;v2...] to sp.
     502 * v is pointer to equal sign.
    469503 * exit if trouble.
    470  */
    471 static void
    472 scanEV (SetSpec *sp, char e[], char v[])
     504 * N.B. e[] and v[] are modified in place.
     505 */
     506static void
     507scanEEVV (SetSpec *sp, char *v, char *e)
    473508{
    474509        static char sep[] = ";";
    475         char *ep, *vp;
    476 
    477         if (verbose > 1)
    478             fprintf (stderr, "Scanning %s = %s\n", e, v);
     510        char *ec, *vc;
     511
     512        *v++ = '\0';
    479513
    480514        while (1) {
    481             char *e0 = strtok_r (e, sep, &ep);
    482             char *v0 = strtok_r (v, sep, &vp);
     515            char *e0 = strtok_r (e, sep, &ec);
     516            char *v0 = strtok_r (v, sep, &vc);
    483517
    484518            if (!e0 && !v0)
    485519                break;
    486520            if (!e0) {
    487                 fprintf (stderr, "More values than elements for %s.%s\n",
    488                                                                 sp->d, sp->p);
     521                fprintf (stderr, "More values than elements for %s.%s\n", sp->d, sp->p);
    489522                exit(2);
    490523            }
    491524            if (!v0) {
    492                 fprintf (stderr, "More elements than values for %s.%s\n",
    493                                                                 sp->d, sp->p);
     525                fprintf (stderr, "More elements than values for %s.%s\n", sp->d, sp->p);
    494526                exit(2);
    495527            }
     
    498530            sp->ev[sp->nev].e = strcpy (malloc(strlen(e0)+1), e0);
    499531            sp->ev[sp->nev].v = strcpy (malloc(strlen(v0)+1), v0);
     532            if (verbose > 1)
     533                fprintf (stderr, "Found assignment %s=%s\n", sp->ev[sp->nev].e, sp->ev[sp->nev].v);
    500534            sp->nev++;
    501535
     
    503537            v = NULL;
    504538        }
     539}
     540
     541/* add specs of the form e1=v1[;e2=v2...] to sp.
     542 * exit if trouble.
     543 * N.B. ev[] is modified in place.
     544 */
     545static void
     546scanEVEV (SetSpec *sp, char ev[])
     547{
     548        char *s, *e;
     549        int last = 0;
     550
     551        do {
     552            s = strchr (ev, ';');
     553            if (s)
     554                *s++ = '\0';
     555            else {
     556                s = ev + strlen (ev);
     557                last = 1;
     558            }
     559            e = strchr (ev, '=');
     560            if (e)
     561                *e++ = '\0';
     562            else {
     563                fprintf (stderr, "Malformed assignment: %s\n", ev);
     564                usage();
     565            }
     566
     567            sp->ev = (SetEV *) realloc (sp->ev, (sp->nev+1)*sizeof(SetEV));
     568            sp->ev[sp->nev].e = strcpy (malloc(strlen(ev)+1), ev);
     569            sp->ev[sp->nev].v = strcpy (malloc(strlen(e)+1), e);
     570            if (verbose > 1)
     571                fprintf (stderr, "Found assignment %s=%s\n", sp->ev[sp->nev].e, sp->ev[sp->nev].v);
     572            sp->nev++;
     573
     574            ev = s;
     575
     576        } while (!last);
    505577}
    506578
     
    517589
    518590/* For RCS Only -- Do Not Edit */
    519 static char *rcsid[2] = {(char *)rcsid, "@(#) $RCSfile: setINDI.c,v $ $Date: 2007/10/11 20:12:11 $ $Revision: 1.4 $ $Name:  $"};
     591static char *rcsid[2] = {(char *)rcsid, "@(#) $RCSfile: setINDI.c,v $ $Date: 2010/11/07 07:13:59 $ $Revision: 1.6 $ $Name:  $"};
Note: See TracChangeset for help on using the changeset viewer.