1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
|
// ********************************************************
// Les includes
// ********************************************************
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> /* close */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "libdll.h"
// ********************************************************
// Définition des variables
// ********************************************************
int g_step = 0; // Gestion de la boucle LAFonction.
int g_stepCon = 0; // Gestion pour savoir ou la connection/initialisation à planté pour savoir quoi fermer.
int g_erreur; // Variable permettant de récupérer la valeur de retour des fonctions utilisées.
char g_codeErreur[6]; // Code erreur pour afficher dans la boite de dialogue.
int nbCaractere; // Indique le nombre de caractères qui a été reçu ou envoyé.
SOCKET idSocket; // Identifiant de la socket.
SOCKADDR_IN infoServeur; // Déclaration de la structure des informations lié au serveur.
short packetIDTmp = 1; // Valeur du packetID sauvegardé.
short cpt = 0; // Variable pour compter le nombre de fois que l'on passe dans la step 1 (initialisation)
unsigned short paramOld[NBPARAM]; // Sauvegarde des params avant leurs modifs dans labView
unsigned char sendbuf[SIZEBUFFERS]; // Buffer message envoi.
char recbuf[SIZEBUFFERR]; // Buffer message reception.
int secondeNew;
int secondeOld;
// ********************************************************
// LAFonction
// ********************************************************
int main(void){
unsigned short statusAndMeasure[NBSTATUS];
unsigned short paramLv[NBPARAM];
short stop = 0;
while(1){
connection();
}
return 0;
}
int LAfonction(short stop, unsigned short statusAndMeasure[], unsigned short paramLv[]){
// Test fermeture du programme
if(stop == 1){
g_step = 3;
}
// Step = 0 -> Initialisation + connection.
if(g_step == 0){
connection();
secondeOld = getTime();
}
// Step = 1 -> Recuperer tout les parametres.
if(g_step == 1 || g_step == 2){
secondeNew = getTime();
// Status and Measures reading (TCS request)
if(secondeOld != secondeNew ){
sending(1,0,0);
receive(statusAndMeasure, paramLv);
secondeOld = getTime();
}
else{
if(g_step == 1){
sending(2, cpt, 0);
receive(statusAndMeasure, paramLv);
// Compteur de passage dans initialisation
cpt++;
// Initialisation terminee
if(cpt == NBPARAM){
g_step = 2;
cpt = 0;
}
}
else if(g_step == 2){
// Boucle pour voir si le tableau des parametres a été modifié.
for(; cpt < NBPARAM; cpt++){
if((paramLv[cpt] != paramOld[cpt]) && (cpt != 0)){
sending(3, cpt, paramLv[cpt]);
receive(statusAndMeasure, paramLv);
break;
}
}
if(cpt == NBPARAM) cpt = 0;
}
}
}
//Step = 3 -> Deconnection.
if(g_step == 3){
disconnection();
return 1;
}
return 0;
}
// ********************************************************
// Fonctions Connection
// ********************************************************
void connection(void){
char *ip_adr = "200.0.1.233";
unsigned short port = 2000;
// Ouverture d'une Socket
idSocket = socket(AF_INET, SOCK_STREAM, 0);
if(idSocket == INVALID_SOCKET){
g_step = 3;
g_stepCon = 0;
printf("Erreur connexion fonction socket()\n");
}
// Etablissement de l'ouverture de session
infoServeur.sin_family = AF_INET;
infoServeur.sin_addr.s_addr = inet_addr(ip_adr); // Indiquez l'adresse IP de votre serveur
infoServeur.sin_port = htons(port); // Port écouté du serveur
free(ip_adr);
ip_adr = NULL;
g_erreur = connect(idSocket, (struct sockaddr*)&infoServeur, sizeof(infoServeur));
if(g_erreur != 0){
g_step = 3;
g_stepCon = 1;
printf("Erreur connexion fonction connect()\n");
}
else{
g_step = 1;
g_stepCon = 2;
printf("Vous êtes connecté avec le client\n");
}
}
// ********************************************************
// Fonctions Send
// ********************************************************
void sending(int action, unsigned short index, unsigned short value){
int size;
memset(sendbuf, 0x0, sizeof(sendbuf));
// Status and Measures reading (TCS request)
if(action == 1){
// Création d'un pointeur vers la structure.
statMeasReq *packet;
// Allocation de la taille.
packet = malloc(sizeof(statMeasReq));
// Mise a zéro
memset(packet, 0x0, sizeof(statMeasReq));
// Garnissage.
packet->control = 0x02;
packet->lenght = 12;
packet->checksum = 0;
packet->packetID = packetIDTmp++;
getDateTime(packet);
packet->checksum = checksum((unsigned short *)packet, packet->lenght);
//Copie la structure dans le buffer
memcpy((void*)sendbuf, (const void*)packet, packet->lenght);
//Prend la taille du packet pour la transmettre a la fonction send.
size = packet->lenght;
//Libère la mémoire
free(packet);
packet = NULL;
}
// Command or Parameter reading (TCS request)
if(action == 2){
// Création d'un pointeur vers la structure.
struct commParaRead *packet;
// Allocation de la taille.
packet = malloc(sizeof(struct commParaRead));
// Mise a zéro
memset(packet, 0x0, sizeof(struct commParaRead));
// Garnissage.
packet->control = 0x12;
packet->lenght = 6;
packet->checksum = 0;
packet->index = index;
packet->checksum = checksum((unsigned short *)packet, packet->lenght);
//Copie la structure dans le buffer
memcpy((void*)sendbuf, (const void*)packet, packet->lenght);
//Prend la taille du packet pour la transmettre a la fonction send.
size = packet->lenght;
//Libère la mémoire
free(packet);
packet = NULL;
}
// Command or Parameter writing (TCS request)
if(action == 3){
// Création d'un pointeur vers la structure.
struct commParaWrit *packet;
// Allocation de la taille.
packet = malloc(sizeof(struct commParaWrit));
// Mise a zéro
memset(packet, 0x0, sizeof(struct commParaWrit));
// Garnissage.
packet->control = 0x13;
packet->lenght = 8;
packet->checksum = 0;
packet->index = index;
packet->value = value;
packet->checksum = checksum((unsigned short *)packet, packet->lenght);
//Copie la structure dans le buffer
memcpy((void*)sendbuf, (const void*)packet, packet->lenght);
//Prend la taille du packet pour la transmettre a la fonction send.
size = packet->lenght;
//Libère la mémoire
free(packet);
packet = NULL;
}
nbCaractere = send(idSocket, sendbuf, size, 0);
if(nbCaractere == SOCKET_ERROR){
g_step = 3;
printf("Erreur fonction send()\n");
}
else loginfo(sendbuf, nbCaractere, 1);
}
// ********************************************************
// Fonction Receive
// ********************************************************
void receive(unsigned short statusAndMeasure[], unsigned short paramLv[]){
int sel;
fd_set read;
struct timeval timeout;
unsigned short saveChecksum;
unsigned short returnChecksum;
memset(recbuf, 0x0, sizeof(recbuf));
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
FD_ZERO(&read);
FD_SET(idSocket, &read);
sel = select(idSocket + 1, &read, NULL, NULL, &timeout);
// Probleme avec la fonction select.
if(sel == SOCKET_ERROR){
g_step = 3;
printf("Erreur fonction select()\n");
}
// Temps écoulé pour la fonction select.
else if(sel == 0){
g_step = 3;
printf("Timeout fonction select() écoulé\n");
}
// Il y a un message a recuperer.
else{
//S'il y a une action a faire pour recv ... la fonction est faite
if(FD_ISSET(idSocket, &read)){
nbCaractere = recv(idSocket, recbuf, MAXSIZEPACKET, 0);
// Erreur lors de la fonction rec().
if(nbCaractere==SOCKET_ERROR){
g_step = 3;
printf("Erreur fonction recv()\n");
}
else{
recbuf[nbCaractere]='\0'; // Permet de fermer le tableau après le contenu des data, car la fonction recv ne le fait pas.
loginfo(recbuf, nbCaractere, 2);
// Creation du pointeur
struct packetRec *packet;
// Allocation de la taille.
packet = malloc(sizeof(struct packetRec));
packet->data = malloc(nbCaractere-6);
// Mise à zero.
memset(packet, 0x0, sizeof(struct packetRec));
memcpy((void*)packet, (const void*)recbuf, nbCaractere);
// Test du checksum.
saveChecksum = packet->checksum;
packet->checksum = 0;
returnChecksum = checksum((unsigned short *)packet, nbCaractere);
if(saveChecksum == returnChecksum) packet->checksum = saveChecksum;
// Test du byte de control si checksum OK
if(packet->checksum != 0){
// Status and Measures reading (PLC answer)
if(packet->control == 0x02){
memcpy((void *)statusAndMeasure, (const void*)&recbuf[6], 142);
}
// Command/Parameter reading or writing (PLC answer)
if(packet->control == 0x12 || packet->control == 0x17){
struct commParaReadWrit *p;
p = malloc(sizeof(struct commParaReadWrit));
memset(p, 0x0, sizeof(struct commParaReadWrit));
memcpy((void *)p, (const void*)recbuf, nbCaractere);
paramLv[p->index] = p->value;
paramOld[p->index] = paramLv[p->index];
// Liberation de la mémoire
free(p);
p = NULL;
}
// PLC answer at a "parameter/command writing" request by "Last packet rejected"
if(packet->control == 0x18){
struct packetRejected *p;
p = malloc(sizeof(struct packetRejected));
memset(p, 0x0, sizeof(struct packetRejected));
memcpy((void *)p, (const void*)recbuf, nbCaractere);
// Liberation de la mémoire
free(p);
p = NULL;
}
}
//Liberation de la mémoire.
free(packet->data);
packet->data = NULL;
free(packet);
packet = NULL;
}
}
}
}
// ********************************************************
// Fonctions Close
// ********************************************************
void disconnection(void){
// Fermeture de la session TCP Correspondant à la commande connect()
if(g_stepCon == 2){
g_erreur = shutdown(idSocket, 2); // 2 signifie socket d'émission et d'écoute
if(g_erreur != 0){
printf("Erreur fonction shutdown()\n");
}
else g_stepCon = 2;
}
// Fermeture de la socket correspondant à la commande socket()
if(g_stepCon == 1){
g_erreur = closesocket(idSocket);
if(g_erreur != 0){
printf("Erreur fonction close()\n");
}
else{
g_stepCon = 0;
g_step = 0;
cpt = 0;
}
}
}
// ********************************************************
// Calcule du checksum
// ********************************************************
unsigned short checksum(unsigned short *addr, int len){
int nleft = len;
unsigned short *w = addr;
int sum = 0;
unsigned short answer = 0;
// Somme des données pris deux par deux.
while (nleft > 1){
sum += *w;
w++;
nleft -= 2;
}
// Calcule du complément à 1 sur 16bits.
answer = ~sum;
// Envoie de la valeur du checksum calculé.
return(answer);
}
// ********************************************************
// Fonction de log des messages envoyés et recu
// ********************************************************
void loginfo(char tab[], int size, int code){
FILE * log = NULL;
int j;
log = fopen("Log.csv", "a");
if(log != NULL){
if(code == 1){
fprintf(log, "%s;", "Send:");
for(j=0; j<size; j++){
if(j == 0 || j == 1) fprintf(log,"%hhX;", (unsigned char)tab[j]);
else{
fprintf(log, "%hhX%hhX;", (unsigned char)tab[j+1], (unsigned char)tab[j]);
j++;
}
}
}
if(code == 2){
fprintf(log, ";->;%s;", "Receive:");
for(j=0; j<size; j++){
if(j == 0 || j == 1) fprintf(log,"%hhX;", (unsigned char)tab[j]);
else{
fprintf(log, "%hhX%hhX;", (unsigned char)tab[j+1], (unsigned char)tab[j]);
j++;
}
}
fprintf(log,"\n");
}
}
fclose (log);
}
// ********************************************************
// Fonction de recherche de texte dans un fichier .ini
// ********************************************************
char* getconf(const char *name){
FILE *fp;
char sLine[1024];
char *sName = NULL;
char *sValue = NULL;
memset(sLine, 0x0, sizeof(sLine));
// Ouvre le fichier en lecture seule
fp = fopen("config.ini", "r");
// Si erreur ouverture fichier arret programme
if(!fp){
g_step = 3;
}
// On boucle ligne par ligne jusqu'a la fin du fichier
while(sValue == NULL && fgets(sLine, (int)sizeof sLine, fp)){
if(strchr(sLine, '=')){
sName = sLine;
*strchr(sName, '=') = '\0';
if(!strcmp(sName, name)) sValue = sName+strlen(sName)+1;
}
}
if(sValue == NULL){
g_step = 3;
}
fclose(fp);
return(strdup(sValue));
}
// ********************************************************
// Fonction de recuperation de l'heure en seconde
// ********************************************************
int getTime(){
time_t timer1;
int secondes, minutes, heures;
struct tm *nT;
time(&timer1);
nT = localtime(&timer1);
heures = nT->tm_hour*3600;
minutes = nT->tm_min*60;
secondes = (nT->tm_sec + heures + minutes);
return secondes;
}
void getDateTime(statMeasReq *packet){
time_t timer1;
struct tm *nT;
time(&timer1);
nT = localtime(&timer1);
packet->year = (nT->tm_year+1900);
packet->month = (nT->tm_mon+1);
packet->day = nT->tm_mday;
packet->hour = nT->tm_hour;
packet->minute = nT->tm_min;
} |