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

Legend:
Removed from v.105  
changed lines
  Added in v.168

  ViewVC Help
Powered by ViewVC 1.1.20