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
|
/*=============================================================================|
| PROJECT SNAP7 1.4.0 |
|==============================================================================|
| Copyright (C) 2013, 2014 Davide Nardella |
| All rights reserved. |
|==============================================================================|
| SNAP7 is free software: you can redistribute it and/or modify |
| it under the terms of the Lesser GNU General Public License as published by |
| the Free Software Foundation, either version 3 of the License, or |
| (at your option) any later version. |
| |
| It means that you can distribute your commercial software linked with |
| SNAP7 without the requirement to distribute the source code of your |
| application and without the requirement that your application be itself |
| distributed under LGPL. |
| |
| SNAP7 is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| Lesser GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License and a |
| copy of Lesser GNU General Public License along with Snap7. |
| If not, see http://www.gnu.org/licenses/ |
|==============================================================================|
| |
| Client Example |
| |
|=============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "snap7.h"
#ifdef OS_WINDOWS
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
S7Object Client;
unsigned char Buffer[65536]; // 64 K buffer
int SampleDBNum = 1000;
char *Address; // PLC IP Address
int Rack=0,Slot=2; // Default Rack and Slot
int ok = 0; // Number of test pass
int ko = 0; // Number of test failure
int JobDone=false;
int JobResult=0;
//------------------------------------------------------------------------------
// Async completion callback
//------------------------------------------------------------------------------
// This is a simply text demo, we use callback only to set an internal flag...
void S7API CliCompletion(void *usrPtr, int opCode, int opResult)
{
JobResult=opResult;
JobDone = true;
}
//------------------------------------------------------------------------------
// SysSleep (copied from snap_sysutils.cpp) multiplatform millisec sleep
//------------------------------------------------------------------------------
void SysSleep(longword Delay_ms)
{
#ifdef OS_WINDOWS
Sleep(Delay_ms);
#else
struct timespec ts;
ts.tv_sec = (time_t)(Delay_ms / 1000);
ts.tv_nsec =(long)((Delay_ms - ts.tv_sec) * 1000000);
nanosleep(&ts, (struct timespec *)0);
#endif
}
//------------------------------------------------------------------------------
// Usage Syntax
//------------------------------------------------------------------------------
void Usage()
{
printf("Usage\n");
printf(" client <IP> [Rack=0 Slot=2]\n");
printf("Example\n");
printf(" client 192.168.1.101 0 2\n");
printf("or\n");
printf(" client 192.168.1.101\n");
getchar();
}
//------------------------------------------------------------------------------
// hexdump, a very nice function, it's not mine.
// I found it on the net somewhere some time ago... thanks to the author ;-)
//------------------------------------------------------------------------------
#ifndef HEXDUMP_COLS
#define HEXDUMP_COLS 16
#endif
void hexdump(void *mem, unsigned int len)
{
unsigned int i, j;
for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++)
{
/* print offset */
if(i % HEXDUMP_COLS == 0)
{
printf("0x%04x: ", i);
}
/* print hex data */
if(i < len)
{
printf("%02x ", 0xFF & ((char*)mem)[i]);
}
else /* end of block, just aligning for ASCII dump */
{
printf(" ");
}
/* print ASCII dump */
if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1))
{
for(j = i - (HEXDUMP_COLS - 1); j <= i; j++)
{
if(j >= len) /* end of block, not really printing */
{
putchar(' ');
}
else if(isprint((((char*)mem)[j] & 0x7F))) /* printable char */
{
putchar(0xFF & ((char*)mem)[j]);
}
else /* other char */
{
putchar('.');
}
}
putchar('\n');
}
}
}
//------------------------------------------------------------------------------
// Check error
//------------------------------------------------------------------------------
int Check(int Result, char * function)
{
int ExecTime;
char text[1024];
printf("\n");
printf("+-----------------------------------------------------\n");
printf("| %s\n",function);
printf("+-----------------------------------------------------\n");
if (Result==0) {
Cli_GetExecTime(Client, &ExecTime);
printf("| Result : OK\n");
printf("| Execution time : %d ms\n",ExecTime);
printf("+-----------------------------------------------------\n");
ok++;
}
else {
printf("| ERROR !!! \n");
if (Result<0)
printf("| Library Error (-1)\n");
else
{
Cli_ErrorText(Result, text, 1024);
printf("| %s\n",text);
}
printf("+-----------------------------------------------------\n");
ko++;
}
return !Result;
}
//------------------------------------------------------------------------------
// Multi Read
//------------------------------------------------------------------------------
void MultiRead()
{
int res;
// Multiread buffers
byte MB[16]; // 16 Merker bytes
byte EB[16]; // 16 Digital Input bytes
byte AB[16]; // 16 Digital Output bytes
word TM[8]; // 8 timers
word CT[8]; // 8 counters
// Prepare struct
TS7DataItem Items[5];
// NOTE : *AMOUNT IS NOT SIZE* , it's the number of items
// Merkers
Items[0].Area =S7AreaMK;
Items[0].WordLen =S7WLByte;
Items[0].DBNumber =0; // Don't need DB
Items[0].Start =0; // Starting from 0
Items[0].Amount =16; // 16 Items (bytes)
Items[0].pdata =&MB;
// Digital Input bytes
Items[1].Area =S7AreaPE;
Items[1].WordLen =S7WLByte;
Items[1].DBNumber =0; // Don't need DB
Items[1].Start =0; // Starting from 0
Items[1].Amount =16; // 16 Items (bytes)
Items[1].pdata =&EB;
// Digital Output bytes
Items[2].Area =S7AreaPA;
Items[2].WordLen =S7WLByte;
Items[2].DBNumber =0; // Don't need DB
Items[2].Start =0; // Starting from 0
Items[2].Amount =16; // 16 Items (bytes)
Items[2].pdata =&AB;
// Timers
Items[3].Area =S7AreaTM;
Items[3].WordLen =S7WLTimer;
Items[3].DBNumber =0; // Don't need DB
Items[3].Start =0; // Starting from 0
Items[3].Amount =8; // 8 Timers
Items[3].pdata =&TM;
// Counters
Items[4].Area =S7AreaCT;
Items[4].WordLen =S7WLCounter;
Items[4].DBNumber =0; // Don't need DB
Items[4].Start =0; // Starting from 0
Items[4].Amount =8; // 8 Counters
Items[4].pdata =&CT;
res=Cli_ReadMultiVars(Client, &Items[0], 5);
if (Check(res,"Multiread Vars"))
{
// Result of Client->ReadMultivars is the "global result" of
// the function, it's OK if something was exchanged.
// But we need to check single Var results.
// Let shall suppose that we ask for 5 vars, 4 of them are ok but
// the 5th is inexistent, we will have 4 results ok and 1 not ok.
printf("Dump MB0..MB15 - Var Result : %d\n",Items[0].Result);
if (Items[0].Result==0)
hexdump(&MB,16);
printf("Dump EB0..EB15 - Var Result : %d\n",Items[1].Result);
if (Items[1].Result==0)
hexdump(&EB,16);
printf("Dump AB0..AB15 - Var Result : %d\n",Items[2].Result);
if (Items[2].Result==0)
hexdump(&AB,16);
printf("Dump T0..T7 - Var Result : %d\n",Items[3].Result);
if (Items[3].Result==0)
hexdump(&TM,16); // 8 Timers -> 16 bytes
printf("Dump Z0..Z7 - Var Result : %d\n",Items[4].Result);
if (Items[4].Result==0)
hexdump(&CT,16); // 8 Counters -> 16 bytes
};
}
//------------------------------------------------------------------------------
// List blocks in AG
//------------------------------------------------------------------------------
void ListBlocks()
{
TS7BlocksList List;
int res=Cli_ListBlocks(Client, &List);
if (Check(res,"List Blocks in AG"))
{
printf(" OBCount : %d\n",List.OBCount);
printf(" FBCount : %d\n",List.FBCount);
printf(" FCCount : %d\n",List.FCCount);
printf(" SFBCount : %d\n",List.SFBCount);
printf(" SFCCount : %d\n",List.SFCCount);
printf(" DBCount : %d\n",List.DBCount);
printf(" SDBCount : %d\n",List.SDBCount);
};
}
//------------------------------------------------------------------------------
// CPU Info : catalog
//------------------------------------------------------------------------------
void OrderCode()
{
TS7OrderCode Info;
int res=Cli_GetOrderCode(Client, &Info);
if (Check(res,"Catalog"))
{
printf(" Order Code : %s\n",Info.Code);
printf(" Version : %d.%d.%d\n",Info.V1,Info.V2,Info.V3);
};
}
//------------------------------------------------------------------------------
// CPU Info : unit info
//------------------------------------------------------------------------------
void CpuInfo()
{
TS7CpuInfo Info;
int res=Cli_GetCpuInfo(Client, &Info);
if (Check(res,"Unit Info"))
{
printf(" Module Type Name : %s\n",Info.ModuleTypeName);
printf(" Seriel Number : %s\n",Info.SerialNumber);
printf(" AS Name : %s\n",Info.ASName);
printf(" Module Name : %s\n",Info.ModuleName);
};
}
//------------------------------------------------------------------------------
// CP Info
//------------------------------------------------------------------------------
void CpInfo()
{
TS7CpInfo Info;
int res=Cli_GetCpInfo(Client, &Info);
if (Check(res,"Communication processor Info"))
{
printf(" Max PDU Length : %d bytes\n",Info.MaxPduLengt);
printf(" Max Connections : %d \n",Info.MaxConnections);
printf(" Max MPI Rate : %d bps\n",Info.MaxMpiRate);
printf(" Max Bus Rate : %d bps\n",Info.MaxBusRate);
};
}
//------------------------------------------------------------------------------
// PLC Status
//------------------------------------------------------------------------------
void UnitStatus()
{
int res=0;
int Status;
Cli_GetPlcStatus(Client, &Status);
if (Check(res,"CPU Status"))
{
switch (Status)
{
case S7CpuStatusRun : printf(" RUN\n"); break;
case S7CpuStatusStop: printf(" STOP\n"); break;
default : printf(" UNKNOWN\n"); break;
}
};
}
//------------------------------------------------------------------------------
// Upload DB0 (surely exists in AG)
//------------------------------------------------------------------------------
void UploadDB0()
{
int Size = sizeof(Buffer); // Size is IN/OUT par
// In input it tells the client the size available
// In output it tells us how many bytes were uploaded.
int res=Cli_Upload(Client, Block_SDB, 0, &Buffer, &Size);
if (Check(res,"Block Upload (SDB 0)"))
{
printf("Dump (%d bytes) :\n",Size);
hexdump(&Buffer,Size);
}
}
//------------------------------------------------------------------------------
// Async Upload DB0 (using callback as completion trigger)
//------------------------------------------------------------------------------
void AsCBUploadDB0()
{
int Size = sizeof(Buffer); // Size is IN/OUT par
// In input it tells the client the size available
// In output it tells us how many bytes were uploaded.
int res;
JobDone=false;
res=Cli_AsUpload(Client, Block_SDB, 0, &Buffer, &Size);
if (res==0)
{
while (!JobDone)
{
SysSleep(100);
}
res=JobResult;
}
if (Check(res,"Async (callback) Block Upload (SDB 0)"))
{
printf("Dump (%d bytes) :\n",Size);
hexdump(&Buffer,Size);
}
}
//------------------------------------------------------------------------------
// Async Upload DB0 (using event wait as completion trigger)
//------------------------------------------------------------------------------
void AsEWUploadDB0()
{
int Size = sizeof(Buffer); // Size is IN/OUT par
// In input it tells the client the size available
// In output it tells us how many bytes were uploaded.
int res;
JobDone=false;
res=Cli_AsUpload(Client, Block_SDB, 0, &Buffer, &Size);
if (res==0)
{
res=Cli_WaitAsCompletion(Client,3000);
}
if (Check(res,"Async (Wait event) Block Upload (SDB 0)"))
{
printf("Dump (%d bytes) :\n",Size);
hexdump(&Buffer,Size);
}
}
//------------------------------------------------------------------------------
// Async Upload DB0 (using polling as completion trigger)
//------------------------------------------------------------------------------
void AsPOUploadDB0()
{
int Size = sizeof(Buffer); // Size is IN/OUT par
// In input it tells the client the size available
// In output it tells us how many bytes were uploaded.
int res;
JobDone=false;
res=Cli_AsUpload(Client, Block_SDB, 0, &Buffer, &Size);
if (res==0)
{
while (Cli_CheckAsCompletion(Client,&res)!=JobComplete)
{
SysSleep(100);
};
}
if (Check(res,"Async (polling) Block Upload (SDB 0)"))
{
printf("Dump (%d bytes) :\n",Size);
hexdump(&Buffer,Size);
}
}
//------------------------------------------------------------------------------
// Read a sample SZL Block
//------------------------------------------------------------------------------
void ReadSzl_0011_0000()
{
PS7SZL SZL = (PS7SZL)(&Buffer); // use our buffer casted as TS7SZL
int Size = sizeof(Buffer);
// Block ID 0x0011 IDX 0x0000 normally exists in every CPU
int res=Cli_ReadSZL(Client, 0x0011, 0x0000, SZL, &Size);
if (Check(res,"Read SZL - ID : 0x0011, IDX 0x0000"))
{
printf(" LENTHDR : %d\n",SZL->Header.LENTHDR);
printf(" N_DR : %d\n",SZL->Header.N_DR);
printf("Dump (%d bytes) :\n",Size);
hexdump(&Buffer,Size);
}
}
//------------------------------------------------------------------------------
// Unit Connection
//------------------------------------------------------------------------------
int CliConnect()
{
int Requested, Negotiated, res;
res = Cli_ConnectTo(Client, Address,Rack,Slot);
if (Check(res,"UNIT Connection")) {
Cli_GetPduLength(Client, &Requested, &Negotiated);
printf(" Connected to : %s (Rack=%d, Slot=%d)\n",Address,Rack,Slot);
printf(" PDU Requested : %d bytes\n",Requested);
printf(" PDU Negotiated : %d bytes\n",Negotiated);
};
return !res;
}
//------------------------------------------------------------------------------
// Unit Disconnection
//------------------------------------------------------------------------------
void CliDisconnect()
{
Cli_Disconnect(Client);
}
//------------------------------------------------------------------------------
// Perform readonly tests, no cpu status modification
//------------------------------------------------------------------------------
void PerformTests()
{
OrderCode();
CpuInfo();
CpInfo();
UnitStatus();
ReadSzl_0011_0000();
UploadDB0();
AsCBUploadDB0();
AsEWUploadDB0();
AsPOUploadDB0();
MultiRead();
}
void Summary()
{
printf("\n");
printf("+-----------------------------------------------------\n");
printf("| Test Summary \n");
printf("+-----------------------------------------------------\n");
printf("| Performed : %d\n",(ok+ko));
printf("| Passed : %d\n",ok);
printf("| Failed : %d\n",ko);
printf("+----------------------------------------[press a key]\n");
getchar();
}
int main(int argc, char* argv[])
{
// Get Progran args
if (argc!=2 && argc!=4)
{
Usage();
return 1;
}
Address=argv[1];
if (argc==4)
{
Rack=atoi(argv[2]);
Slot=atoi(argv[3]);
}
// Client Creation
Client=Cli_Create();
Cli_SetAsCallback(Client, CliCompletion,NULL);
// Connection
if (CliConnect())
{
PerformTests();
CliDisconnect();
};
// Deletion
Cli_Destroy(&Client);
Summary();
return 0;
}
|