RDK Documentation (Open Sourced RDK Components)
Helper.cpp
1 /*
2  * If not stated otherwise in this file or this component's Licenses.txt file the
3  * following copyright and licenses apply:
4  *
5  * Copyright 2016 RDK Management
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18 */
19 
20 
21 using namespace std;
22 
23 /* A Helper module for TRM Manager which would process all the request for TRM Manager */
24 
25 
26 /*Helper header*/
27 #include "Helper.h"
28 #include "Debug.h"
29 
30 /*For Socket*/
31 #include <arpa/inet.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <fcntl.h>
35 
36 /*C++ include*/
37 #include <errno.h>
38 #include <stdlib.h>
39 #include <map>
40 #include <string>
41 #include <string.h>
42 #include <uuid/uuid.h>
43 #include <list>
44 #include <vector>
45 #include <time.h>
46 #include <sys/time.h>
47 #include <stddef.h>
48 #include <sys/syscall.h>
49 #include <unistd.h>
50 #include <stdint.h>
51 #include <vector>
52 #include <memory>
53 #include <limits>
54 #include <iostream>
55 #include <map>
56 #include <string>
57 
58 /* TRM Include*/
59 #include "trm/Messages.h"
60 #include "trm/MessageProcessor.h"
61 #include "trm/Activity.h"
62 #include "trm/JsonEncoder.h"
63 #include "trm/JsonDecoder.h"
64 #include "trm/TRM.h"
65 #include "trm/Klass.h"
66 #include "trm/TunerReservation.h"
67 #include <pthread.h>
68 #include "safec_lib.h"
69 
70 using namespace TRM;
71 
72 /*Connection and Message Processing Info*/
73 
74 /* Static variables */
75 #define MAX_PAYLOAD_LEN 4096
76 static int trm_diag_fd = -1;
77 static const char* ip ="127.0.0.1";
78 static int port = 9987;
79 static int is_connected = 0;
80 static const uint32_t kTRMMgrClientId = 0XFFFFFF04;
81 static bool TrmResponseRcvd = false;
82 static uint32_t numofTRMErrors = 0;
83 
84 
85 /* Static functions */
86 static int connect_to_trm();
87 static void processBuffer( const char* , int );
88 static void * ProcessTRMMessage (void* arg);
89 static bool url_request_post( const char *payload, int payload_length, unsigned int clientId);
90 static char responseStr[MAX_PAYLOAD_LEN];
91 static bool waitForTRMResponse();
92 static bool getAllTunerReservationsResponse();
93 
94 
95 enum Type {
96  REQUEST = 0x1234,
97  RESPONSE = 0x1800,
98  NOTIFICATION = 0x1400,
99  UNKNOWN,
100 };
101 
102 
103 
104 /* list of all connected device IDs. */
105 std::list<std::string> conDeviceList;
106 /* list of all connected Events. */
107 std::list<NotifyClientConnectionEvent> helperConEventLists;
108 
109 
111 {
112 public :
113  void operator() (const TRM::GetVersionResponse &msg);
114  void operator() (const TRM::GetAllReservationsResponse &msg);
115  void operator() (const TRM::NotifyClientConnectionEvent &msg);
116  void operator() (const TRM::NotifyTunerReservationConflicts &msg);
117  void operator() (const TRM::ReserveTunerResponse &msg);
118 
119 
120 };
121 
122 
123 /* For connection sync */
124 static pthread_mutex_t Helper_mutex;
125 
127 {
128 public:
129  HelperLock_(void) {
130  pthread_mutex_lock(&Helper_mutex);
131  }
132  ~HelperLock_(void) {
133  pthread_mutex_unlock(&Helper_mutex);
134  }
135 };
136 #define HelperLock() HelperLock_ t()
137 
138 bool TRMMgrHelperImpl::inited = false;
139 
140 TRMMgrHelperImpl::TRMMgrHelperImpl()
141 {
142  DIAG_TRACE((" %s():%d \r\n" , __FUNCTION__, __LINE__));
143 }
144 
145 TRMMgrHelperImpl::~TRMMgrHelperImpl()
146 {
147  DIAG_TRACE(("%s():%d \r\n" , __FUNCTION__, __LINE__));
148 }
149 
150 
151 /**
152  * @brief Init and connect with TRM
153  *
154  */
156 {
157  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
158 
159  if ( false == inited )
160  {
161 
162  /*Connect To TRM */
163  connect_to_trm();
164 
165  /*Mutex Init*/
166  pthread_mutex_init(&Helper_mutex, NULL);
167 
168  /* Create a Thread to Process Message */
169  pthread_t trm_process_message_thread;
170  pthread_create(&trm_process_message_thread, NULL,ProcessTRMMessage, (void *)trm_diag_fd);
171 
172  inited = true;
173  }
174  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
175 }
176 
177 
178 /**
179  * @brief Instance of TRMMgrHelperImpl object.
180  *
181  */
183 {
184  static TRMMgrHelperImpl TRMMgrHelperInstance;
185  return TRMMgrHelperInstance;
186 }
187 
188 
189 /**
190  * @brief Get TRM Version Number
191  */
192 
193 
194 bool TRMMgrHelperImpl::getVersion(uint32_t *length,char *responseMsg)
195 {
196  bool ret = false;
197  std::vector<uint8_t> out;
198 
199  uuid_t value;
200  char guid[64];
201  uuid_generate(value);
202  uuid_unparse(value, guid);
203 
204 
205  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
206 
207  if (NULL == responseMsg)
208  {
209  DIAG_WARN(("responseMsg is NULL \r\n"));
210  return false;
211  }
212 
213  TRM::GetVersion msg(guid, "");
214  JsonEncode(msg, out);
215  out.push_back(0);
216 
217  int len = strlen((const char*)&out[0]);
218  int retry_count = 5;
219  errno_t safec_rc = -1;
220 
221  do
222  {
223  TrmResponseRcvd = false;
224  safec_rc = memset_s(responseStr, sizeof(responseStr), 0, sizeof(responseStr));
225  ERR_CHK(safec_rc);
226  ret = url_request_post( (char *) &out[0], len, kTRMMgrClientId);
227  retry_count --;
228  } while ((ret == false) && (retry_count >0));
229 
230  if (ret == true)
231  {
232  // Wait for a response
233  ret = waitForTRMResponse();
234  }
235 
236  // copy to response message for Requested Client
237  safec_rc = strcpy_s(responseMsg,MAX_PAYLOAD_LEN, responseStr);
238  if(safec_rc != EOK) {
239  ERR_CHK(safec_rc);
240  return false;
241  }
242 
243  *length = strlen(responseStr);
244 
245  DIAG_DEBUG(("Message Length of getVersion response = %d ...\r\n",*length));
246  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
247 
248  return ret;
249 
250 }
251 
252 
253 /**
254  * @brief Send a TRM Request to get all Reservation
255  * Get the Response and send to TRM Mgr.
256  */
257 bool TRMMgrHelperImpl::getTunerReservationsList(uint32_t *length,char *responseMsg)
258 {
259 
260 
261  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
262 
263  bool ret = false;
264  errno_t safec_rc = -1;
265 
266  if (NULL == responseMsg)
267  {
268  DIAG_WARN(("responseMsg is NULL ...\r\n"));
269  return false;
270  }
271 
272  /* Get the Message from the Get All Reservation Response Message */
273  ret = getAllTunerReservationsResponse();
274 
275  if (ret == true)
276  {
277  // copy to response message for Requested Client
278  safec_rc = strcpy_s(responseMsg,MAX_PAYLOAD_LEN, responseStr);
279  if(safec_rc != EOK) {
280  ERR_CHK(safec_rc);
281  return false;
282  }
283  *length = strlen(responseStr);
284  DIAG_DEBUG(("Message Length of getTunerReservationsList = %d ...\r\n",*length));
285  }
286  else
287  {
288  ret = false;
289  DIAG_WARN(("getAllTunerReservationsResponse Failed ...\r\n"));
290  }
291 
292  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
293  return ret;
294 }
295 
296 
297 
298 
299 /**
300  * @brief Send a TRM Request to get all connected Device IDs
301  * Get the Response and send to TRM Mgr.
302  */
303 bool TRMMgrHelperImpl::getConnectedDeviceIdList(uint32_t *length,char *responseMsg)
304 {
305 
306  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
307 
308  bool ret = false;
309 
310  if (NULL == responseMsg)
311  {
312  DIAG_WARN(("responseMsg is NULL ...\r\n"));
313  return false;
314  }
315 
316  /* Get the connected devices from the Get All Reservation Response Message */
317  ret = getAllTunerReservationsResponse();
318 
319  if (ret == true)
320  {
321  /* Get the UUID and Response Message */
322  TRM::ResponseStatus responseStatus(ResponseStatus::kOk);
323  std::vector<uint8_t> out;
324  uuid_t value;
325  char guid[64];
326  uuid_generate(value);
327  uuid_unparse(value, guid);
328 
329  /* Frame the Connected Device Message */
330  TRM::GetAllConnectedDeviceIdsResponse msg(guid,responseStatus,conDeviceList);
331 
332  // Encode the message
333  msg.print();
334  JsonEncode(msg, out);
335  out.push_back(0);
336 
337  // copy to response message for Requested Client
338  std::copy(out.begin(), out.end(),responseMsg);
339  responseMsg[out.size()] = '\0';
340  *length = out.size();
341 
342  DIAG_DEBUG(("Message Length of GetAllConnectedDeviceIdsResponse = %d ...\r\n",*length));
343  }
344  else
345  {
346  ret = false;
347  DIAG_WARN(("getAllTunerReservationsResponse Failed --->\r\n"));
348 
349  }
350 
351  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
352 
353  return ret;
354 }
355 
356 
357 /**
358  * @brief Send a TRM Request to get all Reservation
359  * Get the Response and send to TRM Mgr.
360  */
361 static bool getAllTunerReservationsResponse()
362 {
363  bool ret = false;
364  std::vector<uint8_t> out;
365  uuid_t value;
366  char guid[64];
367  uuid_generate(value);
368  uuid_unparse(value, guid);
369 
370  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
371 
372  // get Tuner reservation
373  TRM::GetAllReservations msg(guid,"");
374 
375  // Encode the message
376  JsonEncode(msg, out);
377  out.push_back(0);
378  int len = strlen((const char*)&out[0]);
379  int retry_count = 5;
380  errno_t safec_rc = -1;
381 
382  do
383  {
384  //Post the message
385  TrmResponseRcvd = false;
386  safec_rc = memset_s(responseStr, sizeof(responseStr), 0, sizeof(responseStr));
387  ERR_CHK(safec_rc);
388 
389  ret = url_request_post( (char *) &out[0], len, kTRMMgrClientId);
390  retry_count --;
391  } while ((ret == false) && (retry_count >0));
392 
393  if (ret == true)
394  {
395  // Wait for a response
396  ret = waitForTRMResponse();
397  }
398 
399  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
400  return ret;
401 }
402 
403 
404 bool TRMMgrHelperImpl::getNumofTRMErrors(uint32_t *errCount)
405 {
406 
407  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
408 
409  bool ret = true;
410 
411  if (NULL == errCount)
412  {
413  DIAG_WARN(("Param errCount is NULL ...\r\n"));
414  return false;
415  }
416 
417  *errCount = numofTRMErrors;
418 
419  DIAG_DEBUG(("Num of TRM Errors are %d ...\r\n",*errCount));
420 
421  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
422 
423  return ret;
424 }
425 
426 /**
427  * @brief Send a TRM Request to get all connected Device IDs
428  * Get the Response and send to TRM Mgr.
429  */
430 bool TRMMgrHelperImpl::getTRMConnectionEventList(uint32_t *length,char *responseMsg)
431 {
432 
433  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
434 
435  bool ret = true;
436 
437  if (NULL == responseMsg)
438  {
439  DIAG_WARN(("responseMsg is NULL ...\r\n"));
440  return false;
441  }
442 
443  if (0 == helperConEventLists.size())
444  {
445 
446  DIAG_WARN(("No Event to Send ...\r\n"));
447  *length = 0;
448  return true;
449  }
450 
451  /* Get the UUID and Response Message */
452  TRM::ResponseStatus responseStatus(ResponseStatus::kOk);
453  std::vector<uint8_t> out;
454  uuid_t value;
455  char guid[64];
456  uuid_generate(value);
457  uuid_unparse(value, guid);
458 
459  /* Frame the Connected Device Message */
460  TRM::GetTRMConnectionEvents msg(guid,responseStatus,helperConEventLists);
461 
462  // Encode the message
463  JsonEncode(msg, out);
464  out.push_back(0);
465 
466  // copy to response message for Requested Client
467  std::copy(out.begin(), out.end(),responseMsg);
468  responseMsg[out.size()] = '\0';
469  *length = out.size();
470 
471  DIAG_DEBUG(("Message Length of getTRMConnectionEventList = %d ...\r\n",*length));
472  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
473 
474  return ret;
475 }
476 
477 
478 
479 /**
480  * @brief Version Response Message
481  */
483 {
484  HelperLock();
485 
486  int statusCode = msg.getStatus().getStatusCode();
487  if (TRM::ResponseStatus::kOk == statusCode)
488  {
489  DIAG_DEBUG(("(GetVersionResponse) Sucess = %d\r\n",statusCode));
490  }
491  else
492  {
493  DIAG_WARN(("(GetVersionResponse) Error code = %d\r\n",statusCode));
494  }
495 
496  TrmResponseRcvd = true;
497 }
498 
499 
500 
501 
502 /**
503  * @brief TRM GetAllReservationsResponse Message
504  */
506 {
507  HelperLock();
508 
509  int statusCode = msg.getStatus().getStatusCode();
510 
511  if (TRM::ResponseStatus::kOk == statusCode)
512  {
513 
514  const std::map<std::string, std::list<TunerReservation> > & allReservations = msg.getAllReservations();
515  std::map<std::string, std::list<TunerReservation> >::const_iterator it;
516 
517  /*clear the list */
518  conDeviceList.clear();
519  for (it = allReservations.begin(); it != allReservations.end(); it++)
520  {
521  const std::list<TunerReservation> & tunerReservations = it->second;
522  std::list<TunerReservation>::const_iterator it1;
523  for (it1 = tunerReservations.begin(); it1 != tunerReservations.end(); it1++) {
524  if (!((*it1).getDevice().empty()))
525  {
526  DIAG_DEBUG(("Add device %s to List \r\n",(*it1).getDevice().c_str()));
527  conDeviceList.push_back ((*it1).getDevice());
528  }
529  }
530  }
531  }
532  else
533  {
534  DIAG_WARN(("(GetVersionResponse) Error code = %d\r\n",statusCode));
535  }
536 
537  TrmResponseRcvd = true;
538 }
539 
540 /**
541  * @brief Get Notify Client Message
542  */
544 {
545  HelperLock();
546 
547  DIAG_DEBUG(("NotifyClientConnectionEvent) Event Name = %s\r\n",msg.getEventName().c_str()));
548  DIAG_DEBUG(("NotifyClientConnectionEvent) Device IP = %s\r\n", msg.getClientIP().c_str()));
549  DIAG_DEBUG(("NotifyClientConnectionEvent) Time Stamp = %llu\r\n",msg.getEventTimeStamp()));
550 
551  /* Update new events to the list*/
552  helperConEventLists.push_back(msg);
553 
554  /* Increment the Num of Tuner Error Count*/
555  numofTRMErrors ++;
556 
557  TrmResponseRcvd = true;
558 }
559 
560 
561 /**
562  * @brief Get Notify Conflict message
563  */
565 {
566  HelperLock();
567 
568  const TRM::ReserveTunerResponse::ConflictCT &conflicts = msg.getConflicts();
569 
570  if (conflicts.size() != 0)
571  {
572  DIAG_WARN(("Diag Helper : Found %d conflict(s)\r\n",conflicts.size()));
573  numofTRMErrors++;
574 
575  TRM::ReserveTunerResponse::ConflictCT::const_iterator it = conflicts.begin();
576  for (it = conflicts.begin(); it != conflicts.end(); it++)
577  {
578  DIAG_DEBUG(("Device:[%s] with Activity:[%s] Locator:[%s] Token:[%s] is in conflict with:\r\n",
579  (*it).getDevice().c_str(),
580  (const char *)(*it).getActivity().getActivity(),
581  (*it).getServiceLocator().c_str(),
582  (*it).getReservationToken().c_str()));
583 
585  DIAG_DEBUG(("Device:[%s] with Activity:[%s] Locator:[%s] Token:[%s]\r\n",
586  resv.getDevice().c_str(),
587  (const char *)resv.getActivity().getActivity(),
588  resv.getServiceLocator().c_str(),
589  resv.getReservationToken().c_str()));
590  }
591  }
592  TrmResponseRcvd = true;
593 }
594 
595 
596 
598 {
599  HelperLock();
600 
601  TRM::ResponseStatus status = msg.getStatus();
602  DIAG_DEBUG(("Received ReserveTunerResponse message \r\n"));
603 
604  if ( status == TRM::ResponseStatus::kOk )
605  {
606  DIAG_DEBUG(("%s - ResponseStatus - kOK \r\n", __FUNCTION__));
607  const TRM::ReserveTunerResponse::ConflictCT &conflicts = msg.getConflicts();
608  if (conflicts.size() != 0)
609  {
610  DIAG_WARN(("%s- Has %d Conflict(s)\r\n", __FUNCTION__,conflicts.size()));
611  numofTRMErrors++;
612  }
613  else
614  {
615  DIAG_DEBUG(("%s- Has No(%d) Conflict(s)\r\n", __FUNCTION__,conflicts.size()));
616  }
617 
618  }
619 }
620 
621 
622 /**
623  * @brief This function is used to Process the incoming TRM message.
624  */
625 static void* ProcessTRMMessage (void* arg)
626 {
627  int read_trm_count = 0;
628  char *buf = NULL;
629  const int header_length = 16;
630  unsigned int payload_length = 0;
631  errno_t safec_rc = -1;
632 
633  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
634 
635  while (1)
636  {
637  if (is_connected == 0)
638  {
639  connect_to_trm();
640  }
641  if ( is_connected )
642  {
643  buf = (char *) malloc(header_length);
644  if (buf == NULL)
645  {
646  DIAG_WARN(("%s:%d : Malloc failed for %d bytes \r\n", __FUNCTION__, __LINE__, header_length));
647  continue;
648  }
649 
650  safec_rc = memset_s(buf, header_length, 0, header_length);
651  ERR_CHK(safec_rc);
652 
653 
654  /* Read Response from TRM, read header first, then payload */
655  read_trm_count = read(trm_diag_fd, buf, header_length);
656 
657  DIAG_TRACE(("\r\n Read Header from TRM %d vs expected %d\r\n", read_trm_count, header_length));
658 
659  #if 0
660  __TIMESTAMP();printf("=====RESPONSE HEADER===================================================\r\n[");
661  for (idx = 0; idx < (header_length); idx++) {
662  DIAG_TRACE(("%02x:", buf[idx]));
663  }
664  printf("\r\n:");
665  #endif
666 
667  if (read_trm_count == header_length)
668  {
669  unsigned int payload_length_offset = 12;
670  payload_length =((((unsigned char)(buf[payload_length_offset+0])) << 24) |
671  (((unsigned char)(buf[payload_length_offset+1])) << 16) |
672  (((unsigned char)(buf[payload_length_offset+2])) << 8 ) |
673  (((unsigned char)(buf[payload_length_offset+3])) << 0 ));
674 
675  if((payload_length > 0) && (payload_length < MAX_PAYLOAD_LEN)) /*Coverity fix, what is the maximum payload size? or how much maximum memory can be assigned*/
676  {
677  free( buf);
678  buf = NULL;
679  DIAG_DEBUG(("TRM Response payloads is %d and header %d\r\n", payload_length, header_length));
680  fflush(stderr);
681 
682  buf = (char *) malloc(payload_length+1);
683  safec_rc = memset_s(buf, payload_length+1, 0, payload_length+1);
684  ERR_CHK(safec_rc);
685 
686  read_trm_count = read(trm_diag_fd, buf, payload_length);
687  DIAG_DEBUG(("Read Payload from TRM %d vs expected %d\r\n", read_trm_count, payload_length));
688 
689  if (read_trm_count != 0)
690  {
691  buf[payload_length] = '\0';
692  processBuffer(buf, read_trm_count);
693  free(buf);
694  buf = NULL;
695  }
696  else
697  {
698  /* retry connect after payload-read failure*/
699  is_connected = 0;
700  free(buf);
701  buf = NULL;
702  DIAG_WARN(("%s:%d : read_trm_count is 0 \r\n", __FUNCTION__, __LINE__));
703 
704  }
705  }
706  else
707  {
708  /* retry connect after payload-read failure*/
709 
710  //is_connected = 0;
711  free(buf);
712  buf = NULL;
713  DIAG_WARN(("%s:%d : payload_length = %d Count Mismatch \r\n", __FUNCTION__, __LINE__,payload_length));
714  }
715  }
716  else
717  {
718  DIAG_WARN(("%s:%d : header-read failure read_trm_count %d \r\n", __FUNCTION__, __LINE__, read_trm_count));
719  free(buf);
720  buf = NULL;
721  /* retry connect after header-read failure */
722  is_connected = 0;
723  }
724  }
725  else
726  {
727  DIAG_WARN(("%s - Not connected- Sleep and retry \r\n", __FUNCTION__));
728  sleep(1);
729  }
730  }
731  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
732 
733 }
734 
735 
736 /**
737  * @brief This function is used to Deocode the parse message from TRM Srv
738  */
739 static void processBuffer( const char* buf, int len)
740 {
741  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
742 
743  if (buf != NULL)
744  {
745  DIAG_DEBUG(("Response %s \r\n", buf));
746  DIAG_DEBUG(("Response Length %d - %d\r\n", strlen(buf),len));
747 
748  errno_t safec_rc = -1;
749  safec_rc = memset_s(responseStr, sizeof(responseStr), 0, sizeof(responseStr));
750  ERR_CHK(safec_rc);
751 
752  std::vector<uint8_t> response;
753 
754  safec_rc = strcpy_s(responseStr, sizeof(responseStr), buf);
755  ERR_CHK(safec_rc);
756 
757  response.insert( response.begin(), buf, buf+len);
758 
759  MsgProcessor msgProc;
760  TRM::JsonDecoder jdecoder( msgProc);
761  jdecoder.decode( response);
762  }
763  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
764 }
765 
766 
767 
768 
769 /**
770  * @brief This function is used to connect to TRM Srv
771  */
772 static int connect_to_trm()
773 {
774  int socket_fd ;
775  int socket_error = 0;
776  struct sockaddr_in trm_address = {0};
777 
778  HelperLock();
779 
780  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
781 
782 
783  if (is_connected == 0)
784  {
785  sleep(5);
786  DIAG_WARN(("Connecting to remote %s-%d \r\n",__FUNCTION__, __LINE__));
787  trm_address.sin_family = AF_INET;
788  trm_address.sin_addr.s_addr = inet_addr(ip);
789  trm_address.sin_port = htons(port);
790  if (trm_diag_fd == -1 )
791  {
792  socket_fd = socket(AF_INET, SOCK_STREAM, 0);
793  }
794  else
795  {
796  socket_fd = trm_diag_fd;
797  }
798 
799  while(1)
800  {
801  int retry_count = 10;
802  socket_error = connect(socket_fd, (struct sockaddr *) &trm_address, sizeof(struct sockaddr_in));
803  if (socket_error == ECONNREFUSED && retry_count > 0)
804  {
805  DIAG_WARN(("TRM Server is not started...retry to connect \r\n" , __FUNCTION__, __LINE__));
806  sleep(2);
807  retry_count--;
808  }
809  else
810  {
811  break;
812  }
813  }
814 
815  if (socket_error == 0)
816  {
817  DIAG_WARN(("%s:%d : Connected \r\n" , __FUNCTION__, __LINE__));
818  int current_flags = fcntl(socket_fd, F_GETFL, 0);
819  current_flags &= (~O_NONBLOCK);
820  fcntl(socket_fd, F_SETFL, current_flags);
821  trm_diag_fd = socket_fd;
822  is_connected = 1;
823  }
824  else
825  {
826  DIAG_WARN(("%s:%d : socket_error %d, closing socket\r\n" , __FUNCTION__, __LINE__, socket_error));
827  close(socket_fd);
828  trm_diag_fd = -1;
829  }
830  }
831 
832  DIAG_TRACE(("%s:%d : Exit with socket error code %d\r\n",__FUNCTION__, __LINE__, socket_error));
833  return socket_error;
834 }
835 
836 
837 
838 /**
839  * @brief This function is used to post request to TRM server
840  */
841 static bool url_request_post( const char *payload, int payload_length, unsigned int clientId)
842 {
843  bool ret = false;
844 
845  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
846 
847  if ( is_connected == 0)
848  connect_to_trm();
849 
850  if ( is_connected )
851  {
852  if (payload_length != 0)
853  {
854  /* First prepend header */
855  static int message_id = 0x1000;
856  const int header_length = 16;
857  unsigned char *buf = NULL;
858  buf = (unsigned char *) malloc(payload_length + header_length);
859  int idx = 0;
860  /* Magic Word */
861  buf[idx++] = 'T';
862  buf[idx++] = 'R';
863  buf[idx++] = 'M';
864  buf[idx++] = 'S';
865  /* Type, set to UNKNOWN, as it is not used right now*/
866  buf[idx++] = (UNKNOWN & 0xFF000000) >> 24;
867  buf[idx++] = (UNKNOWN & 0x00FF0000) >> 16;
868  buf[idx++] = (UNKNOWN & 0x0000FF00) >> 8;
869  buf[idx++] = (UNKNOWN & 0x000000FF) >> 0;
870  /* Message id */
871  ++message_id;
872 
873  DIAG_WARN(("CONNECTION CLIENTID: %02x\r\n",clientId));
874 
875  buf[idx++] = (clientId & 0xFF000000) >> 24;
876  buf[idx++] = (clientId & 0x00FF0000) >> 16;
877  buf[idx++] = (clientId & 0x0000FF00) >> 8;
878  buf[idx++] = (clientId & 0x000000FF) >> 0;
879  /* Payload length */
880  buf[idx++] = (payload_length & 0xFF000000) >> 24;
881  buf[idx++] = (payload_length & 0x00FF0000) >> 16;
882  buf[idx++] = (payload_length & 0x0000FF00) >> 8;
883  buf[idx++] = (payload_length & 0x000000FF) >> 0;
884 
885  for (int i =0; i< payload_length; i++)
886  buf[idx+i] = payload[i];
887  DIAG_TRACE(("====== REQUEST MSG ======\r\n["));
888 
889  for (idx = 0; idx < (header_length); idx++) {
890  DIAG_TRACE(( "%02x", buf[idx]));
891  }
892  DIAG_TRACE(("]\r\n\n"));
893 
894  for (; idx < (payload_length + header_length); idx++) {
895  DIAG_TRACE(("%c", buf[idx]));
896  }
897  DIAG_TRACE(("\n\n"));
898 
899  /* Write payload from fastcgi to TRM */
900  int write_trm_count = write(trm_diag_fd, buf, payload_length + header_length);
901  DIAG_TRACE(("Send to TRM %d vs expected %d\r\n", write_trm_count, payload_length + header_length));
902  free(buf);
903  buf = NULL;
904 
905  if (write_trm_count == 0)
906  {
907  is_connected = 0;
908  DIAG_WARN(("%s():%d : Error in Sending Data to Socket:write_trm_count is now 0 \r\n", __FUNCTION__, __LINE__));
909  }
910  else
911  {
912  ret = true;
913  }
914  }
915  }
916  else
917  {
918  DIAG_WARN(("%s():%d : Not Connected to TRM Server\r\n", __FUNCTION__, __LINE__));
919  }
920 
921  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
922 
923  return ret;
924 }
925 
926 
927 /**
928  * @brief This function waits for TRM respnse */
929 static bool waitForTRMResponse()
930 {
931  int retry_count = 500;
932 
933  DIAG_TRACE(("Enter %s():%d \r\n" , __FUNCTION__, __LINE__));
934 
935  while ((false == TrmResponseRcvd) && (retry_count > 0))
936  {
937  DIAG_DEBUG(("%s():%d ..and loop ..\r\n", __FUNCTION__, __LINE__));
938  usleep(10*1000);
939  retry_count --;
940  }
941 
942  if((retry_count == 0))
943  {
944  DIAG_WARN(("Time out.. waitForTRMResponse %s():%d \r\n" , __FUNCTION__, __LINE__));
945  return false;
946  }
947  DIAG_TRACE(("Exit %s():%d \r\n" , __FUNCTION__, __LINE__));
948  return true;
949 }
950 
TRM::ResponseStatus
This class is responsible for handling response message for tuner reservation. All response messages ...
Definition: ResponseStatus.h:62
TRM::ReserveTunerResponse::getConflicts
const ConflictCT & getConflicts(void) const
This function returns an array of existing tuner reservations that is in conflict with the requested ...
Definition: Messages.h:914
TRM::MessageProcessor
Definition: MessageProcessor.h:39
TRM::NotifyTunerReservationConflicts::getConflicts
const ConflictCT & getConflicts(void) const
This function will return the array of tuner reservation conflicts.
Definition: Messages.h:2001
TRMMgrHelperImpl::getInstance
static TRMMgrHelperImpl & getInstance()
Instance of TRMMgrHelperImpl object.
Definition: Helper.cpp:182
TRMMgrHelperImpl::init
static void init()
Init and connect with TRM.
Definition: Helper.cpp:155
MsgProcessor
This function is used to Deocode the parse messafe from TRM Srv.
Definition: Helper.cpp:110
TRM::TunerReservationBase::getDevice
const std::string & getDevice(void) const
This function is used to get the remote device id requesting for tuner reservation.
Definition: TunerReservation.cpp:127
TRM::GetAllConnectedDeviceIdsResponse
Definition: Messages.h:2178
TRM::NotifyClientConnectionEvent
Definition: Messages.h:2099
HelperLock_
Definition: Helper.cpp:126
TRM::NotifyTunerReservationConflicts
Class for implementing asynchronous notification from TRM to the owner of a token that a tuner reserv...
Definition: Messages.h:1945
TRM::ReserveTunerResponse
Class implementing the response message to a ReserveTuner request.
Definition: Messages.h:858
MsgProcessor::operator()
void operator()(const TRM::GetVersionResponse &msg)
Version Response Message.
Definition: Helper.cpp:482
TRM::TunerReservationBase::getActivity
const Activity & getActivity(void) const
This function is used to return the granted activity. Granted activity may or may not be the same as ...
Definition: TunerReservation.cpp:142
Messages.h
TRM::GetTRMConnectionEvents
Definition: Messages.h:2139
TRM::TunerReservationBase::getServiceLocator
const std::string & getServiceLocator(void) const
This function is used to return the locator of the service that the tuner is tuned to.
Definition: TunerReservation.cpp:94
TRMMgrHelperImpl::getConnectedDeviceIdList
bool getConnectedDeviceIdList(uint32_t *length, char *responseMsg)
Send a TRM Request to get all connected Device IDs Get the Response and send to TRM Mgr.
Definition: Helper.cpp:303
TRM::JsonDecoder
Definition: JsonDecoder.h:73
TRMMgrHelperImpl::getTRMConnectionEventList
bool getTRMConnectionEventList(uint32_t *length, char *responseMsg)
Send a TRM Request to get all connected Device IDs Get the Response and send to TRM Mgr.
Definition: Helper.cpp:430
TRMMgrHelperImpl::getTunerReservationsList
bool getTunerReservationsList(uint32_t *length, char *responseMsg)
Send a TRM Request to get all Reservation Get the Response and send to TRM Mgr.
Definition: Helper.cpp:257
TRM::GetAllReservationsResponse
Implements the response message for the request to get All tuner reservation details.
Definition: Messages.h:1692
TRMMgrHelperImpl::getVersion
bool getVersion(uint32_t *length, char *responseMsg)
Get TRM Version Number.
Definition: Helper.cpp:194
TRM::GetAllReservations
Implements a request message to get reservation detail of all the tuners that are valid at that time.
Definition: Messages.h:1727
TRM::TunerReservationBase
The TunerReservation class is used to set the requested or granted tuner reservation from client....
Definition: TunerReservation.h:139
TRM::TunerReservationBase::getReservationToken
const std::string & getReservationToken(void) const
This function is used to return the unique token generated when a reservation is created.
Definition: TunerReservation.cpp:83
TRMMgrHelperImpl
Definition: Helper.h:33
TRM::Activity::getActivity
const Enum< Activity > & getActivity(void) const
This function is used to return the request or granted usage of tuner. The Activity field represents ...
Definition: Activity.cpp:89
TRM::NotifyTunerReservationConflicts::getTunerReservation
const TunerReservation & getTunerReservation(void) const
This function will return the details of the current reservation that has to be cancelled as a result...
Definition: Messages.h:1972
TRM::GetVersion
Implements a message to request for getting TRM server version.
Definition: Messages.h:1820
TRM::GetVersionResponse
Implements the response message for the queries that request TRM server version.
Definition: Messages.h:1783