c4e223dee6ec7780333cd5096a14be4280dcea11
[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
48
49 #endif
50
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <stdint.h>
54 #include <fcntl.h>    /* For O_RDWR */
55 #include <memory.h>
56 #include "hexfile.h"
57 #include <iostream>
58 #include <algorithm>
59 #include <fstream>
60 #include <sstream> 
61
62
63 #ifdef LINUX
64
65 #define RB "\e(0\x6a\e(B" // 188 Right Bottom corner
66 #define RT "\e(0\x6b\e(B" // 187 Right Top corner
67 #define LT "\e(0\x6c\e(B" // 201 Left Top cornet
68 #define LB "\e(0\x6d\e(B" // 200 Left Bottom corner
69 #define MC "\e(0\x6e\e(B" // 206 Midle Cross
70 #define HL "\e(0\x71\e(B" // 205 Horizontal Line
71 #define LC "\e(0\x74\e(B" // 204 Left Cross
72 #define RC "\e(0\x75\e(B" // 185 Right Cross
73 #define BC "\e(0\x76\e(B" // 202 Bottom Cross
74 #define TC "\e(0\x77\e(B" // 203 Top Cross
75 #define VL "\e(0\x78\e(B" // 186 Vertical Line
76 #define SP " "            // space string
77 #define BLUE_B "\033[1;34m"
78 #define COLOR_E "\033[0m"
79 #define C2_B "\033[0;36m"
80 #define C3_B "\033[3;34m"
81 #define C4_B "\033[1;33m"
82 #define C5_B "\033[4;33m"
83 #endif
84 #ifdef WIN
85 #define RB " "// 188 Right Bottom corner
86 #define RT  " "// 187 Right Top corner
87 #define LT  " "// 201 Left Top cornet
88 #define LB  " "// 200 Left Bottom corner
89 #define MC " " // 206 Midle Cross
90 #define HL " "// 205 Horizontal Line
91 #define LC  " "// 204 Left Cross
92 #define RC  " "// 185 Right Cross
93 #define BC  " "// 202 Bottom Cross
94 #define TC  " "// 203 Top Cross
95 #define VL  " "// 186 Vertical Line
96 #define SP " "            // space string
97 #define BLUE_B ""
98 #define C2_B ""
99 #define C3_B ""
100 #define C4_B ""
101 #define COLOR_E ""
102 #define C5_B ""
103
104
105 #endif
106
107 void printhelp() {
108 printf("owTools - Program for reading and controlling 1-Wire Devices from www.tm3d.de\n\n");
109 printf("run:  owTools -a [COMn|USBn|GPIOn] [options]\n\n");
110 printf("    COMn -> Adapter DS9097 and compatible (e.g. LinkUSB)\n");
111 printf("         n=1 -> Windows COM1 -> Linux /dev/ttyS1\n");
112 printf("    USBn -> Adapter DS2490/DS9490 \n");
113 printf("         n=1 -> first USB-Adapter \n");
114 printf("    GPIOn -> port of RaspberrPI (port Name not Pin number)\n\n");
115 printf("Options:\n");
116 printf("   -i interactive mode\n");
117 printf("          select a device and get information about it\n");
118 printf("   -s \"id as 64bit Hex\" try to skip select menu with this id  \n");
119 printf("                example: -s \"5D02160084D9A220\" \n");
120 printf("   -c read and print all continuous\n");
121 printf("      -p time in sec between readings\n");
122 printf("      -d [config file] put all Data in mysql Database descripted in config file\n");
123 printf("         Config file: \n");
124 printf("            [server]\n");
125 printf("            [port] -> 3306\n");
126 printf("            [user] \n");
127 printf("            [password]\n");
128 printf("            [database]\n");
129 printf("            [prefix] -> a prefix of all tables \n\n");
130 printf("      -r Search every time for new Devices\n");
131 printf("      -t [text_file] append comma separadet to text-file\n");
132 printf("   -f [hexfile]    flash new\n");
133 printf("   -n [\"id as 64bit Hex\"] change id   \n");
134 printf("                example: -n \"5D02160084D9A220\" \n");
135 printf("                no argument increments id by 256 (keep family code) \n");
136 printf("      -g get from server\n");
137 printf("   -w [1|2] show Warnings (1) or all information (2)\n");
138 printf("   -m memory functions\n");
139 printf("   -x write direct 1-Wire\n");
140
141
142
143
144 }
145
146
147 typedef struct {
148         std::string flag;
149         std::string arg;
150 } arg_t ;
151
152
153 //length of shown chars of an UTF8 string ... sometimes not the same as byte count
154 std::size_t utf8_length(std::string const &s) {
155   std::size_t len = 0;
156   std::string::const_iterator begin = s.begin(), end = s.end();
157   while (begin != end) {
158     unsigned char c = *begin;
159     int n=1;
160     if      ((c & 0x80) == 0)    n = 1;
161     else if ((c & 0xE0) == 0xC0) n = 2;
162     else if ((c & 0xF0) == 0xE0) n = 3;
163     else if ((c & 0xF8) == 0xF0) n = 4;
164     
165     len += 1;
166     begin += n;
167   }
168   return len;
169 }
170
171
172 std::vector<arg_t> comlist;
173
174 std::string getArg(std::string flag) {
175         for(arg_t a:comlist) {
176                 if (a.flag==flag) return a.arg;
177         }
178         return ""; 
179 }
180
181
182
183 int getArgi(std::string flag) {
184         return atoi(getArg(flag).c_str());
185 }
186
187 #ifdef LINUX
188 int database=0;
189 mySensorDB *sdb=NULL;
190 #endif
191 int textfile=0;
192 std::string textfilename;
193
194
195 /*
196 snum_t getArgsnum(std::string flag) {
197         snum_t snum;
198         snum.num=0;
199         return snum;
200 }
201 */
202 int findCPU(std::string cpu) {
203         std::ifstream fileInput;
204         std::string line;
205         fileInput.open("/proc/cpuinfo");
206         if(fileInput.is_open()) {       
207                 for(unsigned int curLine = 0; getline(fileInput, line); curLine++) {
208                         if (line.find(cpu) != std::string::npos) {
209                                 fileInput.close();
210                                 return 1;
211                         }
212                 }
213                 fileInput.close();
214                 
215         }
216         return 0;
217 }
218
219
220
221
222 owInterface *owi= NULL;
223
224 void setLogMode() {
225         if (getArg("w")=="2")
226                         owi->log->setLogLevel(0);
227         else if (getArg("w")=="2") owi->log->setLogLevel(0);
228         else owi->log->setLogLevel(OWLOG_ERROR);
229
230 }
231
232 int appendTextFile(std::string line) {
233         std::ofstream file;
234     file.open(textfilename, std::ios::out | std::ios::app);
235     if (file.fail()) {
236                 owi->log->set(OWLOG_ERROR,"Can not open outputfile for text output");
237                 return -1;
238         }
239    
240
241     file << line << std::endl;
242     file.close();
243     return 0;
244 }
245
246
247 void continuous(std::vector<owDevice*> *devices,int intervall,int headline,int searchrom) {
248         int first=1;
249         char valbuf[100];
250         std::string tfl;
251         while (1) {
252                 if (searchrom) {
253                         owi->log->clear();
254                         owi->Find();
255                         if (owi->isDevicesChanged()||(first==1)) {
256                                 first=0;
257                                 if (headline) {
258                                         printf("                     \t");
259                                         for (owDevice* dev :*devices) {
260                                                 if (dev->configstate!=OWDCS_NONE) {
261                                                         for (size_t i=0;i<4;i++) {
262                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
263                                                                         printf(BLUE_B "%02X.%02X%02X" COLOR_E "\t",dev->getNum().byte[7],dev->getNum().byte[1],dev->getNum().byte[0]);
264                                                         }
265                                                 }
266                                         }
267                                         printf("\ntime                 \t");
268                                         for (owDevice* dev :*devices) {
269                                                 if (dev->configstate!=OWDCS_NONE) {
270                                                         for (size_t i=0;i<4;i++) {
271                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0)
272                                                                         printf(C2_B "%s" COLOR_E "\t",dev->config->getQuantity((uint8_t)i).substr(0,7).c_str());
273                                                         }
274                                                 }
275                                         }
276                                         printf("\n                     \t");
277                                         for (owDevice* dev :*devices) {
278                                                 if (dev->configstate!=OWDCS_NONE) {
279                                                         for (size_t i=0;i<4;i++) {
280                                                                 if (dev->config->getPropertyID((uint8_t)i)!=0) {
281                                                                         size_t l=utf8_length(dev->config->getUnit((uint8_t)i));
282                                                                         std::string ls="           ";
283                                                                         printf(C3_B "[%s]%s" COLOR_E "\t",dev->config->getUnit((uint8_t)i).c_str(),ls.substr(0,5-l).c_str());
284                                                                 }
285                                                         }
286                                                 }
287                                         }
288                                         
289                                 }       
290                                 printf("\n");
291 #ifdef LINUX
292                                 if (database) {
293                                         //owi->log->setLogLevel(0);
294                                         for (owDevice* dev : *devices) {
295                                                 sdb->createDeviceTable(dev);
296                                         }
297                                 }
298 #endif
299                         }
300                         
301                 }
302                 time_t t=time(NULL);
303                 int st=(int)t;
304 #ifdef LINUX
305                 struct tm tm = *localtime(&t);
306 #endif
307 #ifdef WIN
308                 struct tm tm;
309                 localtime_s(&tm,&t);
310 #endif
311
312                 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);
313                 if (textfile) {
314                         snprintf(valbuf,100,"%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
315                         tfl=valbuf;
316                 }
317
318
319                 for (owDevice* dev :*devices) {
320                         for(int k=0;k<owi->maxrepeat;k++){
321                                 //std::vector<uint8_t> data;
322                                 //data.push_back(0xCC);
323                                 //data.push_back(0x44);
324                                 //owi->Reset();
325                                 //owi->Communicate(&data, 2, 0);
326                                 dev->convertAll();
327                                 if (owi->log->last()<OWLOG_ERROR) break;
328                                 owi->log->clear();
329                         }
330                         if (owi->log->last()<OWLOG_ERROR) {
331                                 if (dev->configstate!=OWDCS_NONE) {
332                                         for (size_t i=0;i<4;i++) {                                      
333                                                 if (dev->config->getPropertyID((int8_t)i)!=0) {
334                                                         if (dev->values[i]<=-10) 
335                                                                 printf("%0.2f \t",dev->values[i]);
336                                                         else if (dev->values[i]<0) 
337                                                                 printf("%0.3f \t",dev->values[i]);
338                                                         else if (dev->values[i]<10) 
339                                                                 printf("%0.4f \t",dev->values[i]);
340                                                         else if (dev->values[i]<100)    
341                                                                 printf("%0.3f \t",dev->values[i]);
342                                                         else if (dev->values[i]<1000)   
343                                                                 printf("%0.2f \t",dev->values[i]);
344                                                         else
345                                                                 printf("%0.1f \t",dev->values[i]);
346                                                         fflush(stdout);
347                                                         if (textfile) {
348                                                                 snprintf(valbuf,100,",%0.4f",dev->values[i]);
349                                                                 tfl.append(valbuf);
350                                                         }
351                                                 }
352                                         }
353                                 }
354 #ifdef LINUX
355                                 if (database) {
356                                         sdb->insertValues(dev);
357                                 }
358 #endif
359                         } else {
360                                 owi->log->setLogLevel(OWLOG_INFO);
361                                 owi->log->set(OWLOG_ERROR,"Too many errors, mybee conection is dead.");
362                                 return;
363                         }
364                         
365                 
366                 }
367                 printf("\n");
368                 if (textfile) {
369                         appendTextFile(tfl);
370                 }
371                 while (((int)time(NULL)) < (st + intervall)) {
372 #ifdef LINUX
373                         sleep(1);
374 #endif
375 #ifdef WIN
376                         Sleep(1000);
377 #endif          
378                 }
379         }
380 }
381
382 void device_menu(owDevice* d) {
383         for(int i=0;i<70;i++) printf(HL);printf("\n");
384         printf("Selected Device: ");
385         snum_t snum=d->getNum();
386         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
387         printf("  \n");
388         printf("Chip Info: ");
389         std::vector<std::string> info=d->getFamilyInfo();
390         for (std::string s : info) printf(" %s",s.c_str());
391         printf("\n");
392         printf("Values info: ");
393         int tm3d=d->readConfig();
394         for (size_t i=0;i<4;i++) {
395                 printf("%s in %s",d->config->getQuantity((uint8_t)i).c_str(),d->config->getUnit((uint8_t)i).c_str());
396                 if (i<4) printf("; "); 
397         }
398         if (tm3d) printf(" (tm3d.de)"); else printf(" (default)"); 
399         printf("\n");
400         d->convertAll();
401         for (size_t i=0;i<d->values.size();i++) {
402                 printf(C4_B "%0.4f %s" COLOR_E,d->values[i],d->config->getUnit((uint8_t)i).c_str());
403         }
404         printf("\n");
405         for(int i=0;i<70;i++) printf(HL);printf("\n");
406         printf("0) Exit\n");
407         printf("1) Run continuous\n");
408         std::string inp;
409         while (1) {
410                 printf("Select an option: ");std::getline (std::cin,inp);
411                 int dnr=atoi(inp.c_str());
412                 if (dnr<=0) return;
413                 if (dnr==1) {
414                         std::vector<owDevice*> v;
415                         v.push_back(d);
416                         continuous(&v,1,1,0);
417                 } 
418 //                      if (dnr<=i) break; 
419         //              printf("\033[4;33mSelect a number between 0 and %i\033[0m\n",i);
420         }
421         
422         
423 }
424
425 int selectDevice() {
426         std::string s;
427         owi->Find();
428         int i = 0;
429         char *end;
430         unsigned long long l = 0;
431         if ((s = getArg("s")) != "") {
432                 l = strtoull(s.c_str(), &end, 16);
433                 for (owDevice* dev : owi->devices) {
434                         i++;
435                         snum_t snum = dev->getNum();
436                         if (l == snum.num) return i;
437
438                 }
439                 printf("Number not found -> Select one or exit!\n");
440         }
441
442         i=0;
443         for (owDevice* dev :owi->devices) {
444                 i++;
445                 snum_t snum=dev->getNum();
446                 printf("%i) ",i);
447                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
448
449                 printf("  ");
450                 for (int j=0;j<4;j++) printf("%s ",dev->config->getQuantity(j).c_str());
451                 printf("\n");
452         }
453         printf("0) Exit Programm\n");
454         std::string inp;
455         int dnr=0;
456         while (1) {
457                 printf("Select device with number: ");std::getline (std::cin,inp);
458                 dnr=atoi(inp.c_str());
459                 if (dnr<=0) return 0;
460                 if (dnr<=i) break; 
461                 printf(C5_B "Select a number between 0 and %i" COLOR_E "\n",i);
462         }
463         return dnr;
464
465 }
466
467 int questionYesNo(std::string text) {
468         std::string inp;
469         printf("%s [Y/n] ",text.c_str());std::getline (std::cin,inp);
470         if (inp=="Y") return 1; else return 0;
471         
472 }
473
474 void interactive(owInterface *owi) {
475         while (1) {
476                 int i=selectDevice();
477                 if (i==0 ) return;
478                 device_menu(owi->devices[i-1]);
479         }
480 }
481
482 int main(int argc, char *argv[]) {
483         int i;
484         arg_t a;
485         //printf("Kommando: %s:\n", argv[0]);
486         while (--argc) {
487                 if (**++argv != '-') {
488         //printf("   Arg. = %s\n", *argv);
489         if (comlist.empty()) {
490                 a.flag=".";
491                 a.arg=*argv;
492                 comlist.push_back(a);
493         } else {
494                 if ((*(comlist.end()-1)).arg!="1") {
495                         a.flag=".";
496                         a.arg=*argv;
497                         comlist.push_back(a);
498                 } else {
499                         (*(comlist.end()-1)).arg=*argv;
500                 }
501         }
502                 } else {
503                         for( i=1; (*argv)[i] != '\0'; i++) {
504                                 //printf("   Flag = (%c)\n", (*argv)[i]);
505                                 a.flag=(*argv)[i];
506                                 a.arg="1";
507                                 comlist.push_back(a);
508                         }
509                 }
510     }          
511
512         //for(arg_t a:comlist) printf("%s->%s\n",a.flag.c_str(),a.arg.c_str());
513         if (getArg("h")=="1") {
514                 printhelp();
515                 return 0;
516         }
517         std::string adapter=getArg("a");
518         if (adapter.empty()) {
519                 printhelp();
520                 return 0;
521         }       
522         std::transform(adapter.begin(), adapter.end(),adapter.begin(), ::toupper);
523
524         std::string s;
525 #ifdef LINUX    
526         if(adapter.find("COM")!=std::string::npos) {
527                 owi=new owCOMInterface();
528                 int port=atoi(adapter.substr(adapter.find("COM")+3).c_str());
529                 printf("Open /dev/ttyUSB%i\n",port);
530                 owi->InitAdapter(port);
531         } else 
532         if(adapter.find("USB")!=std::string::npos) {
533                 owi=new owUSBInterface();
534                 int port=atoi(adapter.substr(adapter.find("USB")+3).c_str());
535                 printf("Open the %i. USB Adapter\n",port);
536                 int err;
537                 if ((err=owi->InitAdapter(port))<0) {
538                         if (err==-1) printf("No Adapter found!\n  On Linux, try: sudo owTools....\n  On Windows: Install libusb0 driver\n");
539                         if (err==-2) printf("Maybe Adapter is used ... (try sudo)\nOn Linux: If the kernel modul is loaded type: sudo rmmod ds2490\n");
540                         exit(0);
541                 }
542         } else 
543         if(adapter.find("GPIO")!=std::string::npos) {
544                 if (findCPU("BCM2708")) {
545                         printf("\033[1;33mRaspberry Pi 1 is dedected. 1-wire on the GPIO port can have many errors in the transfer.\033[0m\n");
546                         owi=new owPiGPioInterface();
547                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
548                         printf("Open GPIO %i\n",port);
549                 } else if (findCPU("BCM2709")) {
550                         owi=new owPiGPioInterface();
551                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
552                         printf("Open GPIO %i\n",port);
553                         owi->InitAdapter(port);
554                 } else {
555                         printf("\033[1;31mGPIO works with Raspberry PI only \033[0m\n");
556                 }
557         }  else
558         if(adapter.find("W1")!=std::string::npos) {
559                 owi=new owW1Interface();
560                 if (owi->InitAdapter(0)) {
561                         printf("Use W1-Kernel 1-Wire functions on /sys/bus/w1\n");
562                 } else printf("No W1-Kernel module found!!\n");
563         } else 
564 #endif
565         if (adapter.find("ARDUINO") != std::string::npos) {
566                 owi = new owARDUINOInterface();
567                 int port = atoi(adapter.substr(adapter.find("ARDUINO") + 7).c_str());
568                 printf("Open /dev/ttyS%i\n", port);
569                 owi->InitAdapter(port);
570         }
571
572 #ifdef WIN
573                 else 
574         if (adapter.find("USB") != std::string::npos) {
575                 printf("USB \n");
576                 owi = new owTMEXWIN();
577                 int port = atoi(adapter.substr(adapter.find("USB") + 3).c_str());
578                 printf("Open the %i. USB Adapter\n", port);
579                 int err;
580                 char cs[20];
581                 sprintf_s(cs, 20, "{%i,6}", port);
582                 if ((err = owi->InitAdapter(cs))==0) {
583                                         printf("ERROR Init USB Adapter\n");
584                                         exit(0);
585                                 }
586                         }
587         else
588                 if (adapter.find("COM") != std::string::npos) {
589                         owi = new owTMEXWIN();
590                         int port = atoi(adapter.substr(adapter.find("COM") + 3).c_str());
591                         printf("Open Adapter on COM%i\n", port);
592                         int err;
593                         char cs[20];
594                         sprintf_s(cs, 20, "{%i,5}", port);
595                         if ((err = owi->InitAdapter(cs))==0) {
596                                 printf("ERROR Init Serial Adapter\n");
597                                 exit(0);
598                         }
599                 }
600 #endif
601         if (owi == NULL) {
602                 printf("No 1-Wiremaster found\n");
603                 return 0;
604         }
605         setLogMode();
606         
607         
608
609         if (getArg("i")=="1") {
610                 interactive(owi);       
611         } else 
612         if (getArg("c")=="1") {
613                 int reload=(getArg("r")=="1");
614                 owi->Find();
615                 printf("\n");
616                 //owi->log->setLogLevel(3);
617                 std::string s;
618                 int pause;
619                 if ((s=getArg("p")) !="") {
620                         pause=atoi(s.c_str());
621                 } else pause=30;
622 #ifdef LINUX
623                 if  ((s=getArg("d")) !="") {
624                         reload=1;
625                         printf("Use Database\n");
626                         sdb=new mySensorDB(s,owi->log);
627                         if (sdb->log->last()>OWLOG_WARNING) {
628                                 exit(1);
629                         }
630                         sdb->connect();
631                         if (sdb->log->last()>OWLOG_WARNING) {
632                                 exit(1);
633                         }
634                         sdb->createSensorTable();
635                         if (sdb->log->last()>OWLOG_WARNING) {
636                                 exit(1);
637                         }                               
638                         database=1;
639                 }
640 #endif
641                 if      ((s=getArg("t")) !="")  {
642                         textfile=1;
643                         printf("Write values to textfile %s\n",s.c_str());
644                         textfilename=s;
645                 }
646                 
647                 continuous(&(owi->devices),pause,1,reload);     
648         } else 
649         if ((s=getArg("f"))!="") {
650                 printf("Flash %s in selected Device\n",s.c_str());
651                 int sel=selectDevice();
652                 if (sel==0) exit(0);
653                 int resetid=questionYesNo("Would you reset to default ID? (This is necessary if another device is used!)");
654                 owi->log->setLogLevel(OWLOG_INFO);              
655                 owi->flashHEXFile(s,owi->device_nums[sel-1],resetid,1);
656                 setLogMode();
657                 owi->Clean();
658                 owi->Find();
659                 for (owDevice* dev :owi->devices) {
660                         snum_t snum=dev->getNum();
661                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
662
663                         printf("\n");
664                 }
665                 printf("%i Devices found\n",(int)owi->devices.size());  
666                                 
667         } else 
668         if ((s=getArg("v"))!="") {
669                 printf("Reset VOC\n");
670                 int sel=selectDevice();
671                 if (sel==0) exit(0);
672                 owDevice* dev=owi->devices[sel-1];
673                 std::vector<uint8_t> cl;
674                 cl.push_back(0x4E);
675                 cl.push_back(0x1F);
676                 cl.push_back(0x1F);
677                 cl.push_back(0x1F);
678                 dev->Communicate(&cl,4,0);
679         } else 
680         //------------------------------------------------------------------------------------------
681         // --------------------- Direct Write
682         //------------------------------------------------------------------------------------------
683         
684         if ((s=getArg("x"))!="") {
685                 std::vector<uint8_t> v;
686                 int sp=0;
687                 std::string ts="";
688                 for ( std::string::iterator  it = s.begin() ; it < s.end(); it++ ,sp++) {
689                         if (isxdigit(*it)) {
690                                 char c=(*it);
691                                 ts.append(1,c);
692                                 if (ts.length()>=2) {
693                                         v.push_back(strtoul(ts.c_str(),NULL, 16));
694                                         ts="";
695                                 }
696                         }
697                 }
698                 if (ts.length()!=0) {
699                         v.push_back(strtoul(ts.c_str(),NULL, 16));
700                 }
701                 printf("Send ");
702                 for (uint8_t val :v) printf("%02X ",val);
703                 printf(" to selected Device\n");
704                 int sel=selectDevice();
705                 if (sel==0) exit(0);
706                 sel-=1;
707                 owDevice* dev=owi->devices[sel];
708                 dev->Communicate(&v,v.size(),0);
709                 for (uint8_t val :v) printf("%02X ",val);
710                 printf("\n");
711                 exit(0);
712                 
713                 
714         }
715
716         //------------------------------------------------------------------------------------------
717         // --------------------- Memory functions
718         //------------------------------------------------------------------------------------------
719         
720         if ((s=getArg("m"))!="") {
721                 int pnr=0;
722                 std::vector<uint8_t> mem;
723                 if(s.find("read")!=std::string::npos) {
724                         size_t cla=s.find_first_of("(",0);
725                         size_t page=s.find_first_of("p=",cla);
726                         size_t epage=s.find_first_of(";",page);
727                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
728                         std::string pn=s.substr(page+2,epage-page-2);
729                         printf("%s Read Memory Page %s of Device:\n",s.c_str(),pn.c_str());
730                         pnr=atoi(pn.c_str());
731
732                 } else 
733                 if(s.find("write")!=std::string::npos) {
734                         size_t cla=s.find("(",0);
735                         size_t page=s.find("p=",cla);
736                         size_t epage=s.find(";",page);
737                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
738                         std::string pn=s.substr(page+2,epage-page-2);
739                         size_t data=s.find("d=",cla);
740                         size_t edata=s.find(";",data);
741                         if (edata==std::string::npos) edata=s.find(")",data);
742                         std::string pd=s.substr(data+2,edata-data-2);
743                         std::istringstream pdss(pd);
744                         //std::cout << pd <<std::endl;
745                         while (!pdss.eof()) {
746                                 int v;
747                                 pdss>>std::hex>>v;
748                                 mem.push_back(v);
749                         }
750                         printf("Write ");
751                         for(uint8_t v :mem) printf("%02X ",v);
752                         printf("to Memory Page %s of Device:\n",pn.c_str());
753                         pnr=atoi(pn.c_str());
754
755                 } else exit(1);
756                 int sel=selectDevice();
757                 if (sel==0) exit(0);
758                 sel-=1;
759                 //snum_t snum=owi->devices[sel]->getNum();
760                 owDevice* dev=owi->devices[sel];
761                 if(s.find("read")!=std::string::npos) {
762                         int r=dev->readMemory(pnr,0,dev->getPageSize(),&mem);
763                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
764                         printf("\n");
765                         exit(0);
766                 } else 
767                 if(s.find("write")!=std::string::npos) {
768                         int r=dev->writeMemory(pnr,0,dev->getPageSize(),&mem);
769                         r=dev->readMemory(pnr,0,dev->getPageSize(),&mem);
770                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
771                         printf("\n");
772                         exit(0);
773                 }
774         }
775         if ((s=getArg("n"))!="") {
776                 printf("Change id of selected Device\n");
777                 int sel=selectDevice();
778                 if (sel==0) exit(0);
779                 sel-=1;
780                 
781                 snum_t snum=owi->devices[sel]->getNum();
782                 
783                 if ((getArg("g"))=="1") {
784                         printf("get ID from Server\n");
785                         char s[255];
786 #ifdef LINUX
787                         sprintf(s,"wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt",snum.byte[0]);
788 #endif
789 #ifdef WIN
790                         sprintf_s(s, "wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt", snum.byte[0]);
791 #endif
792                         int err;
793                         if ((err=system(s))==0) {
794                                 printf("OK!\n");
795                                 std::string rs;
796                                 std::stringstream str;
797                                 std::ifstream fs;
798                                 fs.open ("id.txt" );
799                                 snum_t isnum;
800                                 int i=0; int br=0;
801                                 if(fs.is_open()) {
802                                 while(fs.peek() != EOF) {
803                                         char c= (char) fs.get();
804                                         if (br==0) {
805                                                 if (c=='x') br=1;
806                                         } else {
807                                                 if ((c==',')|(c=='}')) {
808                                                         isnum.byte[i]=(uint8_t)strtoull(s, NULL, 16);
809                                                         //printf("%x\n",strtol(s, NULL, 16));
810                                                         i++;
811                                                         br=0;
812                                                         s[0]=0;
813                                                 } else {
814                                                         s[br-1]=c;
815                                                         s[br]=0;
816                                                         br++;
817                                                 }
818                                         }
819                                         if (c=='}') break;
820                                 }
821                                 
822                                 fs.close();
823                                 }                                         
824                                 snum.num=isnum.num;
825                         } else (printf("ERROR %i\n",err));
826                 } else {
827                         if (s=="1") {
828                                 snum.num+=256;
829                         } else {
830                                 unsigned long long l=strtoull(s.c_str(),NULL,16);
831                                 if ((snum.num&0xFF)!=(l&0xFF)) {
832                                         printf("ERROR: Family of Device 0x%02X->0x%02X can not be changed\n",(int)(snum.num&0xFF),(int)(l&0xFF));
833                                         exit(1);
834                                 }
835                                 snum.num=l;
836                                 //printf("->%016llX\n",(unsigned long long)l);
837                         }
838                         
839                 }
840
841
842                 printf("New ID: ");
843                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
844
845                 printf("\n");
846                 
847                 owi->devices[sel]->changeID(snum);              
848         
849                 owi->Clean();
850                 owi->Find();
851                 for (owDevice* dev :owi->devices) {
852                         snum_t snum=dev->getNum();
853                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
854
855                         printf("\n");
856                 }
857                 printf("%i Devices found\n",(int)owi->devices.size());  
858                                 
859         } else {
860                 owi->Find();
861                 for (owDevice* dev :owi->devices) {
862                         printf("_______________________________________________________________________\n");
863                         snum_t snum=dev->getNum();
864                         printf(BLUE_B "%016llX " COLOR_E,(unsigned long long)snum.num);
865                         switch (dev->configstate) {
866                                 case OWDCS_16:printf("old Configcode from www.tm3d.de");break;
867                                 case OWDCS_24:printf("Configcode from www.tm3d.de");break;
868                                 case OWDCS_DEFAULT:printf("Default Configcode set by this Software");break;
869                                 case OWDCS_NONE:printf("No Configcode");break;
870                         }
871                         printf( " - (");
872                         for(int i=0;i<3;i++)
873                                 printf(" %s",dev->getFamilyInfo()[i].c_str());
874                         printf(" )\n");
875                         if (dev->configstate!=OWDCS_NONE) {
876                                 std::vector<std::vector<std::string>> ia;
877                                 std::vector<size_t> maxcol;
878                                 dev->convertAll();
879                                 for(int i=0;i<4;i++) {
880                                         std::vector<std::string> colm;
881                                         size_t max=0;
882                                         colm.push_back(dev->config->getSensorChip(i));
883                                         if (max<utf8_length(colm[0])) max=utf8_length(colm[0]);
884                                         colm.push_back(dev->config->getQuantity(i));
885                                         if (max<utf8_length(colm[1])) max=utf8_length(colm[1]);
886                                         colm.push_back(dev->config->getUnit(i));
887                                         if (max<utf8_length(colm[2])) max=utf8_length(colm[2]);
888                                         if (dev->config->getPropertyID(i)==0) {
889                                                 colm.push_back("");
890                                         } else {
891                                                 char hs[50];
892 #ifdef LINUX
893                                                 sprintf(hs,"%0.3f",dev->values[i]);
894 #endif
895 #ifdef WIN
896                                                 sprintf_s(hs, "%0.3f", dev->values[i]);
897 #endif
898                                                 colm.push_back(hs);
899                                         }
900                                         if (max<utf8_length(colm[3])) max=utf8_length(colm[3]);
901                                         ia.push_back(colm);
902                                         maxcol.push_back(max);
903                                 }
904                                 std::string space="                                                          ";
905                                 for(int i=0;i<4;i++) {
906                                         for(int j=0;j<4;j++) {
907                                                 printf("%s%s",ia[j][i].c_str(),space.substr(0,maxcol[j]-utf8_length(ia[j][i])+2).c_str());
908                                         }
909                                         printf("\n");
910                                 }
911                         }
912                 }
913                 printf("%i Devices found\n",(int)owi->devices.size());
914         }
915         return 0;
916    
917 }