- split out meta parser
[enigma2.git] / lib / dvb / dvbtime.cpp
1 #include <lib/dvb/dvbtime.h>
2 #include <lib/dvb/dvb.h>
3
4 #include <sys/ioctl.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9
10 // defines for DM7000 / DM7020
11 #define FP_IOCTL_SET_RTC         0x101
12 #define FP_IOCTL_GET_RTC         0x102
13
14 static time_t prev_time;
15
16 void setRTC(time_t time)
17 {
18         int fd = open("/dev/dbox/fp0", O_RDWR);
19         if ( fd >= 0 )
20         {
21                 if ( ::ioctl(fd, FP_IOCTL_SET_RTC, (void*)&time ) < 0 )
22                         eDebug("FP_IOCTL_SET_RTC failed(%m)");
23                 else
24                         prev_time = time;
25                 close(fd);
26         }
27 }
28
29 time_t getRTC()
30 {
31         time_t rtc_time=0;
32         int fd = open("/dev/dbox/fp0", O_RDWR);
33         if ( fd >= 0 )
34         {
35                 if ( ::ioctl(fd, FP_IOCTL_GET_RTC, (void*)&rtc_time ) < 0 )
36                         eDebug("FP_IOCTL_GET_RTC failed(%m)");
37                 close(fd);
38         }
39         return rtc_time != prev_time ? rtc_time : 0;
40 }
41
42 time_t parseDVBtime(__u8 t1, __u8 t2, __u8 t3, __u8 t4, __u8 t5)
43 {
44         tm t;
45         t.tm_sec=fromBCD(t5);
46         t.tm_min=fromBCD(t4);
47         t.tm_hour=fromBCD(t3);
48         int mjd=(t1<<8)|t2;
49         int k;
50
51         t.tm_year = (int) ((mjd - 15078.2) / 365.25);
52         t.tm_mon = (int) ((mjd - 14956.1 - (int)(t.tm_year * 365.25)) / 30.6001);
53         t.tm_mday = (int) (mjd - 14956 - (int)(t.tm_year * 365.25) - (int)(t.tm_mon * 30.6001));
54         k = (t.tm_mon == 14 || t.tm_mon == 15) ? 1 : 0;
55         t.tm_year = t.tm_year + k;
56         t.tm_mon = t.tm_mon - 1 - k * 12;
57         t.tm_mon--;
58
59         t.tm_isdst =  0;
60         t.tm_gmtoff = 0;
61
62         return timegm(&t);
63 }
64
65 TDT::TDT(eDVBChannel *chan)
66         :chan(chan)
67 {
68         CONNECT(tableReady, TDT::ready);
69         CONNECT(m_interval_timer.timeout, TDT::start);
70         if (chan)
71                 chan->getDemux(demux);
72 }
73
74 void TDT::ready(int error)
75 {
76         eDVBLocalTimeHandler::getInstance()->updateTime(error, chan);
77 }
78
79 int TDT::createTable(int nr, const __u8 *data, unsigned int max)
80 {
81         if ( data && data[0] == 0x70 || data[0] == 0x73 )
82         {
83                 int length = ((data[1] & 0x0F) << 8) | data[2];
84                 if ( length >= 8 )
85                 {
86                         time_t tptime = parseDVBtime(data[3], data[4], data[5], data[6], data[7]);
87                         eDVBLocalTimeHandler::getInstance()->updateTime(tptime, chan);
88                         error=0;
89                         return 1;
90                 }
91         }
92         return 0;
93 }
94
95 void TDT::start()
96 {
97         if ( chan )
98         {
99                 eDVBTableSpec spec;
100                 spec.pid = TimeAndDateTable::PID;
101                 spec.tid = TimeAndDateTable::TID;
102                 spec.tid_mask = 0xFC;
103                 spec.timeout = TimeAndDateTable::TIMEOUT;
104                 spec.flags= eDVBTableSpec::tfAnyVersion |
105                                         eDVBTableSpec::tfHaveTID |
106                                         eDVBTableSpec::tfHaveTIDMask |
107                                         eDVBTableSpec::tfCheckCRC |
108                                         eDVBTableSpec::tfHaveTimeout;
109                 if ( demux )
110                         eGTable::start( demux, spec );
111         }
112 }
113
114 void TDT::startTimer( int interval )
115 {
116         m_interval_timer.start(interval, true);
117 }
118
119 eDVBLocalTimeHandler *eDVBLocalTimeHandler::instance;
120 DEFINE_REF(eDVBLocalTimeHandler);
121
122 eDVBLocalTimeHandler::eDVBLocalTimeHandler()
123         :m_time_ready(false), m_time_difference(0)
124 {
125         if ( !instance )
126                 instance=this;
127         ePtr<eDVBResourceManager> res_mgr;
128         eDVBResourceManager::getInstance(res_mgr);
129         if (!res_mgr)
130                 eDebug("[eDVBLocalTimerHandler] no resource manager !!!!!!!");
131         else
132                 res_mgr->connectChannelAdded(slot(*this,&eDVBLocalTimeHandler::DVBChannelAdded), m_chanAddedConn);
133 }
134
135 eDVBLocalTimeHandler::~eDVBLocalTimeHandler()
136 {
137         instance=0;
138         for (std::map<iDVBChannel*, channel_data>::iterator it=m_knownChannels.begin(); it != m_knownChannels.end(); ++it)
139                 delete it->second.tdt;
140 }
141
142 void eDVBLocalTimeHandler::readTimeOffsetData( const char* filename )
143 {
144         m_timeOffsetMap.clear();
145         FILE *f=fopen(filename, "r");
146         if (!f)
147                 return;
148         char line[256];
149         fgets(line, 256, f);
150         while (true)
151         {
152                 if (!fgets( line, 256, f ))
153                         break;
154                 if (strstr(line, "Transponder UTC Time Offsets\n"))
155                         continue;
156                 int dvbnamespace,tsid,onid,offs;
157                 if ( sscanf( line, "%08x,%04x,%04x:%d\n",&dvbnamespace,&tsid,&onid,&offs ) == 4 )
158                         m_timeOffsetMap[eDVBChannelID(dvbnamespace,tsid,onid)]=offs;
159         }
160         fclose(f);
161 }
162
163 void eDVBLocalTimeHandler::writeTimeOffsetData( const char* filename )
164 {
165         FILE *f=fopen(filename, "w+");
166         if ( f )
167         {
168                 fprintf(f, "Transponder UTC Time Offsets\n");
169                 for ( std::map<eDVBChannelID,int>::iterator it ( m_timeOffsetMap.begin() ); it != m_timeOffsetMap.end(); ++it )
170                         fprintf(f, "%08x,%04x,%04x:%d\n",
171                                 it->first.dvbnamespace.get(),
172                                 it->first.transport_stream_id.get(), it->first.original_network_id.get(), it->second );
173                 fclose(f);
174         }
175 }
176
177 void eDVBLocalTimeHandler::updateTime( time_t tp_time, eDVBChannel *chan )
178 {
179         bool restart_tdt = false;
180         if (!tp_time )
181                 restart_tdt = true;
182         else if (tp_time == -1)
183         {
184                 restart_tdt = true;
185                 /*if ( eSystemInfo::getInstance()->getHwType() == eSystemInfo::DM7020 ||
186                 ( eSystemInfo::getInstance()->getHwType() == eSystemInfo::DM7000
187                         && eSystemInfo::getInstance()->hasStandbyWakeupTimer() ) )     TODO !!!!!!! */
188                 {
189                         eDebug("[eDVBLocalTimerHandler] no transponder tuned... or no TDT/TOT avail .. try to use RTC :)");
190                         time_t rtc_time = getRTC();
191                         if ( rtc_time ) // RTC Ready?
192                         {
193                                 tm now = *localtime(&rtc_time);
194                                 eDebug("[eDVBLocalTimerHandler] RTC time is %02d:%02d:%02d",
195                                         now.tm_hour,
196                                         now.tm_min,
197                                         now.tm_sec);
198                                 time_t linuxTime=time(0);
199                                 time_t nowTime=linuxTime+m_time_difference;
200                                 now = *localtime(&nowTime);
201                                 eDebug("[eDVBLocalTimerHandler] Receiver time is %02d:%02d:%02d",
202                                         now.tm_hour,
203                                         now.tm_min,
204                                         now.tm_sec);
205                                 m_time_difference = rtc_time - linuxTime;
206                                 eDebug("[eDVBLocalTimerHandler] RTC to Receiver time difference is %d seconds", nowTime - rtc_time );
207                                 if ( abs(m_time_difference) > 59 )
208                                 {
209                                         eDebug("[eDVBLocalTimerHandler] set Linux Time to RTC Time");
210                                         timeval tnow;
211                                         gettimeofday(&tnow,0);
212                                         tnow.tv_sec=rtc_time;
213                                         settimeofday(&tnow,0);
214                                         for (ePtrList<eMainloop>::iterator it(eMainloop::existing_loops)
215                                                 ;it != eMainloop::existing_loops.end(); ++it)
216                                                 it->setTimerOffset(m_time_difference);
217                                         m_time_difference=0;
218                                 }
219                                 else if ( !m_time_difference )
220                                         eDebug("[eDVBLocalTimerHandler] no change needed");
221                                 else
222                                         eDebug("[eDVBLocalTimerHandler] set to RTC time");
223                                 /*emit*/ m_timeUpdated();
224                         }
225                         else
226                                 eDebug("[eDVBLocalTimerHandler] shit RTC not ready :(");
227                 }
228         }
229         else
230         {
231                 std::map< eDVBChannelID, int >::iterator it( m_timeOffsetMap.find( chan->getChannelID() ) );
232
233  // current linux time
234                 time_t linuxTime = time(0);
235
236  // current enigma time
237                 time_t nowTime=linuxTime+m_time_difference;
238
239         // difference between current enigma time and transponder time
240                 int enigma_diff = tp_time-nowTime;
241
242                 int new_diff=0;
243
244                 if ( m_time_ready )  // ref time ready?
245                 {
246                         // difference between reference time (current enigma time)
247                         // and the transponder time
248                         eDebug("[eDVBLocalTimerHandler] diff is %d", enigma_diff);
249                         if ( abs(enigma_diff) < 120 )
250                         {
251                                 eDebug("[eDVBLocalTimerHandler] diff < 120 .. use Transponder Time");
252                                 m_timeOffsetMap[chan->getChannelID()] = 0;
253                                 new_diff = enigma_diff;
254                         }
255                         else if ( it != m_timeOffsetMap.end() ) // correction saved?
256                         {
257                                 eDebug("[eDVBLocalTimerHandler] we have correction %d", it->second);
258                                 time_t CorrectedTpTime = tp_time+it->second;
259                                 int ddiff = CorrectedTpTime-nowTime;
260                                 eDebug("[eDVBLocalTimerHandler] diff after add correction is %d", ddiff);
261                                 if ( abs(it->second) < 300 ) // stored correction < 5 min
262                                 {
263                                         eDebug("[eDVBLocalTimerHandler] use stored correction(<5 min)");
264                                         new_diff = ddiff;
265                                 }
266                                 else if ( /*eSystemInfo::getInstance()->getHwType() == eSystemInfo::DM7020 &&  TODO !!!*/
267                                                 getRTC() )
268                                 {
269                                         time_t rtc=getRTC();
270                                         m_timeOffsetMap[chan->getChannelID()] = rtc-tp_time;
271                                         new_diff = rtc-nowTime;  // set enigma time to rtc
272                                         eDebug("[eDVBLocalTimerHandler] update stored correction to %d (calced against RTC time)", rtc-tp_time );
273                                 }
274                                 else if ( abs(ddiff) <= 120 )
275                                 {
276 // with stored correction calced time difference is lower 2 min
277 // this don't help when a transponder have a clock running to slow or to fast
278 // then its better to have a DM7020 with always running RTC
279                                         eDebug("[eDVBLocalTimerHandler] use stored correction(corr < 2 min)");
280                                         new_diff = ddiff;
281                                 }
282                                 else  // big change in calced correction.. hold current time and update correction
283                                 {
284                                         eDebug("[eDVBLocalTimerHandler] update stored correction to %d", -enigma_diff);
285                                         m_timeOffsetMap[chan->getChannelID()] = -enigma_diff;
286                                 }
287                         }
288                         else
289                         {
290                                 eDebug("[eDVBLocalTimerHandler] no correction found... store calced correction(%d)",-enigma_diff);
291                                 m_timeOffsetMap[chan->getChannelID()] = -enigma_diff;
292                         }
293                 }
294                 else  // no time setted yet
295                 {
296                         if ( it != m_timeOffsetMap.end() )
297                         {
298                                 enigma_diff += it->second;
299                                 eDebug("[eDVBLocalTimerHandler] we have correction (%d)... use", it->second );
300                         }
301                         else
302                                 eDebug("[eDVBLocalTimerHandler] dont have correction.. set Transponder Diff");
303                         new_diff=enigma_diff;
304                         m_time_ready=true;
305                 }
306
307                 time_t t = nowTime+new_diff;
308                 m_last_tp_time_difference=tp_time-t;
309
310                 if (!new_diff)
311                 {
312                         eDebug("[eDVBLocalTimerHandler] not changed");
313                         return;
314                 }
315
316                 tm now = *localtime(&t);
317                 eDebug("[eDVBLocalTimerHandler] time update to %02d:%02d:%02d",
318                         now.tm_hour,
319                         now.tm_min,
320                         now.tm_sec);
321
322                 m_time_difference = t - linuxTime;   // calc our new linux_time -> enigma_time correction
323                 eDebug("[eDVBLocalTimerHandler] m_time_difference is %d", m_time_difference );
324
325 //              if ( eSystemInfo::getInstance()->getHwType() == eSystemInfo::DM7020 )  TODO !!
326                         setRTC(t);
327
328                 if ( abs(m_time_difference) > 59 )
329                 {
330                         eDebug("[eDVBLocalTimerHandler] set Linux Time");
331                         timeval tnow;
332                         gettimeofday(&tnow,0);
333                         tnow.tv_sec=t;
334                         settimeofday(&tnow,0);
335                         for (ePtrList<eMainloop>::iterator it(eMainloop::existing_loops)
336                                 ;it != eMainloop::existing_loops.end(); ++it)
337                                 it->setTimerOffset(m_time_difference);
338                         m_time_difference=0;
339                 }
340
341                  /*emit*/ m_timeUpdated();
342         }
343
344         if ( restart_tdt )
345         {
346                 std::map<iDVBChannel*, channel_data>::iterator it =
347                         m_knownChannels.find(chan);
348                 if ( it != m_knownChannels.end() )
349                 {
350                         delete it->second.tdt;
351                         it->second.tdt = new TDT(chan);
352                         it->second.tdt->startTimer(60*1000);  // restart TDT for this transponder in 60min
353                 }
354         }
355 }
356
357 void eDVBLocalTimeHandler::DVBChannelAdded(eDVBChannel *chan)
358 {
359         if ( chan )
360         {
361                 eDebug("[eDVBLocalTimerHandler] add channel %p", chan);
362                 std::pair<std::map<iDVBChannel*, channel_data>::iterator, bool> tmp =
363                         m_knownChannels.insert( std::pair<iDVBChannel*, channel_data>(chan, channel_data()) );
364                 tmp.first->second.tdt = new TDT(chan);
365                 tmp.first->second.channel = chan;
366                 chan->connectStateChange(slot(*this, &eDVBLocalTimeHandler::DVBChannelStateChanged), tmp.first->second.m_stateChangedConn);
367         }
368 }
369
370 void eDVBLocalTimeHandler::DVBChannelStateChanged(iDVBChannel *chan)
371 {
372         std::map<iDVBChannel*, channel_data>::iterator it =
373                 m_knownChannels.find(chan);
374         if ( it != m_knownChannels.end() )
375         {
376                 int state=0;
377                 chan->getState(state);
378                 switch (state)
379                 {
380                         case iDVBChannel::state_idle:
381                                 break;
382                         case iDVBChannel::state_tuning:
383                                 break;
384                         case iDVBChannel::state_unavailable:
385                                 break;
386                         case iDVBChannel::state_ok:
387                                 eDebug("[eDVBLocalTimerHandler] channel %p running", chan);
388                                 it->second.tdt->start();
389                                 break;
390                         case iDVBChannel::state_release:
391                                 eDebug("[eDVBLocalTimerHandler] remove channel %p", chan);
392                                 delete it->second.tdt;
393                                 m_knownChannels.erase(it);
394                                 break;
395                 }
396         }
397 }