9a998e2bcbec5a49aa0b634852bdeeb014fae912
[owTools.git] / src / main.cpp
1 // Copyright (c) 2017, Tobias Mueller tm(at)tm3d.de
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //  * Redistributions of source code must retain the above copyright
9 //    notice, this list of conditions and the following disclaimer.
10 //  * Redistributions in binary form must reproduce the above copyright
11 //    notice, this list of conditions and the following disclaimer in the
12 //    documentation and/or other materials provided with the
13 //    distribution.
14 //  * All advertising materials mentioning features or use of this
15 //    software must display the following acknowledgement: This product
16 //    includes software developed by tm3d.de and its contributors.
17 //  * Neither the name of tm3d.de nor the names of its contributors may
18 //    be used to endorse or promote products derived from this software
19 //    without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33 #include "owTools.h"
34
35 #ifdef LINUX
36 #include <mysql.h>
37 #include "mySensorDB.h"
38 #include <sys/mman.h>
39 #include <unistd.h>
40 #include <pthread.h>
41 #include <sched.h>
42 #endif
43
44 #ifdef WIN
45 #include "Windows.h"
46 #include "time.h"
47 #endif
48
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <stdint.h>
52 #include <fcntl.h>    /* For O_RDWR */
53 #include <memory.h>
54 #include "hexfile.h"
55 #include <iostream>
56 #include <algorithm>
57 #include <fstream>
58 #include <sstream> 
59
60 #ifdef LINUX
61
62 #define RB "\e(0\x6a\e(B" // 188 Right Bottom corner
63 #define RT "\e(0\x6b\e(B" // 187 Right Top corner
64 #define LT "\e(0\x6c\e(B" // 201 Left Top cornet
65 #define LB "\e(0\x6d\e(B" // 200 Left Bottom corner
66 #define MC "\e(0\x6e\e(B" // 206 Midle Cross
67 #define HL "\e(0\x71\e(B" // 205 Horizontal Line
68 #define LC "\e(0\x74\e(B" // 204 Left Cross
69 #define RC "\e(0\x75\e(B" // 185 Right Cross
70 #define BC "\e(0\x76\e(B" // 202 Bottom Cross
71 #define TC "\e(0\x77\e(B" // 203 Top Cross
72 #define VL "\e(0\x78\e(B" // 186 Vertical Line
73 #define SP " "            // space string
74 #define BLUE_B "\033[1;34m"
75 #define COLOR_E "\033[0m"
76 #define C2_B "\033[0;36m"
77 #define C3_B "\033[3;34m"
78 #define C4_B "\033[1;33m"
79 #define C5_B "\033[4;33m"
80 #endif
81 #ifdef WIN
82 #define RB " "// 188 Right Bottom corner
83 #define RT  " "// 187 Right Top corner
84 #define LT  " "// 201 Left Top cornet
85 #define LB  " "// 200 Left Bottom corner
86 #define MC " " // 206 Midle Cross
87 #define HL " "// 205 Horizontal Line
88 #define LC  " "// 204 Left Cross
89 #define RC  " "// 185 Right Cross
90 #define BC  " "// 202 Bottom Cross
91 #define TC  " "// 203 Top Cross
92 #define VL  " "// 186 Vertical Line
93 #define SP " "            // space string
94 #define BLUE_B ""
95 #define C2_B ""
96 #define C3_B ""
97 #define C4_B ""
98 #define COLOR_E ""
99 #define C5_B ""
100
101
102 #endif
103
104 void printhelp() {
105 printf("owTools - Program for reading and controlling 1-Wire Devices from www.tm3d.de\n\n");
106 printf("run:  owTools -a [COMn|USBn|GPIOn] [options]\n\n");
107 printf("    COMn -> Adapter DS9097 and compatible (e.g. LinkUSB)\n");
108 printf("         n=1 -> Windows COM1 -> Linux /dev/ttyS1\n");
109 printf("    USBn -> Adapter DS2490/DS9490 \n");
110 printf("         n=1 -> first USB-Adapter \n");
111 printf("    GPIOn -> port of RaspberrPI (port Name not Pin number)\n\n");
112 printf("Options:\n");
113 printf("   -i interactive mode\n");
114 printf("          select a device and get information about it\n");
115 printf("   -c read and print all continuous\n");
116 printf("      -p time in sec between readings\n");
117 printf("      -d [config file] put all Data in mysql Database descripted in config file\n");
118 printf("         Config file: \n");
119 printf("            [server]\n");
120 printf("            [port] -> 3306\n");
121 printf("            [user] \n");
122 printf("            [password]\n");
123 printf("            [database]\n");
124 printf("            [prefix] -> a prefix of all tables \n\n");
125 printf("      -r Search every time for new Devices\n");
126 printf("   -f [hexfile]    flash new\n");
127 printf("   -n change id   \n");
128 printf("      -g get from server\n");
129 printf("   -w [1|2] show Warnings (1) or all information (2)\n");
130 printf("   -m memory functions\n");
131
132
133
134
135 }
136
137
138 typedef struct {
139         std::string flag;
140         std::string arg;
141 } arg_t ;
142
143
144 //length of shown chars of an UTF8 string ... sometimes not the same as byte count
145 std::size_t utf8_length(std::string const &s) {
146   std::size_t len = 0;
147   std::string::const_iterator begin = s.begin(), end = s.end();
148   while (begin != end) {
149     unsigned char c = *begin;
150     int n=1;
151     if      ((c & 0x80) == 0)    n = 1;
152     else if ((c & 0xE0) == 0xC0) n = 2;
153     else if ((c & 0xF0) == 0xE0) n = 3;
154     else if ((c & 0xF8) == 0xF0) n = 4;
155     
156     len += 1;
157     begin += n;
158   }
159   return len;
160 }
161
162
163 std::vector<arg_t> comlist;
164
165 std::string getArg(std::string flag) {
166         for(arg_t a:comlist) {
167                 if (a.flag==flag) return a.arg;
168         }
169         return ""; 
170 }
171
172
173
174 int getArgi(std::string flag) {
175         return atoi(getArg(flag).c_str());
176 }
177
178 #ifdef LINUX
179 int database=0;
180 mySensorDB *sdb=NULL;
181 #endif
182 /*
183 snum_t getArgsnum(std::string flag) {
184         snum_t snum;
185         snum.num=0;
186         return snum;
187 }
188 */
189 int findCPU(std::string cpu) {
190         std::ifstream fileInput;
191         std::string line;
192         fileInput.open("/proc/cpuinfo");
193         if(fileInput.is_open()) {       
194                 for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
195                         if (line.find(cpu) != std::string::npos) {
196                                 fileInput.close();
197                                 return 1;
198                         }
199                 }
200                 fileInput.close();
201                 
202         }
203         return 0;
204 }
205
206
207
208
209 owInterface *owi= NULL;
210
211 void setLogMode() {
212         if (getArg("w")=="2")
213                         owi->log->setLogLevel(0);
214         else if (getArg("w")=="2") owi->log->setLogLevel(0);
215         else owi->log->setLogLevel(OWLOG_ERROR);
216
217 }
218
219
220 void continuous(std::vector<owDevice*> *devices,int intervall,int headline,int searchrom) {
221         int first=1;
222         while (1) {
223                 if (searchrom) {
224                         owi->log->clear();
225                         owi->Find();
226                         if (owi->isDevicesChanged()||(first==1)) {
227                                 first=0;
228                                 if (headline) {
229                                         printf("                     \t");
230                                         for (owDevice* dev :*devices) {
231                                                 if (dev->configstate!=OWDCS_NONE) {
232                                                         for (size_t i=0;i<4;i++) {
233                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
234                                                                         printf(BLUE_B "%02X.%02X%02X" COLOR_E "\t",dev->getNum().byte[7],dev->getNum().byte[1],dev->getNum().byte[0]);
235                                                         }
236                                                 }
237                                         }
238                                         printf("\ntime                 \t");
239                                         for (owDevice* dev :*devices) {
240                                                 if (dev->configstate!=OWDCS_NONE) {
241                                                         for (size_t i=0;i<4;i++) {
242                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
243                                                                         printf(C2_B "%s" COLOR_E "\t",dev->config->getQuantity((uint8_t)i).substr(0,7).c_str());
244                                                         }
245                                                 }
246                                         }
247                                         printf("\n                     \t");
248                                         for (owDevice* dev :*devices) {
249                                                 if (dev->configstate!=OWDCS_NONE) {
250                                                         for (size_t i=0;i<4;i++) {
251                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0) {
252                                                                         size_t l=utf8_length(dev->config->getUnit((uint8_t)i));
253                                                                         std::string ls="           ";
254                                                                         printf(C3_B "[%s]%s" COLOR_E "\t",dev->config->getUnit((uint8_t)i).c_str(),ls.substr(0,5-l).c_str());
255                                                                 }
256                                                         }
257                                                 }
258                                         }
259                                         
260                                 }       
261                                 printf("\n");
262 #ifdef LINUX
263                                 if (database) {
264                                         //owi->log->setLogLevel(0);
265                                         for (owDevice* dev : *devices) {
266                                                 sdb->createDeviceTable(dev);
267                                         }
268                                 }
269 #endif
270                         }
271                         
272                 }
273                 time_t t=time(NULL);
274                 int st=(int)t;
275 #ifdef LINUX
276                 struct tm tm = *localtime(&t);
277 #endif
278 #ifdef WIN
279                 struct tm tm;
280                 localtime_s(&tm,&t);
281 #endif
282                 printf("%d-%02d-%02d %02d:%02d:%02d\t", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
283                 for (owDevice* dev :*devices) {
284                         for(int k=0;k<owi->maxrepeat;k++){
285                                 dev->convertAll();
286                                 if (owi->log->last()<OWLOG_ERROR) break;
287                                 owi->log->clear();
288                         }
289                         if (owi->log->last()<OWLOG_ERROR) {
290                                 if (dev->configstate!=OWDCS_NONE) {
291                                         for (size_t i=0;i<4;i++) {                                      
292                                                 if (dev->config->getPropertyID((int8_t)i)!=0) {
293                                                         if (dev->values[i]<=-10) 
294                                                                 printf("%0.2f \t",dev->values[i]);
295                                                         else if (dev->values[i]<0) 
296                                                                 printf("%0.3f \t",dev->values[i]);
297                                                         else if (dev->values[i]<10) 
298                                                                 printf("%0.4f \t",dev->values[i]);
299                                                         else if (dev->values[i]<100)    
300                                                                 printf("%0.3f \t",dev->values[i]);
301                                                         else if (dev->values[i]<1000)   
302                                                                 printf("%0.2f \t",dev->values[i]);
303                                                         else
304                                                                 printf("%0.1f \t",dev->values[i]);
305                                                         fflush(stdout);
306                                                 }
307                                         }
308                                 }
309 #ifdef LINUX
310                                 if (database) {
311                                         sdb->insertValues(dev);
312                                 }
313 #endif
314                         } else {
315                                 owi->log->setLogLevel(OWLOG_INFO);
316                                 owi->log->set(OWLOG_ERROR,"Too many errors, mybee conection is dead.");
317                                 return;
318                         }
319                         
320                 
321                 }
322                 printf("\n");
323                 while (((int)time(NULL)) < (st + intervall)) {
324 #ifdef LINUX
325                         sleep(1);
326 #endif
327 #ifdef WIN
328                         Sleep(1000);
329 #endif          
330                 }
331         }
332 }
333
334 void device_menu(owDevice* d) {
335         for(int i=0;i<70;i++) printf(HL);printf("\n");
336         printf("Selected Device: ");
337         snum_t snum=d->getNum();
338         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
339         printf("  \n");
340         printf("Chip Info: ");
341         std::vector<std::string> info=d->getFamilyInfo();
342         for (std::string s : info) printf(" %s",s.c_str());
343         printf("\n");
344         printf("Values info: ");
345         int tm3d=d->readConfig();
346         for (size_t i=0;i<4;i++) {
347                 printf("%s in %s",d->config->getQuantity((uint8_t)i).c_str(),d->config->getUnit((uint8_t)i).c_str());
348                 if (i<4) printf("; "); 
349         }
350         if (tm3d) printf(" (tm3d.de)"); else printf(" (default)"); 
351         printf("\n");
352         d->convertAll();
353         for (size_t i=0;i<d->values.size();i++) {
354                 printf(C4_B "%0.4f %s" COLOR_E,d->values[i],d->config->getUnit((uint8_t)i).c_str());
355         }
356         printf("\n");
357         for(int i=0;i<70;i++) printf(HL);printf("\n");
358         printf("0) Exit\n");
359         printf("1) Run continuous\n");
360         std::string inp;
361         while (1) {
362                 printf("Select an option: ");std::getline (std::cin,inp);
363                 int dnr=atoi(inp.c_str());
364                 if (dnr<=0) return;
365                 if (dnr==1) {
366                         std::vector<owDevice*> v;
367                         v.push_back(d);
368                         continuous(&v,1,1,0);
369                 } 
370 //                      if (dnr<=i) break; 
371         //              printf("\033[4;33mSelect a number between 0 and %i\033[0m\n",i);
372         }
373         
374         
375 }
376
377 int selectDevice() {
378         owi->Find();
379         int i=0;
380         for (owDevice* dev :owi->devices) {
381                 i++;
382                 snum_t snum=dev->getNum();
383                 printf("%i) ",i);
384                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
385
386                 printf("  ");
387                 for (int j=0;j<4;j++) printf("%s ",dev->config->getQuantity(j).c_str());
388                 printf("\n");
389         }
390         printf("0) Exit Programm\n");
391         std::string inp;
392         int dnr=0;
393         while (1) {
394                 printf("Select device with number: ");std::getline (std::cin,inp);
395                 dnr=atoi(inp.c_str());
396                 if (dnr<=0) return 0;
397                 if (dnr<=i) break; 
398                 printf(C5_B "Select a number between 0 and %i" COLOR_E "\n",i);
399         }
400         return dnr;
401
402 }
403
404 int questionYesNo(std::string text) {
405         std::string inp;
406         printf("%s [Y/n] ",text.c_str());std::getline (std::cin,inp);
407         if (inp=="Y") return 1; else return 0;
408         
409 }
410
411 void interactive(owInterface *owi) {
412         while (1) {
413                 int i=selectDevice();
414                 if (i==0 ) return;
415                 device_menu(owi->devices[i-1]);
416         }
417 }
418
419 int main(int argc, char *argv[]) {
420         int i;
421         arg_t a;
422         //printf("Kommando: %s:\n", argv[0]);
423         while (--argc) {
424                 if (**++argv != '-') {
425         //printf("   Arg. = %s\n", *argv);
426         if (comlist.empty()) {
427                 a.flag=".";
428                 a.arg=*argv;
429                 comlist.push_back(a);
430         } else {
431                 if ((*(comlist.end()-1)).arg!="1") {
432                         a.flag=".";
433                         a.arg=*argv;
434                         comlist.push_back(a);
435                 } else {
436                         (*(comlist.end()-1)).arg=*argv;
437                 }
438         }
439                 } else {
440                         for( i=1; (*argv)[i] != '\0'; i++) {
441                                 //printf("   Flag = (%c)\n", (*argv)[i]);
442                                 a.flag=(*argv)[i];
443                                 a.arg="1";
444                                 comlist.push_back(a);
445                         }
446                 }
447     }          
448
449         //for(arg_t a:comlist) printf("%s->%s\n",a.flag.c_str(),a.arg.c_str());
450         if (getArg("h")=="1") {
451                 printhelp();
452                 return 0;
453         }
454         std::string adapter=getArg("a");
455         if (adapter.empty()) {
456                 printhelp();
457                 return 0;
458         }       
459         std::transform(adapter.begin(), adapter.end(),adapter.begin(), ::toupper);
460
461         std::string s;
462 #ifdef LINUX    
463         if(adapter.find("COM")!=std::string::npos) {
464                 owi=new owCOMInterface();
465                 int port=atoi(adapter.substr(adapter.find("COM")+3).c_str());
466                 printf("Open /dev/ttyS%i\n",port);
467                 owi->InitAdapter(port);
468         } else 
469         if(adapter.find("USB")!=std::string::npos) {
470                 owi=new owUSBInterface();
471                 int port=atoi(adapter.substr(adapter.find("USB")+3).c_str());
472                 printf("Open the %i. USB Adapter\n",port);
473                 int err;
474                 if ((err=owi->InitAdapter(port))<0) {
475                         if (err==-1) printf("No Adapter found!\n  On Linux, try: sudo owTools....\n  On Windows: Install libusb0 driver\n");
476                         if (err==-2) printf("Maybe Adapter is used ... (try sudo)\nOn Linux: If the kernel modul is loaded type: sudo rmmod ds2490\n");
477                         exit(0);
478                 }
479         } else 
480         if(adapter.find("GPIO")!=std::string::npos) {
481                 if (findCPU("BCM2708")) {
482                         printf("\033[1;33mRaspberry Pi 1 is dedected. 1-wire on the GPIO port can have many errors in the transfer.\033[0m\n");
483                         owi=new owPiGPioInterface();
484                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
485                         printf("Open GPIO %i\n",port);
486                 } else if (findCPU("BCM2709")) {
487                         owi=new owPiGPioInterface();
488                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
489                         printf("Open GPIO %i\n",port);
490                         owi->InitAdapter(port);
491                 } else {
492                         printf("\033[1;31mGPIO works with Raspberry PI only \033[0m\n");
493                 }
494         }  else
495         if(adapter.find("W1")!=std::string::npos) {
496                 owi=new owW1Interface();
497                 if (owi->InitAdapter(0)) {
498                         printf("Use W1-Kernel 1-Wire functions on /sys/bus/w1\n");
499                 } else printf("No W1-Kernel module found!!\n");
500         } else 
501 #endif
502         if (adapter.find("ARDUINO") != std::string::npos) {
503                 owi = new owARDUINOInterface();
504                 int port = atoi(adapter.substr(adapter.find("ARDUINO") + 7).c_str());
505                 printf("Open /dev/ttyS%i\n", port);
506                 owi->InitAdapter(port);
507         }
508
509 #ifdef WIN
510                 else 
511         if (adapter.find("USB") != std::string::npos) {
512                 printf("USB \n");
513                 owi = new owTMEXWIN();
514                 int port = atoi(adapter.substr(adapter.find("USB") + 3).c_str());
515                 printf("Open the %i. USB Adapter\n", port);
516                 int err;
517                 char cs[20];
518                 sprintf_s(cs, 20, "{%i,6}", port);
519                 if ((err = owi->InitAdapter(cs))==0) {
520                                         printf("ERROR Init USB Adapter\n");
521                                         exit(0);
522                                 }
523                         }
524         else
525                 if (adapter.find("COM") != std::string::npos) {
526                         owi = new owTMEXWIN();
527                         int port = atoi(adapter.substr(adapter.find("COM") + 3).c_str());
528                         printf("Open Adapter on COM%i\n", port);
529                         int err;
530                         char cs[20];
531                         sprintf_s(cs, 20, "{%i,5}", port);
532                         if ((err = owi->InitAdapter(cs))==0) {
533                                 printf("ERROR Init Serial Adapter\n");
534                                 exit(0);
535                         }
536                 }
537 #endif
538         if (owi == NULL) {
539                 printf("No 1-Wiremaster found\n");
540                 return 0;
541         }
542         setLogMode();
543         
544         
545
546         if (getArg("i")=="1") {
547                 interactive(owi);       
548         } else 
549         if (getArg("c")=="1") {
550                 int reload=(getArg("r")=="1");
551                 owi->Find();
552                 printf("\n");
553                 //owi->log->setLogLevel(3);
554                 std::string s;
555                 int pause;
556                 if ((s=getArg("p")) !="") {
557                         pause=atoi(s.c_str());
558                 } else pause=30;
559 #ifdef LINUX
560                 if  ((s=getArg("d")) !="") {
561                         reload=1;
562                         printf("Use Database\n");
563                         sdb=new mySensorDB(s,owi->log);
564                         if (sdb->log->last()>OWLOG_WARNING) {
565                                 exit(1);
566                         }
567                         sdb->connect();
568                         if (sdb->log->last()>OWLOG_WARNING) {
569                                 exit(1);
570                         }
571                         sdb->createSensorTable();
572                         if (sdb->log->last()>OWLOG_WARNING) {
573                                 exit(1);
574                         }                               
575                         database=1;
576                 }
577 #endif
578                         
579                 
580                 continuous(&(owi->devices),pause,1,reload);     
581         } else 
582         if ((s=getArg("f"))!="") {
583                 printf("Flash %s in selected Device\n",s.c_str());
584                 int sel=selectDevice();
585                 if (sel==0) exit(0);
586                 int resetid=questionYesNo("Would you reset to default ID? (This is necessary if another device is used!)");
587                 owi->log->setLogLevel(OWLOG_INFO);              
588                 owi->flashHEXFile(s,owi->device_nums[sel-1],resetid,1);
589                 setLogMode();
590                 owi->Clean();
591                 owi->Find();
592                 for (owDevice* dev :owi->devices) {
593                         snum_t snum=dev->getNum();
594                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
595
596                         printf("\n");
597                 }
598                 printf("%i Devices found\n",(int)owi->devices.size());  
599                                 
600         } else 
601         if ((s=getArg("v"))!="") {
602                 printf("Reset VOC\n");
603                 int sel=selectDevice();
604                 if (sel==0) exit(0);
605                 owDevice* dev=owi->devices[sel-1];
606                 std::vector<uint8_t> cl;
607                 cl.push_back(0x4E);
608                 cl.push_back(0x1F);
609                 cl.push_back(0x1F);
610                 cl.push_back(0x1F);
611                 dev->Communicate(&cl,4,0);
612         } else 
613         //------------------------------------------------------------------------------------------
614         // --------------------- Memory functions
615         //------------------------------------------------------------------------------------------
616         
617         if ((s=getArg("m"))!="") {
618                 int pnr=0;
619                 std::vector<uint8_t> mem;
620                 if(s.find("read")!=std::string::npos) {
621                         size_t cla=s.find_first_of("(",0);
622                         size_t page=s.find_first_of("p=",cla);
623                         size_t epage=s.find_first_of(";",page);
624                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
625                         std::string pn=s.substr(page+2,epage-page-2);
626                         printf("%s Read Memory Page %s of Device:\n",s.c_str(),pn.c_str());
627                         pnr=atoi(pn.c_str());
628
629                 } else 
630                 if(s.find("write")!=std::string::npos) {
631                         size_t cla=s.find("(",0);
632                         size_t page=s.find("p=",cla);
633                         size_t epage=s.find(";",page);
634                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
635                         std::string pn=s.substr(page+2,epage-page-2);
636                         size_t data=s.find("d=",cla);
637                         size_t edata=s.find(";",data);
638                         if (edata==std::string::npos) edata=s.find(")",data);
639                         std::string pd=s.substr(data+2,edata-data-2);
640                         std::istringstream pdss(pd);
641                         //std::cout << pd <<std::endl;
642                         while (!pdss.eof()) {
643                                 int v;
644                                 pdss>>std::hex>>v;
645                                 mem.push_back(v);
646                         }
647                         printf("Write ");
648                         for(uint8_t v :mem) printf("%02X ",v);
649                         printf("to Memory Page %s of Device:\n",pn.c_str());
650                         pnr=atoi(pn.c_str());
651
652                 } else exit(1);
653                 int sel=selectDevice();
654                 if (sel==0) exit(0);
655                 sel-=1;
656                 //snum_t snum=owi->devices[sel]->getNum();
657                 owDevice* dev=owi->devices[sel];
658                 if(s.find("read")!=std::string::npos) {
659                         int r=dev->readMemory(pnr,0,8,&mem);
660                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
661                         printf("\n");
662                         exit(0);
663                 } else 
664                 if(s.find("write")!=std::string::npos) {
665                         int r=dev->writeMemory(pnr,0,8,&mem);
666                         r=dev->readMemory(pnr,0,8,&mem);
667                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
668                         printf("\n");
669                         exit(0);
670                 }
671         }
672         if ((s=getArg("n"))!="") {
673                 printf("Change id of selected Device\n");
674                 int sel=selectDevice();
675                 if (sel==0) exit(0);
676                 sel-=1;
677                 
678                 snum_t snum=owi->devices[sel]->getNum();
679                 if ((getArg("g"))=="1") {
680                         printf("get ID from Server\n");
681                         char s[255];
682 #ifdef LINUX
683                         sprintf(s,"wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt",snum.byte[0]);
684 #endif
685 #ifdef WIN
686                         sprintf_s(s, "wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt", snum.byte[0]);
687 #endif
688                         int err;
689                         if ((err=system(s))==0) {
690                                 printf("OK!\n");
691                                 std::string rs;
692                                 std::stringstream str;
693                                 std::ifstream fs;
694                                 fs.open ("id.txt" );
695                                 snum_t isnum;
696                                 int i=0; int br=0;
697                                 if(fs.is_open()) {
698                                 while(fs.peek() != EOF) {
699                                         char c= (char) fs.get();
700                                         if (br==0) {
701                                                 if (c=='x') br=1;
702                                         } else {
703                                                 if ((c==',')|(c=='}')) {
704                                                         isnum.byte[i]=(uint8_t)strtol(s, NULL, 16);
705                                                         //printf("%x\n",strtol(s, NULL, 16));
706                                                         i++;
707                                                         br=0;
708                                                         s[0]=0;
709                                                 } else {
710                                                         s[br-1]=c;
711                                                         s[br]=0;
712                                                         br++;
713                                                 }
714                                         }
715                                         if (c=='}') break;
716                                 }
717                                 
718                                 fs.close();
719                                 }                                         
720                                 snum.num=isnum.num;
721                         } else (printf("ERROR %i\n",err));
722                 } else {
723                         snum.num+=256;
724                 }
725
726
727                 printf("New ID: ");
728                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
729
730                 printf("\n");
731                 
732                 owi->devices[sel]->changeID(snum);              
733         
734                 owi->Clean();
735                 owi->Find();
736                 for (owDevice* dev :owi->devices) {
737                         snum_t snum=dev->getNum();
738                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
739
740                         printf("\n");
741                 }
742                 printf("%i Devices found\n",(int)owi->devices.size());  
743                                 
744         } else {
745                 owi->Find();
746                 for (owDevice* dev :owi->devices) {
747                         printf("_______________________________________________________________________\n");
748                         snum_t snum=dev->getNum();
749                         printf(BLUE_B "%016llX " COLOR_E,(unsigned long long)snum.num);
750                         switch (dev->configstate) {
751                                 case OWDCS_16:printf("old Configcode from www.tm3d.de");break;
752                                 case OWDCS_24:printf("Configcode from www.tm3d.de");break;
753                                 case OWDCS_DEFAULT:printf("Default Configcode set by this Software");break;
754                                 case OWDCS_NONE:printf("No Configcode");break;
755                         }
756                         printf( " - (");
757                         for(int i=0;i<3;i++)
758                                 printf(" %s",dev->getFamilyInfo()[i].c_str());
759                         printf(" )\n");
760                         if (dev->configstate!=OWDCS_NONE) {
761                                 std::vector<std::vector<std::string>> ia;
762                                 std::vector<size_t> maxcol;
763                                 dev->convertAll();
764                                 for(int i=0;i<4;i++) {
765                                         std::vector<std::string> colm;
766                                         size_t max=0;
767                                         colm.push_back(dev->config->getSensorChip(i));
768                                         if (max<utf8_length(colm[0])) max=utf8_length(colm[0]);
769                                         colm.push_back(dev->config->getQuantity(i));
770                                         if (max<utf8_length(colm[1])) max=utf8_length(colm[1]);
771                                         colm.push_back(dev->config->getUnit(i));
772                                         if (max<utf8_length(colm[2])) max=utf8_length(colm[2]);
773                                         if (dev->config->getPropertyID(i)==0) {
774                                                 colm.push_back("");
775                                         } else {
776                                                 char hs[50];
777 #ifdef LINUX
778                                                 sprintf(hs,"%0.3f",dev->values[i]);
779 #endif
780 #ifdef WIN
781                                                 sprintf_s(hs, "%0.3f", dev->values[i]);
782 #endif
783                                                 colm.push_back(hs);
784                                         }
785                                         if (max<utf8_length(colm[3])) max=utf8_length(colm[3]);
786                                         ia.push_back(colm);
787                                         maxcol.push_back(max);
788                                 }
789                                 std::string space="                                                          ";
790                                 for(int i=0;i<4;i++) {
791                                         for(int j=0;j<4;j++) {
792                                                 printf("%s%s",ia[j][i].c_str(),space.substr(0,maxcol[j]-utf8_length(ia[j][i])+2).c_str());
793                                         }
794                                         printf("\n");
795                                 }
796                         }
797                 }
798                 printf("%i Devices found\n",(int)owi->devices.size());
799         }
800         return 0;
801    
802 }