2 * Copyright (C) ARM Limited 2010-2013. All rights reserved.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
18 #include "OlySocket.h"
19 #include "SessionData.h"
21 Sender::Sender(OlySocket* socket) {
25 // Set up the socket connection
27 char streamline[64] = {0};
30 // Receive magic sequence - can wait forever
31 // Streamline will send data prior to the magic sequence for legacy support, which should be ignored for v4+
32 while (strcmp("STREAMLINE", streamline) != 0) {
33 if (mDataSocket->receiveString(streamline, sizeof(streamline)) == -1) {
34 logg->logError(__FILE__, __LINE__, "Socket disconnected");
39 // Send magic sequence - must be done first, after which error messages can be sent
41 snprintf(magic, 32, "GATOR %i\n", PROTOCOL_VERSION);
42 mDataSocket->send(magic, strlen(magic));
44 gSessionData->mWaitingOnCommand = true;
45 logg->logMessage("Completed magic sequence");
48 pthread_mutex_init(&mSendMutex, NULL);
59 void Sender::createDataFile(char* apcDir) {
64 mDataFileName = (char*)malloc(strlen(apcDir) + 12);
65 sprintf(mDataFileName, "%s/0000000000", apcDir);
66 mDataFile = fopen(mDataFileName, "wb");
68 logg->logError(__FILE__, __LINE__, "Failed to open binary file: %s", mDataFileName);
74 inline T min(const T a, const T b) {
75 return (a < b ? a : b);
78 void Sender::writeData(const char* data, int length, int type) {
79 if (length < 0 || (data == NULL && length > 0)) {
83 // Multiple threads call writeData()
84 pthread_mutex_lock(&mSendMutex);
86 // Send data over the socket connection
89 const int alarmDuration = 8;
92 // Send data over the socket, sending the type and size first
93 logg->logMessage("Sending data with length %d", length);
94 if (type != RESPONSE_APC_DATA) {
95 // type and length already added by the Collector for apc data
96 unsigned char header[5];
98 header[1] = (length >> 0) & 0xff;
99 header[2] = (length >> 8) & 0xff;
100 header[3] = (length >> 16) & 0xff;
101 header[4] = (length >> 24) & 0xff;
102 mDataSocket->send((char*)&header, sizeof(header));
105 // 100Kbits/sec * alarmDuration sec / 8 bits/byte
106 const int chunkSize = 100*1000 * alarmDuration / 8;
109 mDataSocket->send((char*)data + pos, min(length - pos, chunkSize));
116 alarm(alarmDuration);
117 logg->logMessage("Resetting the alarm");
124 // Write data to disk as long as it is not meta data
125 if (mDataFile && type == RESPONSE_APC_DATA) {
126 logg->logMessage("Writing data with length %d", length);
127 // Send data to the data file
128 if (fwrite(data, 1, length, mDataFile) != (unsigned int)length) {
129 logg->logError(__FILE__, __LINE__, "Failed writing binary file %s", mDataFileName);
134 pthread_mutex_unlock(&mSendMutex);