Larger Timeout for Serial
[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 [\"id as 64bit Hex\"] change id   \n");
128 printf("                example: -n \"5D02160084D9A220\" \n");
129 printf("                no argument increments id by 256 (keep family code) \n");
130 printf("      -g get from server\n");
131 printf("   -w [1|2] show Warnings (1) or all information (2)\n");
132 printf("   -m memory functions\n");
133
134
135
136
137 }
138
139
140 typedef struct {
141         std::string flag;
142         std::string arg;
143 } arg_t ;
144
145
146 //length of shown chars of an UTF8 string ... sometimes not the same as byte count
147 std::size_t utf8_length(std::string const &s) {
148   std::size_t len = 0;
149   std::string::const_iterator begin = s.begin(), end = s.end();
150   while (begin != end) {
151     unsigned char c = *begin;
152     int n=1;
153     if      ((c & 0x80) == 0)    n = 1;
154     else if ((c & 0xE0) == 0xC0) n = 2;
155     else if ((c & 0xF0) == 0xE0) n = 3;
156     else if ((c & 0xF8) == 0xF0) n = 4;
157     
158     len += 1;
159     begin += n;
160   }
161   return len;
162 }
163
164
165 std::vector<arg_t> comlist;
166
167 std::string getArg(std::string flag) {
168         for(arg_t a:comlist) {
169                 if (a.flag==flag) return a.arg;
170         }
171         return ""; 
172 }
173
174
175
176 int getArgi(std::string flag) {
177         return atoi(getArg(flag).c_str());
178 }
179
180 #ifdef LINUX
181 int database=0;
182 mySensorDB *sdb=NULL;
183 #endif
184 /*
185 snum_t getArgsnum(std::string flag) {
186         snum_t snum;
187         snum.num=0;
188         return snum;
189 }
190 */
191 int findCPU(std::string cpu) {
192         std::ifstream fileInput;
193         std::string line;
194         fileInput.open("/proc/cpuinfo");
195         if(fileInput.is_open()) {       
196                 for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
197                         if (line.find(cpu) != std::string::npos) {
198                                 fileInput.close();
199                                 return 1;
200                         }
201                 }
202                 fileInput.close();
203                 
204         }
205         return 0;
206 }
207
208
209
210
211 owInterface *owi= NULL;
212
213 void setLogMode() {
214         if (getArg("w")=="2")
215                         owi->log->setLogLevel(0);
216         else if (getArg("w")=="2") owi->log->setLogLevel(0);
217         else owi->log->setLogLevel(OWLOG_ERROR);
218
219 }
220
221
222 void continuous(std::vector<owDevice*> *devices,int intervall,int headline,int searchrom) {
223         int first=1;
224         while (1) {
225                 if (searchrom) {
226                         owi->log->clear();
227                         owi->Find();
228                         if (owi->isDevicesChanged()||(first==1)) {
229                                 first=0;
230                                 if (headline) {
231                                         printf("                     \t");
232                                         for (owDevice* dev :*devices) {
233                                                 if (dev->configstate!=OWDCS_NONE) {
234                                                         for (size_t i=0;i<4;i++) {
235                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
236                                                                         printf(BLUE_B "%02X.%02X%02X" COLOR_E "\t",dev->getNum().byte[7],dev->getNum().byte[1],dev->getNum().byte[0]);
237                                                         }
238                                                 }
239                                         }
240                                         printf("\ntime                 \t");
241                                         for (owDevice* dev :*devices) {
242                                                 if (dev->configstate!=OWDCS_NONE) {
243                                                         for (size_t i=0;i<4;i++) {
244                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
245                                                                         printf(C2_B "%s" COLOR_E "\t",dev->config->getQuantity((uint8_t)i).substr(0,7).c_str());
246                                                         }
247                                                 }
248                                         }
249                                         printf("\n                     \t");
250                                         for (owDevice* dev :*devices) {
251                                                 if (dev->configstate!=OWDCS_NONE) {
252                                                         for (size_t i=0;i<4;i++) {
253                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0) {
254                                                                         size_t l=utf8_length(dev->config->getUnit((uint8_t)i));
255                                                                         std::string ls="           ";
256                                                                         printf(C3_B "[%s]%s" COLOR_E "\t",dev->config->getUnit((uint8_t)i).c_str(),ls.substr(0,5-l).c_str());
257                                                                 }
258                                                         }
259                                                 }
260                                         }
261                                         
262                                 }       
263                                 printf("\n");
264 #ifdef LINUX
265                                 if (database) {
266                                         //owi->log->setLogLevel(0);
267                                         for (owDevice* dev : *devices) {
268                                                 sdb->createDeviceTable(dev);
269                                         }
270                                 }
271 #endif
272                         }
273                         
274                 }
275                 time_t t=time(NULL);
276                 int st=(int)t;
277 #ifdef LINUX
278                 struct tm tm = *localtime(&t);
279 #endif
280 #ifdef WIN
281                 struct tm tm;
282                 localtime_s(&tm,&t);
283 #endif
284                 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);
285                 for (owDevice* dev :*devices) {
286                         for(int k=0;k<owi->maxrepeat;k++){
287                                 dev->convertAll();
288                                 if (owi->log->last()<OWLOG_ERROR) break;
289                                 owi->log->clear();
290                         }
291                         if (owi->log->last()<OWLOG_ERROR) {
292                                 if (dev->configstate!=OWDCS_NONE) {
293                                         for (size_t i=0;i<4;i++) {                                      
294                                                 if (dev->config->getPropertyID((int8_t)i)!=0) {
295                                                         if (dev->values[i]<=-10) 
296                                                                 printf("%0.2f \t",dev->values[i]);
297                                                         else if (dev->values[i]<0) 
298                                                                 printf("%0.3f \t",dev->values[i]);
299                                                         else if (dev->values[i]<10) 
300                                                                 printf("%0.4f \t",dev->values[i]);
301                                                         else if (dev->values[i]<100)    
302                                                                 printf("%0.3f \t",dev->values[i]);
303                                                         else if (dev->values[i]<1000)   
304                                                                 printf("%0.2f \t",dev->values[i]);
305                                                         else
306                                                                 printf("%0.1f \t",dev->values[i]);
307                                                         fflush(stdout);
308                                                 }
309                                         }
310                                 }
311 #ifdef LINUX
312                                 if (database) {
313                                         sdb->insertValues(dev);
314                                 }
315 #endif
316                         } else {
317                                 owi->log->setLogLevel(OWLOG_INFO);
318                                 owi->log->set(OWLOG_ERROR,"Too many errors, mybee conection is dead.");
319                                 return;
320                         }
321                         
322                 
323                 }
324                 printf("\n");
325                 while (((int)time(NULL)) < (st + intervall)) {
326 #ifdef LINUX
327                         sleep(1);
328 #endif
329 #ifdef WIN
330                         Sleep(1000);
331 #endif          
332                 }
333         }
334 }
335
336 void device_menu(owDevice* d) {
337         for(int i=0;i<70;i++) printf(HL);printf("\n");
338         printf("Selected Device: ");
339         snum_t snum=d->getNum();
340         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
341         printf("  \n");
342         printf("Chip Info: ");
343         std::vector<std::string> info=d->getFamilyInfo();
344         for (std::string s : info) printf(" %s",s.c_str());
345         printf("\n");
346         printf("Values info: ");
347         int tm3d=d->readConfig();
348         for (size_t i=0;i<4;i++) {
349                 printf("%s in %s",d->config->getQuantity((uint8_t)i).c_str(),d->config->getUnit((uint8_t)i).c_str());
350                 if (i<4) printf("; "); 
351         }
352         if (tm3d) printf(" (tm3d.de)"); else printf(" (default)"); 
353         printf("\n");
354         d->convertAll();
355         for (size_t i=0;i<d->values.size();i++) {
356                 printf(C4_B "%0.4f %s" COLOR_E,d->values[i],d->config->getUnit((uint8_t)i).c_str());
357         }
358         printf("\n");
359         for(int i=0;i<70;i++) printf(HL);printf("\n");
360         printf("0) Exit\n");
361         printf("1) Run continuous\n");
362         std::string inp;
363         while (1) {
364                 printf("Select an option: ");std::getline (std::cin,inp);
365                 int dnr=atoi(inp.c_str());
366                 if (dnr<=0) return;
367                 if (dnr==1) {
368                         std::vector<owDevice*> v;
369                         v.push_back(d);
370                         continuous(&v,1,1,0);
371                 } 
372 //                      if (dnr<=i) break; 
373         //              printf("\033[4;33mSelect a number between 0 and %i\033[0m\n",i);
374         }
375         
376         
377 }
378
379 int selectDevice() {
380         owi->Find();
381         int i=0;
382         for (owDevice* dev :owi->devices) {
383                 i++;
384                 snum_t snum=dev->getNum();
385                 printf("%i) ",i);
386                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
387
388                 printf("  ");
389                 for (int j=0;j<4;j++) printf("%s ",dev->config->getQuantity(j).c_str());
390                 printf("\n");
391         }
392         printf("0) Exit Programm\n");
393         std::string inp;
394         int dnr=0;
395         while (1) {
396                 printf("Select device with number: ");std::getline (std::cin,inp);
397                 dnr=atoi(inp.c_str());
398                 if (dnr<=0) return 0;
399                 if (dnr<=i) break; 
400                 printf(C5_B "Select a number between 0 and %i" COLOR_E "\n",i);
401         }
402         return dnr;
403
404 }
405
406 int questionYesNo(std::string text) {
407         std::string inp;
408         printf("%s [Y/n] ",text.c_str());std::getline (std::cin,inp);
409         if (inp=="Y") return 1; else return 0;
410         
411 }
412
413 void interactive(owInterface *owi) {
414         while (1) {
415                 int i=selectDevice();
416                 if (i==0 ) return;
417                 device_menu(owi->devices[i-1]);
418         }
419 }
420
421 int main(int argc, char *argv[]) {
422         int i;
423         arg_t a;
424         //printf("Kommando: %s:\n", argv[0]);
425         while (--argc) {
426                 if (**++argv != '-') {
427         //printf("   Arg. = %s\n", *argv);
428         if (comlist.empty()) {
429                 a.flag=".";
430                 a.arg=*argv;
431                 comlist.push_back(a);
432         } else {
433                 if ((*(comlist.end()-1)).arg!="1") {
434                         a.flag=".";
435                         a.arg=*argv;
436                         comlist.push_back(a);
437                 } else {
438                         (*(comlist.end()-1)).arg=*argv;
439                 }
440         }
441                 } else {
442                         for( i=1; (*argv)[i] != '\0'; i++) {
443                                 //printf("   Flag = (%c)\n", (*argv)[i]);
444                                 a.flag=(*argv)[i];
445                                 a.arg="1";
446                                 comlist.push_back(a);
447                         }
448                 }
449     }          
450
451         //for(arg_t a:comlist) printf("%s->%s\n",a.flag.c_str(),a.arg.c_str());
452         if (getArg("h")=="1") {
453                 printhelp();
454                 return 0;
455         }
456         std::string adapter=getArg("a");
457         if (adapter.empty()) {
458                 printhelp();
459                 return 0;
460         }       
461         std::transform(adapter.begin(), adapter.end(),adapter.begin(), ::toupper);
462
463         std::string s;
464 #ifdef LINUX    
465         if(adapter.find("COM")!=std::string::npos) {
466                 owi=new owCOMInterface();
467                 int port=atoi(adapter.substr(adapter.find("COM")+3).c_str());
468                 printf("Open /dev/ttyUSB%i\n",port);
469                 owi->InitAdapter(port);
470         } else 
471         if(adapter.find("USB")!=std::string::npos) {
472                 owi=new owUSBInterface();
473                 int port=atoi(adapter.substr(adapter.find("USB")+3).c_str());
474                 printf("Open the %i. USB Adapter\n",port);
475                 int err;
476                 if ((err=owi->InitAdapter(port))<0) {
477                         if (err==-1) printf("No Adapter found!\n  On Linux, try: sudo owTools....\n  On Windows: Install libusb0 driver\n");
478                         if (err==-2) printf("Maybe Adapter is used ... (try sudo)\nOn Linux: If the kernel modul is loaded type: sudo rmmod ds2490\n");
479                         exit(0);
480                 }
481         } else 
482         if(adapter.find("GPIO")!=std::string::npos) {
483                 if (findCPU("BCM2708")) {
484                         printf("\033[1;33mRaspberry Pi 1 is dedected. 1-wire on the GPIO port can have many errors in the transfer.\033[0m\n");
485                         owi=new owPiGPioInterface();
486                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
487                         printf("Open GPIO %i\n",port);
488                 } else if (findCPU("BCM2709")) {
489                         owi=new owPiGPioInterface();
490                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
491                         printf("Open GPIO %i\n",port);
492                         owi->InitAdapter(port);
493                 } else {
494                         printf("\033[1;31mGPIO works with Raspberry PI only \033[0m\n");
495                 }
496         }  else
497         if(adapter.find("W1")!=std::string::npos) {
498                 owi=new owW1Interface();
499                 if (owi->InitAdapter(0)) {
500                         printf("Use W1-Kernel 1-Wire functions on /sys/bus/w1\n");
501                 } else printf("No W1-Kernel module found!!\n");
502         } else 
503 #endif
504         if (adapter.find("ARDUINO") != std::string::npos) {
505                 owi = new owARDUINOInterface();
506                 int port = atoi(adapter.substr(adapter.find("ARDUINO") + 7).c_str());
507                 printf("Open /dev/ttyS%i\n", port);
508                 owi->InitAdapter(port);
509         }
510
511 #ifdef WIN
512                 else 
513         if (adapter.find("USB") != std::string::npos) {
514                 printf("USB \n");
515                 owi = new owTMEXWIN();
516                 int port = atoi(adapter.substr(adapter.find("USB") + 3).c_str());
517                 printf("Open the %i. USB Adapter\n", port);
518                 int err;
519                 char cs[20];
520                 sprintf_s(cs, 20, "{%i,6}", port);
521                 if ((err = owi->InitAdapter(cs))==0) {
522                                         printf("ERROR Init USB Adapter\n");
523                                         exit(0);
524                                 }
525                         }
526         else
527                 if (adapter.find("COM") != std::string::npos) {
528                         owi = new owTMEXWIN();
529                         int port = atoi(adapter.substr(adapter.find("COM") + 3).c_str());
530                         printf("Open Adapter on COM%i\n", port);
531                         int err;
532                         char cs[20];
533                         sprintf_s(cs, 20, "{%i,5}", port);
534                         if ((err = owi->InitAdapter(cs))==0) {
535                                 printf("ERROR Init Serial Adapter\n");
536                                 exit(0);
537                         }
538                 }
539 #endif
540         if (owi == NULL) {
541                 printf("No 1-Wiremaster found\n");
542                 return 0;
543         }
544         setLogMode();
545         
546         
547
548         if (getArg("i")=="1") {
549                 interactive(owi);       
550         } else 
551         if (getArg("c")=="1") {
552                 int reload=(getArg("r")=="1");
553                 owi->Find();
554                 printf("\n");
555                 //owi->log->setLogLevel(3);
556                 std::string s;
557                 int pause;
558                 if ((s=getArg("p")) !="") {
559                         pause=atoi(s.c_str());
560                 } else pause=30;
561 #ifdef LINUX
562                 if  ((s=getArg("d")) !="") {
563                         reload=1;
564                         printf("Use Database\n");
565                         sdb=new mySensorDB(s,owi->log);
566                         if (sdb->log->last()>OWLOG_WARNING) {
567                                 exit(1);
568                         }
569                         sdb->connect();
570                         if (sdb->log->last()>OWLOG_WARNING) {
571                                 exit(1);
572                         }
573                         sdb->createSensorTable();
574                         if (sdb->log->last()>OWLOG_WARNING) {
575                                 exit(1);
576                         }                               
577                         database=1;
578                 }
579 #endif
580                         
581                 
582                 continuous(&(owi->devices),pause,1,reload);     
583         } else 
584         if ((s=getArg("f"))!="") {
585                 printf("Flash %s in selected Device\n",s.c_str());
586                 int sel=selectDevice();
587                 if (sel==0) exit(0);
588                 int resetid=questionYesNo("Would you reset to default ID? (This is necessary if another device is used!)");
589                 owi->log->setLogLevel(OWLOG_INFO);              
590                 owi->flashHEXFile(s,owi->device_nums[sel-1],resetid,1);
591                 setLogMode();
592                 owi->Clean();
593                 owi->Find();
594                 for (owDevice* dev :owi->devices) {
595                         snum_t snum=dev->getNum();
596                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
597
598                         printf("\n");
599                 }
600                 printf("%i Devices found\n",(int)owi->devices.size());  
601                                 
602         } else 
603         if ((s=getArg("v"))!="") {
604                 printf("Reset VOC\n");
605                 int sel=selectDevice();
606                 if (sel==0) exit(0);
607                 owDevice* dev=owi->devices[sel-1];
608                 std::vector<uint8_t> cl;
609                 cl.push_back(0x4E);
610                 cl.push_back(0x1F);
611                 cl.push_back(0x1F);
612                 cl.push_back(0x1F);
613                 dev->Communicate(&cl,4,0);
614         } else 
615         //------------------------------------------------------------------------------------------
616         // --------------------- Memory functions
617         //------------------------------------------------------------------------------------------
618         
619         if ((s=getArg("m"))!="") {
620                 int pnr=0;
621                 std::vector<uint8_t> mem;
622                 if(s.find("read")!=std::string::npos) {
623                         size_t cla=s.find_first_of("(",0);
624                         size_t page=s.find_first_of("p=",cla);
625                         size_t epage=s.find_first_of(";",page);
626                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
627                         std::string pn=s.substr(page+2,epage-page-2);
628                         printf("%s Read Memory Page %s of Device:\n",s.c_str(),pn.c_str());
629                         pnr=atoi(pn.c_str());
630
631                 } else 
632                 if(s.find("write")!=std::string::npos) {
633                         size_t cla=s.find("(",0);
634                         size_t page=s.find("p=",cla);
635                         size_t epage=s.find(";",page);
636                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
637                         std::string pn=s.substr(page+2,epage-page-2);
638                         size_t data=s.find("d=",cla);
639                         size_t edata=s.find(";",data);
640                         if (edata==std::string::npos) edata=s.find(")",data);
641                         std::string pd=s.substr(data+2,edata-data-2);
642                         std::istringstream pdss(pd);
643                         //std::cout << pd <<std::endl;
644                         while (!pdss.eof()) {
645                                 int v;
646                                 pdss>>std::hex>>v;
647                                 mem.push_back(v);
648                         }
649                         printf("Write ");
650                         for(uint8_t v :mem) printf("%02X ",v);
651                         printf("to Memory Page %s of Device:\n",pn.c_str());
652                         pnr=atoi(pn.c_str());
653
654                 } else exit(1);
655                 int sel=selectDevice();
656                 if (sel==0) exit(0);
657                 sel-=1;
658                 //snum_t snum=owi->devices[sel]->getNum();
659                 owDevice* dev=owi->devices[sel];
660                 if(s.find("read")!=std::string::npos) {
661                         int r=dev->readMemory(pnr,0,8,&mem);
662                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
663                         printf("\n");
664                         exit(0);
665                 } else 
666                 if(s.find("write")!=std::string::npos) {
667                         int r=dev->writeMemory(pnr,0,8,&mem);
668                         r=dev->readMemory(pnr,0,8,&mem);
669                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
670                         printf("\n");
671                         exit(0);
672                 }
673         }
674         if ((s=getArg("n"))!="") {
675                 printf("Change id of selected Device\n");
676                 int sel=selectDevice();
677                 if (sel==0) exit(0);
678                 sel-=1;
679                 
680                 snum_t snum=owi->devices[sel]->getNum();
681                 
682                 if ((getArg("g"))=="1") {
683                         printf("get ID from Server\n");
684                         char s[255];
685 #ifdef LINUX
686                         sprintf(s,"wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt",snum.byte[0]);
687 #endif
688 #ifdef WIN
689                         sprintf_s(s, "wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt", snum.byte[0]);
690 #endif
691                         int err;
692                         if ((err=system(s))==0) {
693                                 printf("OK!\n");
694                                 std::string rs;
695                                 std::stringstream str;
696                                 std::ifstream fs;
697                                 fs.open ("id.txt" );
698                                 snum_t isnum;
699                                 int i=0; int br=0;
700                                 if(fs.is_open()) {
701                                 while(fs.peek() != EOF) {
702                                         char c= (char) fs.get();
703                                         if (br==0) {
704                                                 if (c=='x') br=1;
705                                         } else {
706                                                 if ((c==',')|(c=='}')) {
707                                                         isnum.byte[i]=(uint8_t)strtol(s, NULL, 16);
708                                                         //printf("%x\n",strtol(s, NULL, 16));
709                                                         i++;
710                                                         br=0;
711                                                         s[0]=0;
712                                                 } else {
713                                                         s[br-1]=c;
714                                                         s[br]=0;
715                                                         br++;
716                                                 }
717                                         }
718                                         if (c=='}') break;
719                                 }
720                                 
721                                 fs.close();
722                                 }                                         
723                                 snum.num=isnum.num;
724                         } else (printf("ERROR %i\n",err));
725                 } else {
726                         if (s=="1") {
727                                 snum.num+=256;
728                         } else {
729                                 unsigned long long l=strtol(s.c_str(),NULL,16);
730                                 if ((snum.num&0xFF)!=(l&0xFF)) {
731                                         printf("ERROR: Family of Device 0x%02X->0x%02X can not be changed\n",(int)(snum.num&0xFF),(int)(l&0xFF));
732                                         exit(1);
733                                 }
734                                 snum.num=l;
735                                 //printf("->%016llX\n",(unsigned long long)l);
736                         }
737                         
738                 }
739
740
741                 printf("New ID: ");
742                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
743
744                 printf("\n");
745                 
746                 owi->devices[sel]->changeID(snum);              
747         
748                 owi->Clean();
749                 owi->Find();
750                 for (owDevice* dev :owi->devices) {
751                         snum_t snum=dev->getNum();
752                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
753
754                         printf("\n");
755                 }
756                 printf("%i Devices found\n",(int)owi->devices.size());  
757                                 
758         } else {
759                 owi->Find();
760                 for (owDevice* dev :owi->devices) {
761                         printf("_______________________________________________________________________\n");
762                         snum_t snum=dev->getNum();
763                         printf(BLUE_B "%016llX " COLOR_E,(unsigned long long)snum.num);
764                         switch (dev->configstate) {
765                                 case OWDCS_16:printf("old Configcode from www.tm3d.de");break;
766                                 case OWDCS_24:printf("Configcode from www.tm3d.de");break;
767                                 case OWDCS_DEFAULT:printf("Default Configcode set by this Software");break;
768                                 case OWDCS_NONE:printf("No Configcode");break;
769                         }
770                         printf( " - (");
771                         for(int i=0;i<3;i++)
772                                 printf(" %s",dev->getFamilyInfo()[i].c_str());
773                         printf(" )\n");
774                         if (dev->configstate!=OWDCS_NONE) {
775                                 std::vector<std::vector<std::string>> ia;
776                                 std::vector<size_t> maxcol;
777                                 dev->convertAll();
778                                 for(int i=0;i<4;i++) {
779                                         std::vector<std::string> colm;
780                                         size_t max=0;
781                                         colm.push_back(dev->config->getSensorChip(i));
782                                         if (max<utf8_length(colm[0])) max=utf8_length(colm[0]);
783                                         colm.push_back(dev->config->getQuantity(i));
784                                         if (max<utf8_length(colm[1])) max=utf8_length(colm[1]);
785                                         colm.push_back(dev->config->getUnit(i));
786                                         if (max<utf8_length(colm[2])) max=utf8_length(colm[2]);
787                                         if (dev->config->getPropertyID(i)==0) {
788                                                 colm.push_back("");
789                                         } else {
790                                                 char hs[50];
791 #ifdef LINUX
792                                                 sprintf(hs,"%0.3f",dev->values[i]);
793 #endif
794 #ifdef WIN
795                                                 sprintf_s(hs, "%0.3f", dev->values[i]);
796 #endif
797                                                 colm.push_back(hs);
798                                         }
799                                         if (max<utf8_length(colm[3])) max=utf8_length(colm[3]);
800                                         ia.push_back(colm);
801                                         maxcol.push_back(max);
802                                 }
803                                 std::string space="                                                          ";
804                                 for(int i=0;i<4;i++) {
805                                         for(int j=0;j<4;j++) {
806                                                 printf("%s%s",ia[j][i].c_str(),space.substr(0,maxcol[j]-utf8_length(ia[j][i])+2).c_str());
807                                         }
808                                         printf("\n");
809                                 }
810                         }
811                 }
812                 printf("%i Devices found\n",(int)owi->devices.size());
813         }
814         return 0;
815    
816 }