]> git.stg.codes - stg.git/blob - projects/stargazer/stg_timer.cpp
Добавление исходников
[stg.git] / projects / stargazer / stg_timer.cpp
1 #include <unistd.h>
2 #include <pthread.h>
3
4 #include <cstring>
5
6 #include "common.h"
7
8 static int nonstop;
9 static pthread_t thrStgTimer;
10 static bool isTimerRunning = false;
11 volatile time_t stgTime;
12
13 const int TIME_SPEED = 1;
14 /*
15  1  - 1x  speed
16  2  - 2x  speed
17  5  - 5x  speed
18  10 - 10x speed
19  */
20
21 const int START_TIME = 0;
22 /*
23  0 - as is
24  1 - start before new day (3 min before)   29.11.2005 23:57:00
25  2 - start before new month (3 min before) 30.11.2005 23:57:00
26  */
27
28 //-----------------------------------------------------------------------------
29 void * StgTimer(void *)
30 {
31 #ifdef STG_TIMER_DEBUG
32 struct tm lt;
33 memset(&lt, 0, sizeof(lt));
34
35 lt.tm_year = 2007 - 1900; // 2005
36 lt.tm_mon  = 10 - 1;      // Nov
37 lt.tm_hour = 23;          // 23 h
38 lt.tm_min = 57;           // 50 min
39 lt.tm_sec = 0;            // 00 sec
40
41 switch (START_TIME)
42     {
43     case 0:
44         stgTime = time(NULL);
45         break;
46
47     case 1:
48         lt.tm_mday = 29;
49         stgTime = mktime(&lt);
50         break;
51
52     case 2:
53         lt.tm_mday = 30;
54         stgTime = mktime(&lt);
55         break;
56     }
57 #endif
58
59 nonstop = 1;
60 isTimerRunning = true;
61 while (nonstop)
62     {
63     #ifdef STG_TIMER_DEBUG
64     usleep(1000000 / TIME_SPEED);
65     stgTime++;
66     #else
67     stgTime = time(NULL);
68     usleep(500000);
69     #endif
70     }
71 isTimerRunning = false;
72
73 return NULL;
74 }
75 //-----------------------------------------------------------------------------
76 int RunStgTimer()
77 {
78 static int a = 0;
79 isTimerRunning = false;
80
81 if (a == 0)
82     if (pthread_create(&thrStgTimer, NULL, StgTimer, NULL))
83         {
84         isTimerRunning = false;
85         return -1;
86         }
87
88 a = 1;
89 return 0;
90 }
91 //-----------------------------------------------------------------------------
92 void StopStgTimer()
93 {
94 nonstop = 0;
95 pthread_join(thrStgTimer, NULL); // Cleanup thread resources
96 printfd(__FILE__, "STG_TIMER stopped\n");
97 }
98 //-----------------------------------------------------------------------------
99 bool IsStgTimerRunning()
100 {
101 return isTimerRunning;
102 }
103 //-----------------------------------------------------------------------------
104 int stgUsleep(unsigned long t)
105 {
106 #ifdef STG_TIMER_DEBUG
107 return usleep(t / TIME_SPEED);
108 #else
109 return usleep(t);
110 #endif
111 }
112 //-----------------------------------------------------------------------------
113 void WaitTimer()
114 {
115     for (int i = 0; i < 5 && !isTimerRunning; i++)
116         stgUsleep(200000);
117 }
118 //-----------------------------------------------------------------------------
119
120