New Devices
[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 =======
327                                 std::vector<uint8_t> data;
328                                 data.push_back(0xCC);
329                                 data.push_back(0x44);
330                                 owi->Reset();
331                                 owi->Communicate(&data, 2, 0);
332 >>>>>>> origin/master
333                                 dev->convertAll();
334                                 if (owi->log->last()<OWLOG_ERROR) break;
335                                 owi->log->clear();
336                         }
337                         if (owi->log->last()<OWLOG_ERROR) {
338                                 if (dev->configstate!=OWDCS_NONE) {
339                                         for (size_t i=0;i<4;i++) {                                      
340                                                 if (dev->config->getPropertyID((int8_t)i)!=0) {
341                                                         if (dev->values[i]<=-10) 
342                                                                 printf("%0.2f \t",dev->values[i]);
343                                                         else if (dev->values[i]<0) 
344                                                                 printf("%0.3f \t",dev->values[i]);
345                                                         else if (dev->values[i]<10) 
346                                                                 printf("%0.4f \t",dev->values[i]);
347                                                         else if (dev->values[i]<100)    
348                                                                 printf("%0.3f \t",dev->values[i]);
349                                                         else if (dev->values[i]<1000)   
350                                                                 printf("%0.2f \t",dev->values[i]);
351                                                         else
352                                                                 printf("%0.1f \t",dev->values[i]);
353                                                         fflush(stdout);
354                                                         if (textfile) {
355                                                                 snprintf(valbuf,100,",%0.4f",dev->values[i]);
356                                                                 tfl.append(valbuf);
357                                                         }
358                                                 }
359                                         }
360                                 }
361 #ifdef LINUX
362                                 if (database) {
363                                         sdb->insertValues(dev);
364                                 }
365 #endif
366                         } else {
367                                 owi->log->setLogLevel(OWLOG_INFO);
368                                 owi->log->set(OWLOG_ERROR,"Too many errors, mybee conection is dead.");
369                                 return;
370                         }
371                         
372                 
373                 }
374                 printf("\n");
375                 if (textfile) {
376                         appendTextFile(tfl);
377                 }
378                 while (((int)time(NULL)) < (st + intervall)) {
379 #ifdef LINUX
380                         sleep(1);
381 #endif
382 #ifdef WIN
383                         Sleep(1000);
384 #endif          
385                 }
386         }
387 }
388
389 void device_menu(owDevice* d) {
390         for(int i=0;i<70;i++) printf(HL);printf("\n");
391         printf("Selected Device: ");
392         snum_t snum=d->getNum();
393         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
394         printf("  \n");
395         printf("Chip Info: ");
396         std::vector<std::string> info=d->getFamilyInfo();
397         for (std::string s : info) printf(" %s",s.c_str());
398         printf("\n");
399         printf("Values info: ");
400         int tm3d=d->readConfig();
401         for (size_t i=0;i<4;i++) {
402                 printf("%s in %s",d->config->getQuantity((uint8_t)i).c_str(),d->config->getUnit((uint8_t)i).c_str());
403                 if (i<4) printf("; "); 
404         }
405         if (tm3d) printf(" (tm3d.de)"); else printf(" (default)"); 
406         printf("\n");
407         d->convertAll();
408         for (size_t i=0;i<d->values.size();i++) {
409                 printf(C4_B "%0.4f %s" COLOR_E,d->values[i],d->config->getUnit((uint8_t)i).c_str());
410         }
411         printf("\n");
412         for(int i=0;i<70;i++) printf(HL);printf("\n");
413         printf("0) Exit\n");
414         printf("1) Run continuous\n");
415         std::string inp;
416         while (1) {
417                 printf("Select an option: ");std::getline (std::cin,inp);
418                 int dnr=atoi(inp.c_str());
419                 if (dnr<=0) return;
420                 if (dnr==1) {
421                         std::vector<owDevice*> v;
422                         v.push_back(d);
423                         continuous(&v,1,1,0);
424                 } 
425 //                      if (dnr<=i) break; 
426         //              printf("\033[4;33mSelect a number between 0 and %i\033[0m\n",i);
427         }
428         
429         
430 }
431
432 int selectDevice() {
433         std::string s;
434         owi->Find();
435         int i = 0;
436         char *end;
437         unsigned long long l = 0;
438         if ((s = getArg("s")) != "") {
439                 l = strtoull(s.c_str(), &end, 16);
440                 for (owDevice* dev : owi->devices) {
441                         i++;
442                         snum_t snum = dev->getNum();
443                         if (l == snum.num) return i;
444
445                 }
446                 printf("Number not found -> Select one or exit!\n");
447         }
448
449         i=0;
450         for (owDevice* dev :owi->devices) {
451                 i++;
452                 snum_t snum=dev->getNum();
453                 printf("%i) ",i);
454                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
455
456                 printf("  ");
457                 for (int j=0;j<4;j++) printf("%s ",dev->config->getQuantity(j).c_str());
458                 printf("\n");
459         }
460         printf("0) Exit Programm\n");
461         std::string inp;
462         int dnr=0;
463         while (1) {
464                 printf("Select device with number: ");std::getline (std::cin,inp);
465                 dnr=atoi(inp.c_str());
466                 if (dnr<=0) return 0;
467                 if (dnr<=i) break; 
468                 printf(C5_B "Select a number between 0 and %i" COLOR_E "\n",i);
469         }
470         return dnr;
471
472 }
473
474 int questionYesNo(std::string text) {
475         std::string inp;
476         printf("%s [Y/n] ",text.c_str());std::getline (std::cin,inp);
477         if (inp=="Y") return 1; else return 0;
478         
479 }
480
481 void interactive(owInterface *owi) {
482         while (1) {
483                 int i=selectDevice();
484                 if (i==0 ) return;
485                 device_menu(owi->devices[i-1]);
486         }
487 }
488
489 int main(int argc, char *argv[]) {
490         int i;
491         arg_t a;
492         //printf("Kommando: %s:\n", argv[0]);
493         while (--argc) {
494                 if (**++argv != '-') {
495         //printf("   Arg. = %s\n", *argv);
496         if (comlist.empty()) {
497                 a.flag=".";
498                 a.arg=*argv;
499                 comlist.push_back(a);
500         } else {
501                 if ((*(comlist.end()-1)).arg!="1") {
502                         a.flag=".";
503                         a.arg=*argv;
504                         comlist.push_back(a);
505                 } else {
506                         (*(comlist.end()-1)).arg=*argv;
507                 }
508         }
509                 } else {
510                         for( i=1; (*argv)[i] != '\0'; i++) {
511                                 //printf("   Flag = (%c)\n", (*argv)[i]);
512                                 a.flag=(*argv)[i];
513                                 a.arg="1";
514                                 comlist.push_back(a);
515                         }
516                 }
517     }          
518
519         //for(arg_t a:comlist) printf("%s->%s\n",a.flag.c_str(),a.arg.c_str());
520         if (getArg("h")=="1") {
521                 printhelp();
522                 return 0;
523         }
524         std::string adapter=getArg("a");
525         if (adapter.empty()) {
526                 printhelp();
527                 return 0;
528         }       
529         std::transform(adapter.begin(), adapter.end(),adapter.begin(), ::toupper);
530
531         std::string s;
532 #ifdef LINUX    
533         if(adapter.find("COM")!=std::string::npos) {
534                 owi=new owCOMInterface();
535                 int port=atoi(adapter.substr(adapter.find("COM")+3).c_str());
536                 printf("Open /dev/ttyUSB%i\n",port);
537                 owi->InitAdapter(port);
538         } else 
539         if(adapter.find("USB")!=std::string::npos) {
540                 owi=new owUSBInterface();
541                 int port=atoi(adapter.substr(adapter.find("USB")+3).c_str());
542                 printf("Open the %i. USB Adapter\n",port);
543                 int err;
544                 if ((err=owi->InitAdapter(port))<0) {
545                         if (err==-1) printf("No Adapter found!\n  On Linux, try: sudo owTools....\n  On Windows: Install libusb0 driver\n");
546                         if (err==-2) printf("Maybe Adapter is used ... (try sudo)\nOn Linux: If the kernel modul is loaded type: sudo rmmod ds2490\n");
547                         exit(0);
548                 }
549         } else 
550         if(adapter.find("GPIO")!=std::string::npos) {
551                 if (findCPU("BCM2708")) {
552                         printf("\033[1;33mRaspberry Pi 1 is dedected. 1-wire on the GPIO port can have many errors in the transfer.\033[0m\n");
553                         owi=new owPiGPioInterface();
554                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
555                         printf("Open GPIO %i\n",port);
556                 } else if (findCPU("BCM2709")) {
557                         owi=new owPiGPioInterface();
558                         int port=atoi(adapter.substr(adapter.find("GPIO")+4).c_str());
559                         printf("Open GPIO %i\n",port);
560                         owi->InitAdapter(port);
561                 } else {
562                         printf("\033[1;31mGPIO works with Raspberry PI only \033[0m\n");
563                 }
564         }  else
565         if(adapter.find("W1")!=std::string::npos) {
566                 owi=new owW1Interface();
567                 if (owi->InitAdapter(0)) {
568                         printf("Use W1-Kernel 1-Wire functions on /sys/bus/w1\n");
569                 } else printf("No W1-Kernel module found!!\n");
570         } else 
571 #endif
572         if (adapter.find("ARDUINO") != std::string::npos) {
573                 owi = new owARDUINOInterface();
574                 int port = atoi(adapter.substr(adapter.find("ARDUINO") + 7).c_str());
575                 printf("Open /dev/ttyS%i\n", port);
576                 owi->InitAdapter(port);
577         }
578
579 #ifdef WIN
580                 else 
581         if (adapter.find("USB") != std::string::npos) {
582                 printf("USB \n");
583                 owi = new owTMEXWIN();
584                 int port = atoi(adapter.substr(adapter.find("USB") + 3).c_str());
585                 printf("Open the %i. USB Adapter\n", port);
586                 int err;
587                 char cs[20];
588                 sprintf_s(cs, 20, "{%i,6}", port);
589                 if ((err = owi->InitAdapter(cs))==0) {
590                                         printf("ERROR Init USB Adapter\n");
591                                         exit(0);
592                                 }
593                         }
594         else
595                 if (adapter.find("COM") != std::string::npos) {
596                         owi = new owTMEXWIN();
597                         int port = atoi(adapter.substr(adapter.find("COM") + 3).c_str());
598                         printf("Open Adapter on COM%i\n", port);
599                         int err;
600                         char cs[20];
601                         sprintf_s(cs, 20, "{%i,5}", port);
602                         if ((err = owi->InitAdapter(cs))==0) {
603                                 printf("ERROR Init Serial Adapter\n");
604                                 exit(0);
605                         }
606                 }
607 #endif
608         if (owi == NULL) {
609                 printf("No 1-Wiremaster found\n");
610                 return 0;
611         }
612         setLogMode();
613         
614         
615
616         if (getArg("i")=="1") {
617                 interactive(owi);       
618         } else 
619         if (getArg("c")=="1") {
620                 int reload=(getArg("r")=="1");
621                 owi->Find();
622                 printf("\n");
623                 //owi->log->setLogLevel(3);
624                 std::string s;
625                 int pause;
626                 if ((s=getArg("p")) !="") {
627                         pause=atoi(s.c_str());
628                 } else pause=30;
629 #ifdef LINUX
630                 if  ((s=getArg("d")) !="") {
631                         reload=1;
632                         printf("Use Database\n");
633                         sdb=new mySensorDB(s,owi->log);
634                         if (sdb->log->last()>OWLOG_WARNING) {
635                                 exit(1);
636                         }
637                         sdb->connect();
638                         if (sdb->log->last()>OWLOG_WARNING) {
639                                 exit(1);
640                         }
641                         sdb->createSensorTable();
642                         if (sdb->log->last()>OWLOG_WARNING) {
643                                 exit(1);
644                         }                               
645                         database=1;
646                 }
647 #endif
648 <<<<<<< HEAD
649                 if      ((s=getArg("t")) !="")  {
650                         textfile=1;
651                         printf("Write values to textfile %s\n",s.c_str());
652                         textfilename=s;
653                 }
654 =======
655                         
656 >>>>>>> origin/master
657                 
658                 continuous(&(owi->devices),pause,1,reload);     
659         } else 
660         if ((s=getArg("f"))!="") {
661                 printf("Flash %s in selected Device\n",s.c_str());
662                 int sel=selectDevice();
663                 if (sel==0) exit(0);
664                 int resetid=questionYesNo("Would you reset to default ID? (This is necessary if another device is used!)");
665                 owi->log->setLogLevel(OWLOG_INFO);              
666                 owi->flashHEXFile(s,owi->device_nums[sel-1],resetid,1);
667                 setLogMode();
668                 owi->Clean();
669                 owi->Find();
670                 for (owDevice* dev :owi->devices) {
671                         snum_t snum=dev->getNum();
672                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
673
674                         printf("\n");
675                 }
676                 printf("%i Devices found\n",(int)owi->devices.size());  
677                                 
678         } else 
679         if ((s=getArg("v"))!="") {
680                 printf("Reset VOC\n");
681                 int sel=selectDevice();
682                 if (sel==0) exit(0);
683                 owDevice* dev=owi->devices[sel-1];
684                 std::vector<uint8_t> cl;
685                 cl.push_back(0x4E);
686                 cl.push_back(0x1F);
687                 cl.push_back(0x1F);
688                 cl.push_back(0x1F);
689                 dev->Communicate(&cl,4,0);
690         } else 
691         //------------------------------------------------------------------------------------------
692         // --------------------- Direct Write
693         //------------------------------------------------------------------------------------------
694         
695         if ((s=getArg("x"))!="") {
696                 std::vector<uint8_t> v;
697                 int sp=0;
698                 std::string ts="";
699                 for ( std::string::iterator  it = s.begin() ; it < s.end(); it++ ,sp++) {
700                         if (isxdigit(*it)) {
701                                 char c=(*it);
702                                 ts.append(1,c);
703                                 if (ts.length()>=2) {
704                                         v.push_back(strtoul(ts.c_str(),NULL, 16));
705                                         ts="";
706                                 }
707                         }
708                 }
709                 if (ts.length()!=0) {
710                         v.push_back(strtoul(ts.c_str(),NULL, 16));
711                 }
712                 printf("Send ");
713                 for (uint8_t val :v) printf("%02X ",val);
714                 printf(" to selected Device\n");
715                 int sel=selectDevice();
716                 if (sel==0) exit(0);
717                 sel-=1;
718                 owDevice* dev=owi->devices[sel];
719                 dev->Communicate(&v,v.size(),0);
720                 for (uint8_t val :v) printf("%02X ",val);
721                 printf("\n");
722                 exit(0);
723                 
724                 
725         }
726
727         //------------------------------------------------------------------------------------------
728         // --------------------- Memory functions
729         //------------------------------------------------------------------------------------------
730         
731 =======
732         // --------------------- Memory functions
733         //------------------------------------------------------------------------------------------
734         
735 >>>>>>> origin/master
736         if ((s=getArg("m"))!="") {
737                 int pnr=0;
738                 std::vector<uint8_t> mem;
739                 if(s.find("read")!=std::string::npos) {
740                         size_t cla=s.find_first_of("(",0);
741                         size_t page=s.find_first_of("p=",cla);
742                         size_t epage=s.find_first_of(";",page);
743                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
744                         std::string pn=s.substr(page+2,epage-page-2);
745                         printf("%s Read Memory Page %s of Device:\n",s.c_str(),pn.c_str());
746                         pnr=atoi(pn.c_str());
747
748                 } else 
749                 if(s.find("write")!=std::string::npos) {
750                         size_t cla=s.find("(",0);
751                         size_t page=s.find("p=",cla);
752                         size_t epage=s.find(";",page);
753                         if (epage==std::string::npos) epage=s.find_first_of(")",page);
754                         std::string pn=s.substr(page+2,epage-page-2);
755                         size_t data=s.find("d=",cla);
756                         size_t edata=s.find(";",data);
757                         if (edata==std::string::npos) edata=s.find(")",data);
758                         std::string pd=s.substr(data+2,edata-data-2);
759                         std::istringstream pdss(pd);
760                         //std::cout << pd <<std::endl;
761                         while (!pdss.eof()) {
762                                 int v;
763                                 pdss>>std::hex>>v;
764                                 mem.push_back(v);
765                         }
766                         printf("Write ");
767                         for(uint8_t v :mem) printf("%02X ",v);
768                         printf("to Memory Page %s of Device:\n",pn.c_str());
769                         pnr=atoi(pn.c_str());
770
771                 } else exit(1);
772                 int sel=selectDevice();
773                 if (sel==0) exit(0);
774                 sel-=1;
775                 //snum_t snum=owi->devices[sel]->getNum();
776                 owDevice* dev=owi->devices[sel];
777                 if(s.find("read")!=std::string::npos) {
778                         int r=dev->readMemory(pnr,0,dev->getPageSize(),&mem);
779                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
780                         printf("\n");
781                         exit(0);
782                 } else 
783                 if(s.find("write")!=std::string::npos) {
784                         int r=dev->writeMemory(pnr,0,dev->getPageSize(),&mem);
785                         r=dev->readMemory(pnr,0,dev->getPageSize(),&mem);
786                         for(int i=0;i<r;i++) printf("%02X ",mem[i]);
787                         printf("\n");
788                         exit(0);
789                 }
790         }
791         if ((s=getArg("n"))!="") {
792                 printf("Change id of selected Device\n");
793                 int sel=selectDevice();
794                 if (sel==0) exit(0);
795                 sel-=1;
796                 
797                 snum_t snum=owi->devices[sel]->getNum();
798                 
799                 if ((getArg("g"))=="1") {
800                         printf("get ID from Server\n");
801                         char s[255];
802 #ifdef LINUX
803                         sprintf(s,"wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt",snum.byte[0]);
804 #endif
805 #ifdef WIN
806                         sprintf_s(s, "wget -q http://www.tm3d.de/shop99/owid.php?fam=%02X -O id.txt", snum.byte[0]);
807 #endif
808                         int err;
809                         if ((err=system(s))==0) {
810                                 printf("OK!\n");
811                                 std::string rs;
812                                 std::stringstream str;
813                                 std::ifstream fs;
814                                 fs.open ("id.txt" );
815                                 snum_t isnum;
816                                 int i=0; int br=0;
817                                 if(fs.is_open()) {
818                                 while(fs.peek() != EOF) {
819                                         char c= (char) fs.get();
820                                         if (br==0) {
821                                                 if (c=='x') br=1;
822                                         } else {
823                                                 if ((c==',')|(c=='}')) {
824 <<<<<<< HEAD
825                                                         isnum.byte[i]=(uint8_t)strtoull(s, NULL, 16);
826 =======
827                                                         isnum.byte[i]=(uint8_t)strtol(s, NULL, 16);
828 >>>>>>> origin/master
829                                                         //printf("%x\n",strtol(s, NULL, 16));
830                                                         i++;
831                                                         br=0;
832                                                         s[0]=0;
833                                                 } else {
834                                                         s[br-1]=c;
835                                                         s[br]=0;
836                                                         br++;
837                                                 }
838                                         }
839                                         if (c=='}') break;
840                                 }
841                                 
842                                 fs.close();
843                                 }                                         
844                                 snum.num=isnum.num;
845                         } else (printf("ERROR %i\n",err));
846                 } else {
847                         if (s=="1") {
848                                 snum.num+=256;
849                         } else {
850 <<<<<<< HEAD
851                                 unsigned long long l=strtoull(s.c_str(),NULL,16);
852 =======
853                                 unsigned long long l=strtol(s.c_str(),NULL,16);
854 >>>>>>> origin/master
855                                 if ((snum.num&0xFF)!=(l&0xFF)) {
856                                         printf("ERROR: Family of Device 0x%02X->0x%02X can not be changed\n",(int)(snum.num&0xFF),(int)(l&0xFF));
857                                         exit(1);
858                                 }
859                                 snum.num=l;
860                                 //printf("->%016llX\n",(unsigned long long)l);
861                         }
862                         
863                 }
864
865
866                 printf("New ID: ");
867                 printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
868
869                 printf("\n");
870                 
871                 owi->devices[sel]->changeID(snum);              
872         
873                 owi->Clean();
874                 owi->Find();
875                 for (owDevice* dev :owi->devices) {
876                         snum_t snum=dev->getNum();
877                         printf(BLUE_B "%016llX" COLOR_E,(unsigned long long)snum.num);
878
879                         printf("\n");
880                 }
881                 printf("%i Devices found\n",(int)owi->devices.size());  
882                                 
883         } else {
884                 owi->Find();
885                 for (owDevice* dev :owi->devices) {
886                         printf("_______________________________________________________________________\n");
887                         snum_t snum=dev->getNum();
888                         printf(BLUE_B "%016llX " COLOR_E,(unsigned long long)snum.num);
889                         switch (dev->configstate) {
890                                 case OWDCS_16:printf("old Configcode from www.tm3d.de");break;
891                                 case OWDCS_24:printf("Configcode from www.tm3d.de");break;
892                                 case OWDCS_DEFAULT:printf("Default Configcode set by this Software");break;
893                                 case OWDCS_NONE:printf("No Configcode");break;
894                         }
895                         printf( " - (");
896                         for(int i=0;i<3;i++)
897                                 printf(" %s",dev->getFamilyInfo()[i].c_str());
898                         printf(" )\n");
899                         if (dev->configstate!=OWDCS_NONE) {
900                                 std::vector<std::vector<std::string>> ia;
901                                 std::vector<size_t> maxcol;
902                                 dev->convertAll();
903                                 for(int i=0;i<4;i++) {
904                                         std::vector<std::string> colm;
905                                         size_t max=0;
906                                         colm.push_back(dev->config->getSensorChip(i));
907                                         if (max<utf8_length(colm[0])) max=utf8_length(colm[0]);
908                                         colm.push_back(dev->config->getQuantity(i));
909                                         if (max<utf8_length(colm[1])) max=utf8_length(colm[1]);
910                                         colm.push_back(dev->config->getUnit(i));
911                                         if (max<utf8_length(colm[2])) max=utf8_length(colm[2]);
912                                         if (dev->config->getPropertyID(i)==0) {
913                                                 colm.push_back("");
914                                         } else {
915                                                 char hs[50];
916 #ifdef LINUX
917                                                 sprintf(hs,"%0.3f",dev->values[i]);
918 #endif
919 #ifdef WIN
920                                                 sprintf_s(hs, "%0.3f", dev->values[i]);
921 #endif
922                                                 colm.push_back(hs);
923                                         }
924                                         if (max<utf8_length(colm[3])) max=utf8_length(colm[3]);
925                                         ia.push_back(colm);
926                                         maxcol.push_back(max);
927                                 }
928                                 std::string space="                                                          ";
929                                 for(int i=0;i<4;i++) {
930                                         for(int j=0;j<4;j++) {
931                                                 printf("%s%s",ia[j][i].c_str(),space.substr(0,maxcol[j]-utf8_length(ia[j][i])+2).c_str());
932                                         }
933                                         printf("\n");
934                                 }
935                         }
936                 }
937                 printf("%i Devices found\n",(int)owi->devices.size());
938         }
939         return 0;
940    
941 }