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 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
|
// ********************************************************
// Les includes
// ********************************************************
#ifdef WIN32 /* si vous êtes sous Windows */
#include <winsock2.h> // Pour les fonctions socket.
#include <pthread.h> // Pour les Threads.
#include <stdio.h> // Pour les messageBox.
#include <stdlib.h>
#elif defined (linux) /* si vous êtes sous Linux */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> /* close */
#include <netdb.h> /* gethostbyname */
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
typedef struct in_addr IN_ADDR;
#else /* sinon vous êtes sur une plateforme non supportée */
#error not defined for this platform
#endif
// ********************************************************
// Defines
// ********************************************************
#define NBPARAM 10
#define MAXSIZEPACKET 14
#define SIZEBUFFER 20
// ********************************************************
// Structures
// ********************************************************
struct statMeasReq{
char control;
char lenght;
unsigned short checksum;
unsigned short packetID;
};
struct commParaRead{
char control;
char lenght;
unsigned short checksum;
unsigned short index;
};
struct commParaWrit{
char control;
char lenght;
unsigned short checksum;
unsigned short index;
unsigned short value;
};
struct packetRec{
char control;
char lenght;
unsigned short checksum;
unsigned short id;
char *data;
};
typedef struct{
char control;
char lenght;
unsigned short checksum;
unsigned short packetID;
unsigned short stat1;
unsigned short stat2;
unsigned short meas1;
unsigned short meas2;
}statMeasRead;
struct commParaReadWrit{
char control;
char lenght;
unsigned short checksum;
unsigned short index;
unsigned short value;
unsigned short minVal;
unsigned short maxVal;
};
struct packetRejected{
char control;
char lenght;
unsigned short checksum;
unsigned short index;
};
// ********************************************************
// Définition des variables
// ********************************************************
WSADATA initialisation_win32; // Variable permettant de récupérer la structure d'information sur l'initialisation.
//char *ip_adr = "200.0.1.233"; // Adresse IP du serveur.
//unsigned short port = 2000; // Port de communication avec le serveur.
char *ip_adr = "127.0.0.1";
unsigned short port = 33333;
int erreur; // Variable permettant de récupérer la valeur de retour des fonctions utilisées.
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.
char sendbuf[SIZEBUFFER]; // Buffer message envoi.
char recbuf[SIZEBUFFER]; // Buffer message reception.
int step = 0; // Gestion de la boucle LAFonction.
int stepCon = 0; // Gestion pour savoir ou la connection/initialisation à planté pour savoir quoi fermer.
short packetIDTmp = 1; // Valeur du packetID sauvegardé.
char codeErreur[6]; // Code erreur pour afficher dans la boite de dialogue.
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
int cptReqStat = 0; // Compteur/Timer pour demander les status tout les X fois que l'on passe dans LAFonction
// ********************************************************
// Prototypes
// ********************************************************
__declspec(dllexport) void LAfonction(short stop, statMeasRead *cluster1, unsigned short paramLv[]);
void connection(void);
void sending(int action, int index, int value);
void receive(statMeasRead *cluster1, unsigned short paramLv[]);
void close(void);
unsigned short checksum(unsigned short *addr, int len);
void logSend(char tab[], int size);
void logReceive(char tab[], int size);
// ********************************************************
// LAFonction
// ********************************************************
__declspec(dllexport) void LAfonction(short stop, statMeasRead *cluster1, unsigned short paramLv[]){
// Test fermeture du programme
if(stop == 1){
step = 3;
}
// Step = 0 -> Initialisation + connection.
if(step == 0){
connection();
}
// Step = 1 -> Recuperer tout les parametres.
if(step == 1){
sending(2, cpt, 0);
receive(cluster1, paramLv);
// Compteur de passage dans initialisation
cpt++;
// Initialisation terminee
if(cpt == NBPARAM){
memcpy((void *)paramOld, (const void*)paramLv, NBPARAM*sizeof(short));
step = 2;
}
}
//Step = 2 -> Envoyer et recevoir des données normalement.
if(step == 2){
// Boucle pour voir si le tableau des parametres a été modifié.
for(cpt = 0; cpt < NBPARAM; cpt++){
if(paramLv[cpt] != paramOld[cpt]){
sending(3, cpt, paramLv[cpt]);
receive(cluster1, paramLv);
paramOld[cpt] = paramLv[cpt];
break;
}
}
// Status and Measures reading (TCS request)
cptReqStat++;
if(cptReqStat == 50){
sending(1,0,0);
receive(cluster1, paramLv);
cptReqStat = 0;
}
}
//Step = 3 -> Deconnection.
if(step == 3){
close();
}
}
// ********************************************************
// Fonctions Connection
// ********************************************************
void connection(void){
#ifdef WIN32
// Initialisation de Winsock
erreur = WSAStartup(MAKEWORD(2,2), &initialisation_win32);
if(erreur != 0){
step = 3;
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur,"Erreur connexion : fonction WSAStartup() !",MB_OK|MB_ICONERROR);
}
#endif
// Ouverture d'une Socket
idSocket = socket(AF_INET, SOCK_STREAM, 0);
if(idSocket == INVALID_SOCKET){
step = 3;
stepCon = 1;
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL, codeErreur, "Erreur connexion : fonction socket() !",MB_OK|MB_ICONERROR);
}
// 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
erreur = connect(idSocket, (struct sockaddr*)&infoServeur, sizeof(infoServeur));
if(erreur != 0){
step = 3;
stepCon = 2;
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur, "Erreur connexion : fonction connect() !",MB_OK|MB_ICONERROR);
}
else{
step = 1;
stepCon = 3;
MessageBox(NULL,"Vous êtes connecté avec le serveur","Client connecté !",MB_OK|MB_ICONASTERISK);
}
}
// ********************************************************
// Fonctions Send
// ********************************************************
void sending(int action, int index, int 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.
struct statMeasReq *packet;
// Allocation de la taille.
packet = malloc(sizeof(struct statMeasReq));
// Mise a zéro
memset(packet, 0x0, sizeof(struct statMeasReq));
// Garnissage.
packet->control = 0x02;
packet->lenght = 6;
packet->checksum = 0;
packet->packetID = packetIDTmp++;
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){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur, "Erreur send : fonction send() !",MB_OK|MB_ICONERROR);
//Le serveur est mort, code erreur = 10054.
if(strcmp(codeErreur,"10054") == 0) step = 3;
}
else logSend(sendbuf, nbCaractere);
}
// ********************************************************
// Fonction Receive
// ********************************************************
void receive(statMeasRead *cluster1, 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){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur, "Erreur receive : fonction select() !",MB_OK|MB_ICONERROR);
}
// Temps écoulé pour la fonction select.
else if(sel == 0){
//MessageBox(NULL,codeErreur, "Erreur receive : select() timeout!",MB_OK|MB_ICONERROR);
//step = 3;
}
// 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){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur, "Erreur receive : fonction recv() !",MB_OK|MB_ICONERROR);
//Le serveur est mort, code erreur = 10054.
if(strcmp(codeErreur,"10054") == 0) step = 3;
}
else{
recbuf[nbCaractere]='\0'; // Permet de fermer le tableau après le contenu des data, car la fonction recv ne le fait pas
logReceive(recbuf, nbCaractere);
// Creation du pointeur
struct packetRec *packet;
// Allocation de la taille.
packet = malloc(sizeof(struct packetRec));
packet->data = malloc(((recbuf[1])-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, packet->lenght);
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){
/*struct statMeasRead *p;
p = malloc(sizeof(struct statMeasRead));
memset(p, 0x0, sizeof(struct statMeasRead));
memcpy((void *)p, (const void*)recbuf, nbCaractere);*/
memcpy((void *)cluster1, (const void*)recbuf, nbCaractere);
// Liberation de la mémoire
/*free(p);
p = NULL;*/
}
// 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;
}
}
else MessageBox(NULL,"Le calcule du checkSum à trouvé une erreur", "Erreur receive : fonction checksum() !",MB_OK|MB_ICONERROR);
//Liberation de la mémoire.
free(packet->data);
packet->data = NULL;
free(packet);
packet = NULL;
}
}
}
}
// ********************************************************
// Fonctions Close
// ********************************************************
void close(void){
// Fermeture de la session TCP Correspondant à la commande connect()
if(stepCon == 3){
erreur = shutdown(idSocket, 2); // 2 signifie socket d'émission et d'écoute
if(erreur != 0){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur,"Erreur fermeture connexion : fonction shutdown() !",MB_OK|MB_ICONERROR);
}
else stepCon = 2;
}
// Fermeture de la socket correspondant à la commande socket()
if(stepCon == 2){
erreur = closesocket(idSocket);
if(erreur != 0){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur,"Erreur fermeture connexion : fonction closesocket() !",MB_OK|MB_ICONERROR);
}
else stepCon = 1;
}
#ifdef WIN32
// Quitte proprement le winsock ouvert avec la commande WSAStartup
if(stepCon == 1){
erreur = WSACleanup(); // A appeler autant de fois qu'il a été ouvert.
if(erreur != 0){
sprintf(codeErreur,"%d",WSAGetLastError());
MessageBox(NULL,codeErreur,"Erreur fermeture connexion : fonction WSACleanup() !",MB_OK|MB_ICONERROR);
}
else{
MessageBox(NULL,"Vous êtes deconnecté du serveur","Client deconnecté !",MB_OK|MB_ICONASTERISK);
// Remettre les variable à zéro pour relancer le programme
stepCon = 0;
step = 0;
cpt = 0;
}
}
#endif
}
// ********************************************************
// 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);
}
void logSend(char tab[], int size){
FILE * logS = NULL;
int j;
logS = fopen("LogSend.csv", "a");
if(logS != NULL){
for(j=0; j<size; j++){
if(j == 0 || j == 1) fprintf(logS,"%X;",tab[j]);
else{
fprintf(logS, "%X%X;", tab[j+1], tab[j]);
j++;
}
}
}
fprintf(logS,"\n");
fclose (logS);
}
void logReceive(char tab[], int size){
FILE * logR = NULL;
int j;
logR = fopen("LogRecv.csv", "a");
if(logR != NULL){
for(j=0; j<size; j++){
if(j == 0) fprintf(logR,"%X;",tab[j]);
else if(j == 1) fprintf(logR,"%X;",tab[j]);
else{
fprintf(logR, "%X%X;", tab[j+1], tab[j]);
j++;
}
}
}
fprintf(logR,"\n");
fclose (logR);
} |
Partager