/[H9]/trunk/FlisServer/FlisServerDlg.cpp
ViewVC logotype

Diff of /trunk/FlisServer/FlisServerDlg.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 70 by kevin, Tue Nov 27 15:26:42 2007 UTC revision 297 by torben, Mon Dec 17 15:05:06 2007 UTC
# Line 4  Line 4 
4  #include "stdafx.h"  #include "stdafx.h"
5  #include "FlisServer.h"  #include "FlisServer.h"
6  #include "FlisServerDlg.h"  #include "FlisServerDlg.h"
 #include ".\flisserverdlg.h"  
7  #include <vector>  #include <vector>
8    #include ".\flisserverdlg.h"
9    #include <atlrx.h>
10    
11  #ifdef _DEBUG  #ifdef _DEBUG
12  #define new DEBUG_NEW  #define new DEBUG_NEW
# Line 64  BEGIN_MESSAGE_MAP(CFlisServerDlg, CDialo Line 65  BEGIN_MESSAGE_MAP(CFlisServerDlg, CDialo
65          ON_WM_PAINT()          ON_WM_PAINT()
66          ON_WM_QUERYDRAGICON()          ON_WM_QUERYDRAGICON()
67          //}}AFX_MSG_MAP          //}}AFX_MSG_MAP
68          ON_BN_CLICKED(IDOK, OnBnClickedOk)          ON_BN_CLICKED(IDCLOSE, OnBnClickedClose)
69          ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel)          ON_BN_CLICKED(IDC_Start, OnBnClickedStart)
         ON_BN_CLICKED(IDC_test, OnBnClickedtest)  
70  END_MESSAGE_MAP()  END_MESSAGE_MAP()
71    
72    
# Line 101  BOOL CFlisServerDlg::OnInitDialog() Line 101  BOOL CFlisServerDlg::OnInitDialog()
101    
102          // TODO: Add extra initialization here          // TODO: Add extra initialization here
103          StartSerial();          StartSerial();
104          SetPin();          DBConnect();
105            ResetSms = 0;
106                    
107          return TRUE;  // return TRUE  unless you set the focus to a control          return TRUE;  // return TRUE  unless you set the focus to a control
108  }  }
# Line 156  HCURSOR CFlisServerDlg::OnQueryDragIcon( Line 157  HCURSOR CFlisServerDlg::OnQueryDragIcon(
157  }  }
158  int CFlisServerDlg::StartSerial(void)  int CFlisServerDlg::StartSerial(void)
159  {  {
160            
161          int Baud;          int Baud;
         CString SerialPort = "COM3";  
162    
163            ConfigFile config;
164            try {
165                    config.ReadSettings();
166            } catch(...) {
167                    MessageBox("Could not open config file");
168                    OnOK();
169                    return true;
170            }
171            
172          Baud = 1200;          Baud = 1200;
173          if( Serial.isOpen() ){          if( Serial.isOpen() )
174                  Serial.close();          {
175                  Serial.open( SerialPort, Baud );                  try
176                    {
177                            Serial.close();
178                            Serial.open( config.comport, Baud );
179                    }
180                    catch (...)
181                    {
182                            MessageBox( "Serial.open() exception" );
183                            return 0;
184                    }
185          }          }
186          else {          else
187                  Serial.open( SerialPort, Baud );          {
188                    try
189                    {
190                            Serial.open( config.comport, Baud );
191                    }
192                    catch (...)
193                    {
194                            MessageBox( "Serial.open() exception 2" );
195                            return 0;
196                    }
197          }          }
198            
199                                    
200  return 0;  return 0;
201  }  }
# Line 176  std::vector<unsigned char> CFlisServerDl Line 204  std::vector<unsigned char> CFlisServerDl
204          std::vector<unsigned char> buf;          std::vector<unsigned char> buf;
205          while(Serial.getComstat().cbInQue > 0)          while(Serial.getComstat().cbInQue > 0)
206          {          {
207          unsigned char data = Serial.readByte();                  unsigned char data = Serial.readByte();
208    
209          buf.push_back(data);                  buf.push_back(data);
210          }          }
211          return buf;          return buf;
212  }  }
 void CFlisServerDlg::OnBnClickedOk()  
 {  
         // TODO: Add your control notification handler code here  
         OnOK();  
         if( Serial.isOpen() ){  
                 Serial.close();  
         }  
 }  
213    
214  void CFlisServerDlg::OnBnClickedCancel()  void CFlisServerDlg::writeFrame(std::vector<unsigned char> data)
215  {  {
216          // TODO: Add your control notification handler code here          for (int i=0; i<data.size(); i++)
217          OnCancel();          {
218          if( Serial.isOpen() ){                  Serial.writeByte( data[i] );
219                  Serial.close();                  Sleep(5);
220          }          }
221  }          Serial.writeByte(0x0D);
222            Sleep(100);
223    
224  void CFlisServerDlg::OnBnClickedtest()  }
225    void CFlisServerDlg::SetPin()
226  {  {
227          // TODO: Add your control notification handler code here          bool ready = true;
228          /*          CString tekst;
229          std::vector<unsigned char> data;          std::vector<unsigned char> data;
230    
231          data.push_back('a');          data.push_back('a');
232          data.push_back('t');          data.push_back('t');
233            data.push_back('+');
234            data.push_back('c');
235            data.push_back('p');
236            data.push_back('i');
237            data.push_back('n');
238            data.push_back('?');
239    
240          writeFrame(data);          writeFrame(data);
241            Sleep(100);
242          if(Serial.getComstat().cbInQue > 0)          if(Serial.getComstat().cbInQue > 0)
243          {          {
244          std::vector<unsigned char> answer = readFrame();                  std::vector<unsigned char> answer = readFrame();
245          Sleep(50);                  Sleep(50);
246          if (answer.size() == 0){  
                 m_Textwindow.SetWindowText("ØV");  
         }  
         else{  
                 CString ko;  
                 char test[150];  
                 int i;  
247                  for (int i=0; i<answer.size(); i++)                  for (int i=0; i<answer.size(); i++)
248                            {
249                                    if ((answer[i] != 0x0A) && (answer[i] != 0x0D))
250                                    {
251                                            tekst.AppendChar(answer[i]);
252                                    }
253                            }
254                            AppendText(tekst);
255            }
256            Sleep(5);
257            tekst.MakeLower();
258            int pos = tekst.Find("+cpin: ",0);
259            if (pos != -1)
260            {
261                    tekst = tekst.Right( tekst.GetLength() - pos -1);
262            }
263    
264            if (tekst == "cpin: sim pin")
265            {
266                    CString pin;
267                    ConfigFile config;
268                    try {
269                            config.ReadSettings();
270                    } catch(...) {
271                            MessageBox("Could not open config file");
272                    }
273                    Sleep(50);
274    
275                    data.clear();
276                    data.push_back('a');
277                    data.push_back('t');
278                    data.push_back('+');
279                    data.push_back('c');
280                    data.push_back('p');
281                    data.push_back('i');
282                    data.push_back('n');
283                    data.push_back('=');
284                    for (int i = 0; i<config.pincode.GetLength(); i++)
285                  {                  {
286                          test[i] = answer[i];                  data.push_back(config.pincode[i]);
287                    }
288    
289                    writeFrame(data);
290    
291                    Sleep(500);
292    
293                    while (ready == true)
294                    {
295                            if (Serial.getComstat().cbInQue > 120)
296                            {
297                                    std::vector<unsigned char> answer = readFrame();
298                                    CString tekst;
299                            
300                                    for (int i=0; i<answer.size(); i++)
301                                    {
302                                            if ((answer[i] != 0x0A) && (answer[i] != 0x0D))
303                                            {
304                                                    tekst.AppendChar(answer[i]);
305                                            }
306                                    }
307                                    int n = tekst.Find("WIND: 11",0);
308                                    if (n > -1)
309                                    {
310                                            ready = false;
311                                    }
312                                    else
313                                    {
314                                            AppendText(tekst);
315                                    }
316                            }
317                            Sleep(10); //Small delay to avoid busy wait
318                  }                  }
                 ko = test;  
                 m_Textwindow.SetWindowText(ko);  
319          }          }
320            else if (tekst == "cpin: ready")
321            {
322                    AppendText("No pincode needed");
323            }
324            else
325            {
326                    AppendText("Error in set pin part of the code");
327          }          }
         */  
         SetPin();  
328  }  }
329  void CFlisServerDlg::writeFrame(std::vector<unsigned char> data)  void CFlisServerDlg::SendSmsData(std::vector<unsigned char> data)
330  {  {      
331            
332          for (int i=0; i<data.size(); i++)          for (int i=0; i<data.size(); i++)
333          {          {
334                  Serial.writeByte( data[i] );                  Serial.writeByte( data[i] );
335                  Sleep(5);                  Sleep(5);
336          }          }
337          Serial.writeByte(0x0D);          Serial.writeByte(0x1A);
338          Sleep(100);          Sleep(3000);
339            if(Serial.getComstat().cbInQue > 0)
340            {
341                    CString tekst;
342                    std::vector<unsigned char> answer = readFrame();
343                    Sleep(50);
344    
345                    for (int i=0; i<answer.size(); i++)
346                            {
347                                    if ((answer[i] != 0x0A) && (answer[i] != 0x0D))
348                                    {
349                                            tekst.AppendChar(answer[i]);
350                                    }
351                            }
352                            AppendText(tekst);
353            }
354    
355  }  }
356  int CFlisServerDlg::SetPin(void)  void CFlisServerDlg::SendSmsHead(std::vector<unsigned char> tlfnr)
357  {  {
358          CString tekst, oldtekst;          vector<unsigned char> atcommand;
359          std::vector<unsigned char> data;          atcommand.push_back('a');
360          data.push_back('a');          atcommand.push_back('t');
361          data.push_back('t');          atcommand.push_back('+');
362          data.push_back('+');          atcommand.push_back('c');
363          data.push_back('c');          atcommand.push_back('m');
364          data.push_back('p');          atcommand.push_back('g');
365          data.push_back('i');          atcommand.push_back('s');
366          data.push_back('n');          atcommand.push_back('=');
367          data.push_back('=');          atcommand.push_back('"');
368          data.push_back('2');          int s = (atcommand.size() -1 );
369          data.push_back('5');          
370          data.push_back('9');          for (int i=0; i<(atcommand.size()); i++)
371          data.push_back('5');          {
372                    Serial.writeByte( atcommand[i] );
373                    Sleep(5);
374            }
375            
376            for (int i=0; i<tlfnr.size(); i++)
377            {
378                    Serial.writeByte( tlfnr[i] );
379                    Sleep(5);
380            }
381            Serial.writeByte(atcommand[s]);
382            Serial.writeByte(0x0D);
383            Sleep(250);
384    }
385    void CFlisServerDlg::DBConnect()
386    {
387            CString dsn;
388            ConfigFile config;
389            try {
390                    config.ReadSettings();
391            } catch(...) {
392                    MessageBox("Could not open config file");
393            }
394            
395            dsn.Format("ODBC;Description=asd;DRIVER=PostgreSQL ANSI;SERVER=%s; uid=%s;password=%s;database=%s;sslmode=prefer",config.host,config.username, config.password, config.database);
396            db.OpenEx(dsn, CDatabase::noOdbcDialog);
397    }
398    vector<Commands> CFlisServerDlg::DBReadCommands(void)
399    {
400            vector<Commands> buffer;
401    
402          writeFrame(data);          CString SQL, IDnr, CommandID, InstallationsID;
403          Sleep(750);          SQL = "select id,date_trunc('second', created) as created,executed,commandid,installationid from command WHERE executed IS NULL ORDER BY created ASC LIMIT 1;";
404            CRecordset rs(&db);
405            rs.Open(AFX_DB_USE_DEFAULT_TYPE, SQL);
406            if (rs.GetRecordCount()>0)
407            {
408                    rs.MoveFirst();
409                            
410                    Commands Mycom;
411                    rs.GetFieldValue((short)0, IDnr);
412                    rs.GetFieldValue(3, CommandID);
413                    rs.GetFieldValue(4, InstallationsID);
414                    
415                    Mycom.IDnr = IDnr;
416                    Mycom.CommandID = CommandID;
417                    Mycom.InstallationsID = InstallationsID;
418    
419                    buffer.push_back(Mycom);
420                    rs.MoveNext();
421    
422            }
423            rs.Close();
424            return buffer;
425    }
426    void CFlisServerDlg::ReadSms()
427    {
428            CString tekst;
429            Sleep(950);             //Holder en pause for at lade hele sms'en komme ind i serial køen.
430          if(Serial.getComstat().cbInQue > 0)          if(Serial.getComstat().cbInQue > 0)
431          {          {
432                  std::vector<unsigned char> answer = readFrame();                  std::vector<unsigned char> answer = readFrame();
433                  Sleep(50);                  Sleep(50);
434                          char array1[25];  
                         int i;  
435                          for (int i=0; i<answer.size(); i++)                          for (int i=0; i<answer.size(); i++)
436                          {                          {
437                                  array1[i] = answer[i];                                  if ((answer[i] != 0x0A) && (answer[i] != 0x0D))
438                                    {
439                                            tekst.AppendChar(answer[i]);
440                                    }
441                          }                          }
442    
443                            AppendText(tekst);
444                            SmsSplit(tekst);
445            }
446    }
447    void CFlisServerDlg::SmsSplit(CString data)
448    {
449            CString FyrData, TlfNr, SmsCount, Temper, Flamme, Flis, FremFejl, PowerFail;
450            TlfNr = data.Mid(24,8);
451            FyrData = data.Mid(57,data.GetLength()-59);
452            FyrData.Append(":");
453    
454            if (FyrData.MakeLower() == "conf ok:")
455            {
456                    HandleAcknowledge(TlfNr);
457                    return;
458            }
459            CAtlRegExp<> regex;
460            if (regex.Parse("^{[0-9]+}:{[0-9]+}:[0-1]:[0-1]:[0-1]:[0-1]:$") == REPARSE_ERROR_OK)
461            {
462    
463                    CAtlREMatchContext<> pContext;
464    
465                    if (!regex.Match(FyrData, &pContext))
466                    {
467                            AppendText("Invalid SMS recieved");
468                            return;
469                    }
470            }
471            else
472            {
473                    AppendText("Regex PARSE error!!!"); //Burde aldrig kunne ske !
474            }
475    
476            SmsCount = Splitter(FyrData);
477            Temper = Splitter(FyrData);
478            Flamme = Splitter(FyrData);
479            Flis = Splitter(FyrData);
480            FremFejl = Splitter(FyrData);
481            PowerFail = Splitter(FyrData);
482                    
483                    CString SQL, Textwindow, InstallNR;
484                    SQL.Format("select ID from installation where installationphonenr=%s",TlfNr);
485            
486                    CRecordset rs(&db);
487                    rs.Open(AFX_DB_USE_DEFAULT_TYPE, SQL);
488                    if (rs.GetRecordCount()>0)
489                    {
490                            rs.MoveFirst();        
491                            rs.GetFieldValue((short)0,InstallNR);
492                    }
493                    rs.Close();
494    
495                    SQL.Format("insert into logtable (logtime,temperature,flamedetector,solidfuelempty,conveyorerror,powerfailure,messagenr,installationnr) Values (now(),%s,'%s','%s','%s','%s',%s,%s)",Temper, Flamme, Flis, FremFejl, PowerFail, SmsCount,InstallNR);
496                    try
497                    {
498                    db.ExecuteSQL(SQL);
499                    }
500                    catch(CDBException* e)
501                    {
502                            MessageBox(e->m_strError);
503                    }
504                    AppendText("Sms added to Log");
505                    Sleep(150);
506    }
507    CString CFlisServerDlg::Splitter(CString& fyrdata)
508    {
509            CString Output;
510    
511            int pos = fyrdata.Find(':',0);
512            if (pos != -1)
513                    {
514                            Output = fyrdata.Left(pos);
515                            fyrdata = fyrdata.Right( fyrdata.GetLength() - pos -1);
516                    }
517            return Output;
518    }
519    void CFlisServerDlg::OnBnClickedClose()
520    {
521            // TODO: Add your control notification handler code here
522            continueThread = 0;
523            Sleep(250);
524            DeleteSms();
525    
526            Sleep(500);
527            if( Serial.isOpen() )
528            {
529                    Serial.close();
530            }
531            
532            if(db.IsOpen())
533            {
534                    db.Close();
535            }
536            
537            OnOK();
538    
539    }
540    void CFlisServerDlg::DeleteSms()
541    {
542            vector<unsigned char> atcommand;
543            atcommand.push_back('a');
544            atcommand.push_back('t');
545            atcommand.push_back('+');
546            atcommand.push_back('c');
547            atcommand.push_back('m');
548            atcommand.push_back('g');
549            atcommand.push_back('d');
550            atcommand.push_back('=');
551            atcommand.push_back('1');
552            atcommand.push_back(',');
553            atcommand.push_back('3');
554    
555            writeFrame(atcommand);
556            Sleep(500);
557    }
558    UINT threadWrapper(LPVOID thread)
559    {
560            CFlisServerDlg *t = (CFlisServerDlg*) thread;
561            t->runthread();
562            return 0;
563    }
564    
565    void CFlisServerDlg::startthread()
566    {
567            AfxBeginThread(threadWrapper, (LPVOID) this);
568    }
569    
570    void CFlisServerDlg::runthread()
571    {
572            while (continueThread != 0)
573            {
574                    MyMainThread();
575            }
576    }
577    void CFlisServerDlg::MyMainThread()
578    {
579            if(Serial.getComstat().cbInQue > 0)
580                    {
581                            Sleep(250);
582                            std::vector<unsigned char> answer = readFrame();
583                            Sleep(500);
584                            CString tekst;
585                                    
586                          for (int i=0; i<answer.size(); i++)                          for (int i=0; i<answer.size(); i++)
587                          {                          {
588                                  if ((array1[i] != 0x0A) && (array1[i] != 0x0D))                                  if ((answer[i] != 0x0A) && (answer[i] != 0x0D))
589                                    {
590                                            tekst.AppendChar(answer[i]);
591                                    }
592                            }
593                            tekst.Append(":");
594    
595                            CString command;
596                            bool plus = false;
597                                    int pos = tekst.Find('+',0);
598                                    if (pos != -1)
599                                    {
600                                            plus = true;
601                                            tekst = tekst.Right( tekst.GetLength() - pos -1);
602                                            pos = tekst.Find(':');
603                                            command = tekst.Left(pos);
604                                            tekst = tekst.Right( tekst.GetLength() - pos -1);
605                                    }
606                            
607                            
608                            if(tekst.MakeLower() == "ok")
609                            {      
610                                    AppendText("OK tekst modtaget");
611                            }
612                            else if (tekst.MakeLower() == "error")
613                            {
614                                    CString send;
615                                    send.Append("error tekst");
616                                    send.Append("\r\n");
617                                    send.Append(tekst);
618                                    AppendText(send);
619                            }
620                            else if (plus == true)
621                            {
622                                    if (command.MakeLower() == "cmti")
623                                    {
624                                            CString smscount;
625                                            int pos = tekst.Find(',',0);
626                                            if (pos != -1)
627                                            {
628                                                    smscount = tekst.Right( tekst.GetLength() - pos -1);
629                                                    smscount.Remove(':');
630                                                    ResetSms++;
631                                            }
632    
633                                            std::vector<unsigned char> data;
634                                            data.push_back('a');
635                                            data.push_back('t');
636                                            data.push_back('+');
637                                            data.push_back('c');
638                                            data.push_back('m');
639                                            data.push_back('g');
640                                            data.push_back('r');
641                                            data.push_back('=');
642                                            
643                                            for (int i=0; i< smscount.GetLength(); i++)
644                                            {
645                                                    data.push_back(smscount[i]);
646                                            }
647                                            writeFrame(data);
648    
649                                            data.push_back(0); //Zero terminate the string befor pasting it to logwindows
650                                            AppendText(CString(&data[0]));
651                                            Sleep(200);
652                                            ReadSms();
653    
654                                    }
655                                    else if(command.MakeLower() == "wind")
656                                    {
657    
658                                            CString send;
659                                            send.Append("Wind modtaget");
660                                            send.Append("\r\n");
661                                            send.Append(tekst);
662                                            AppendText(send);
663                                    }
664                            }
665                            else
666                            {
667                                    AppendText(tekst);
668                            }
669                    }
670                    if(ResetSms == 20)
671                    {
672                            DeleteSms();
673                            AppendText("Sms'er slettet da vi nåede grænsen");
674                    }
675    
676                    if (continueThread == 1)
677                    {
678                            
679                            CString testdata, dataframe,testprint, sIDnr, sCommandID, sInstallationsID, sImei;
680                            int commandtest = 0;
681                            int iAll = 1;
682                            std::vector<Commands> data;
683                            data = DBReadCommands();
684                            for (int i=0; i<data.size(); i++)
685                            {
686                                    sIDnr = data[i].IDnr;
687                                    sCommandID = data[i].CommandID;
688                                    commandtest = atoi(data[i].CommandID);
689                                    sInstallationsID = "0";
690    
691                                    if(commandtest > 1)
692                                  {                                  {
693                                          tekst.AppendChar(array1[i]);                                          sInstallationsID = data[i].InstallationsID;
694                                  }                                  }
695                          }                          }
696                            
697                            if (commandtest > 1)
698                            {
699                                    iAll = 0;
700                            }
701    
702                            if (sIDnr.GetLength() > 0)
703                            {
704                                    SendConfig(sIDnr,sCommandID,sInstallationsID);
705                            }
706                            Sleep(300);
707    
708                            CheckAcknowledges();
709                            Sleep(500);
710                    }
711                    CTime now = CTime::GetCurrentTime();
712    
713                    CTimeSpan elapsed = now-Alive.tid;
714    
715                    if (elapsed.GetTotalSeconds() >= 900)
716                    {
717                            keepaliveandread();
718                    }
719    }
720    void CFlisServerDlg::SendConfig(CString IDnr,CString CommandID,CString InstallationsID)
721    {      
722            
723            std::vector<Installation> inst;
724    
725            if (CommandID == "1")
726                    inst = DBReadPhone("0");
727            else
728                    inst = DBReadPhone(InstallationsID);
729    
730            for ( int j=0; j < inst.size(); j++)
731            {
732                    CString TlfNr, Imei, updaterate;
733                    TlfNr.Empty();
734                    Imei.Empty();
735                    updaterate.Empty();
736    
737                    CString dataen = inst[j].InstPhoneNr;
738                    TlfNr.Append(dataen);
739                    CString Imeidata = inst[j].Imei;
740                    Imei.Append(Imeidata);
741                    CString updaterat = inst[j].Updaterate;
742                    updaterate.Append(updaterat);
743            
744                    vector<unsigned char> tlfnr;
745                    for (int i=0; i<TlfNr.GetLength(); i++)
746                    {
747                            tlfnr.push_back(TlfNr[i]);
748                    }
749                    
750                    int calcimei;
751                    __int64 buf;
752    
753                    buf = atof(Imei);
754                    
755                    calcimei = tversum(buf);
756                    
757                    Imei.Format("%d",calcimei);
758                    
759                    SendSmsHead(tlfnr);
760                    Sleep(250);
761                    
762                    vector<unsigned char> smsdata;
763                    
764                    for (int i=0; i<Imei.GetLength(); i++)
765                    {
766                            smsdata.push_back(Imei[i]);
767                    }
768                    smsdata.push_back(':');
769                    for (int i=0; i<Alive.Phonenr.GetLength(); i++)
770                    {
771                            smsdata.push_back(Alive.Phonenr[i]);
772                    }
773                    smsdata.push_back(':');
774                    for (int i=0; i<updaterate.GetLength(); i++)
775                    {
776                            smsdata.push_back(updaterate[i]);
777                    }
778    
779                    SendSmsData(smsdata);
780                    Sleep(500);
781    
782                    if (IDnr != "0")
783                    {
784                            Acks.push_back( Acknowledge(inst[j].instID,TlfNr) );
785                    }
786    
                         m_Textwindow.GetWindowText(oldtekst);  
                         oldtekst.Append("\r\n");  
                         oldtekst.Append(tekst);  
                         m_Textwindow.SetWindowText(oldtekst);  
787          }          }
788  return 0;  
789            if (IDnr != "0")
790            {
791                    CString SQL, Textwindow;
792                    SQL.Format("update command set executed=now() where id=%s",IDnr);
793                    db.ExecuteSQL(SQL);
794                    Sleep(100);
795                    AppendText("Command executed");
796            }
797            Sleep(150);
798    
799    
800    
801    
802  }  }
803  void CFlisServerDlg::SendSmsData(std::vector<unsigned char> data)  vector<Installation> CFlisServerDlg::DBReadPhone(CString sInstallationsID)
804  {  {
805          for (int i=0; i<data.size(); i++)          vector<Installation> buffer;
806    
807            CString SQL, phonenr, imei, updaterate, id;
808            Installation Myinst;
809    
810            if (sInstallationsID != "0")
811          {          {
812                  Serial.writeByte( data[i] );                  SQL.Format("select installationphonenr, imei, updaterate, id from installation WHERE id = %s", sInstallationsID);
                 Sleep(5);  
813          }          }
814          Serial.writeByte(0x1A);          else
815          Sleep(100);          {
816                    SQL.Format("select installationphonenr, imei, updaterate, id from installation");
817            }
818    
819            CRecordset rs(&db);
820            rs.Open(AFX_DB_USE_DEFAULT_TYPE, SQL);
821            if (rs.GetRecordCount()>0)
822            {
823                    rs.MoveFirst();
824                    while(!rs.IsEOF())
825                    {
826                    
827                            rs.GetFieldValue((short)0,phonenr);
828                            rs.GetFieldValue(1,imei);
829                            rs.GetFieldValue(2,updaterate);
830                            rs.GetFieldValue(3,id);
831    
832                            Myinst.InstPhoneNr = phonenr;
833                            Myinst.Imei = imei;
834                            Myinst.Updaterate = updaterate;
835                            Myinst.instID = id;
836    
837                            buffer.push_back(Myinst);
838                            rs.MoveNext();
839                    }
840            }
841            rs.Close();
842            return buffer;
843  }  }
844  void CFlisServerDlg::SendSmsHead(std::vector<unsigned char> data)  int CFlisServerDlg::tversum(__int64 input)
845  {  {
846          for (int i=0; i<data.size(); i++)          int sum = 0;
847            while (input > 0)
848          {          {
849                  Serial.writeByte( data[i] );                  sum += (input %10);
850                  Sleep(5);                  input /= 10;
851          }          }
852          Serial.writeByte(0x0D);          return sum;
853          Sleep(100);  }
854    void CFlisServerDlg::OnBnClickedStart()
855    {
856    // TODO: Add your control notification handler code here
857    
858            AppendText("Indsætter Pinkode, og venter på modem bliver klar, hvis pinkode er nødvendig");
859            UpdateWindow();
860            SetPin();
861            
862            Sleep(100); //Give the modem a chance to send the last data
863            while(Serial.getComstat().cbInQue > 0)
864            {
865                    Serial.readByte(); //Flush the incoming queue
866                    Sleep(1);
867            }
868        Sleep(5);
869    
870            continueThread = 1;
871            keepaliveandread();
872            Sleep(150);
873            AppendText(CString("Server phonenr read from db: ") + Alive.Phonenr );
874            AppendText("Started");
875            AfxBeginThread(threadWrapper,AfxGetMainWnd());
876  }  }
877  void CFlisServerDlg::DBconnect()  void CFlisServerDlg::AppendText(CString s)
878  {  {
         CString dsn;  
         dsn.Format("ODBC;Description=asd;DRIVER=PostgreSQL ANSI;SERVER=%s; uid=%s;password=%s;database=%s",config.host, config.username, config.password, config.database);  
         db.OpenEx(dsn, CDatabase::noOdbcDialog);  
 }  
879            CTime now = CTime::GetCurrentTime();
880            CString Tekst;
881            m_Textwindow.GetWindowText(Tekst);
882            Tekst.AppendFormat("%02d:%02d:%02d : ", now.GetHour(), now.GetMinute(), now.GetSecond());
883            Tekst.Append(s);
884            Tekst.Append("\r\n");
885    
886            m_Textwindow.SetWindowText(Tekst);
887            Sleep(5);
888            int g = m_Textwindow.GetScrollLimit(SB_VERT);
889            if (g > 0)
890            {
891            m_Textwindow.SetSel(m_Textwindow.GetWindowTextLength() -1,m_Textwindow.GetWindowTextLength(),false);
892            }
893    
894    }
895    void ConfigFile::ReadSettings()
896    {
897            ifstream file("Server-Settings.ini");
898            if (!file.is_open())
899                    throw("Could not open file");
900    
901            char buf[200];
902            while (!file.eof() ) {
903                    file.getline(buf,200);
904                    CString tmp(buf);
905    
906                    if (tmp.GetAt(0) == '#')
907                            continue;
908    
909                    int pos = tmp.Find('=');
910                    if (pos>0) {
911                            CString key = tmp.Left(pos).Trim().MakeLower();;
912                            CString value = tmp.Right(tmp.GetLength()-pos-1).Trim();
913    
914                            if (key == "host")
915                                    host = value;
916                            else if (key == "username")
917                                    username = value;
918                            else if (key == "password")
919                                    password = value;
920                            else if (key == "database")
921                                    database = value;
922                            else if (key == "comport")
923                                    comport = value;
924                            else if (key == "pincode")
925                                    pincode = value;
926                    }
927    
928            }
929    
930            file.close();
931    }
932    void CFlisServerDlg::HandleAcknowledge(CString tlfnr)
933    {
934            for (std::list<Acknowledge>::iterator it = Acks.begin(); it != Acks.end(); ++it)
935            {
936                    Acknowledge& current = (*it);
937                    if (current.sTlfNr == tlfnr)
938                    {
939                            CString SQL;
940                            SQL.Format("UPDATE installation SET commerror = false WHERE id = %s", current.sInstallationID);
941                            db.ExecuteSQL(SQL);
942    
943                            Acks.erase(it);
944    
945                            return;
946                    }
947            }
948    }
949    
950    void CFlisServerDlg::CheckAcknowledges()
951    {
952            CTime now = CTime::GetCurrentTime();
953            for (std::list<Acknowledge>::iterator it = Acks.begin(); it != Acks.end(); ++it)
954            {
955                    Acknowledge& current = (*it);
956    
957                    CTimeSpan elapsed = now-current.cTime;
958    
959                    if (elapsed.GetTotalSeconds() >= 300)
960                    {
961                            DumpAckList();
962                            if (current.iRetry >= 1)
963                            {
964                                    CString SQL;
965                                    SQL.Format("UPDATE installation SET commerror = true WHERE id = %s", current.sInstallationID);
966                                    db.ExecuteSQL(SQL);
967                                    Acks.erase(it);
968                                    return; // the iterator is now invalidated, but the thread loop will make sure we are here soon again
969                            }
970                            else
971                            {
972                                    SendConfig("0","2",current.sInstallationID);
973                                    current.iRetry++;
974                                    current.cTime = CTime::GetCurrentTime();
975                                    AppendText( CString("Retry send config to ") + current.sTlfNr );
976                            }
977                    }
978            }
979    }
980    
981    void CFlisServerDlg::DumpAckList()      /* Debug tool */
982    {
983            
984            CTime now = CTime::GetCurrentTime();
985            OutputDebugString("-------------------------------\n");
986            int count = 0;
987            for (std::list<Acknowledge>::iterator it = Acks.begin(); it != Acks.end(); ++it)
988            {
989                    CString msg;
990                    msg.Format("%d:%d:%d> %4d : %s\n", now.GetHour(), now.GetMinute(), now.GetSecond(), count, (*it).sTlfNr);
991                    OutputDebugString(msg);
992                    count++;
993            }
994    }
995    vector<keepalive> CFlisServerDlg::keepaliveandread(void)
996    {
997            vector<keepalive> buffer;
998    
999            CString SQL, name, value;
1000            SQL = "select name, value from config;";
1001            CRecordset rs(&db);
1002            try
1003            {
1004                    rs.Open(AFX_DB_USE_DEFAULT_TYPE, SQL);
1005                    if (rs.GetRecordCount()>0)
1006                    {
1007                            rs.MoveFirst();
1008                            
1009                            rs.GetFieldValue((short)0, name);
1010                            rs.GetFieldValue(1,value);
1011                    
1012                            Alive.name = name;
1013                            Alive.value = value;
1014                            Alive.tid = CTime::GetCurrentTime();
1015                            if(Alive.name == "phonenr")
1016                            {
1017                                    Alive.Phonenr = value;
1018                            }
1019    
1020                            buffer.push_back(Alive);
1021                            rs.MoveNext();
1022    
1023                    }
1024                    rs.Close();
1025                    return buffer;
1026            }
1027            catch (char * str)
1028            {
1029                    AppendText("Keepalive failed, closing and opening the db connection again");
1030                    if(db.IsOpen())
1031                    {
1032                            db.Close();
1033                            AppendText("DB connection closed");
1034                    }
1035                    if(!db.IsOpen())
1036                    {
1037                            DBConnect();
1038                            AppendText("DB connection started again");
1039                    }
1040                    return buffer;
1041            }
1042    
1043            
1044    }

Legend:
Removed from v.70  
changed lines
  Added in v.297

  ViewVC Help
Powered by ViewVC 1.1.20