Changeset bdb766


Ignore:
Timestamp:
01/16/12 16:30:41 (4 months ago)
Author:
Micke Prag <micke.prag@…>
Branches:
('master', 'deebf2045e7119c339412580f37a1e653f7d5715')('controller-upgrade', '00f95d22e12d96ef089e0902ef62ae8ce841dc6f')
Children:
9afb2cbbacbc788de8372e6c0a2dd60585f0e947
Parents:
1e650c7142f7844537be880bdfa4b4229880b6add326331538b646bc02f6b87b9391500238901a94
git-author:
Micke Prag <micke.prag@telldus.se>2012-01-16 16:30:10+01:00
git-committer:
Micke Prag <micke.prag@telldus.se>2012-01-16 16:30:41+01:00
Message:

Merge branch 'master' into ticket96

Conflicts:

telldus-gui/Plugins/Sensors/main.qml
telldus-gui/Plugins/Sensors/sensor.cpp

Files:
27 added
15 deleted
54 edited
24 moved

Legend:

Unmodified
Added
Removed
  • .gitignore

    r47998b r01855c  
    11build/ 
     2qtcreator-build/ 
     3Doxyfile 
     4html/ 
     5latex/ 
     6CMakeLists.txt.user 
  • docs/telldus-core.dox

    r72575f r290a80  
    188188 * \endcode 
    189189 * 
     190 * \subsection sec_bu_sensors Sensors 
     191 * 
     192 * Retrieving sensor values can be done in two ways. Either by a polling 
     193 * interface or by callbacks. The client application can implement one or both 
     194 * of these interfaces. For callbacks, read more under \ref sec_events. 
     195 * 
     196 * Each of the sensors can have one or several value types. Currently only 
     197 * temperature and humidity are implemented. 
     198 * 
     199 * There is no API to add, remove or edit sensors. Each sensor that 
     200 * TellStick Duo has got any data from is added to an internal list. It is up to 
     201 * the client application to filter and only show the sensors your are 
     202 * interested in. 
     203 * 
     204 * To iterate over the list of sensors, call tdSensor() repeatedly as long as it 
     205 * returns \c TELLSTICK_SUCCESS. The parameters \c protocol, \c model, 
     206 * \c sensorId, and \c dataTypes are sent by reference and will be filled with 
     207 * the values. 
     208 * 
     209 * Example: 
     210 * \code 
     211 * char protocol[DATA_LENGTH], model[DATA_LENGTH]; 
     212 * int sensorId = 0, dataTypes = 0; 
     213 * while(tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes) == TELLSTICK_SUCCESS) { 
     214 *   //Print the sensor 
     215 *   printf("%s,\t%s,\t%i\n", protocol, model, sensorId); 
     216 * } 
     217 * \endcode 
     218 * 
     219 * The type of sensor values the sensor supports are stored as flags in the 
     220 * parameter \c sensorId. Call tdSensorValue() for each type. 
     221 * 
     222 * Example: 
     223 * \code 
     224 * char value[DATA_LENGTH]; 
     225 * char timeBuf[80]; 
     226 * time_t timestamp = 0; 
     227 * if (dataTypes & TELLSTICK_TEMPERATURE) { 
     228 *   tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, value, DATA_LENGTH, (int *)&timestamp); 
     229 *   strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); 
     230 *   printf("Temperature:\t%sº\t(%s)\n", value, timeBuf); 
     231 * } 
     232 * \endcode 
     233 * 
    190234 * \section sec_events Events 
    191235 * 
    192  * To get events from either a TellStick Duo or if another software changes the 
    193  * status of a device you have to register for a callback. 
     236 * To get events from either a TellStick Duo, another software changes the 
     237 * status of a device, or new sensors values you have to register for a callback. 
    194238 * 
    195239 * \subsection sec_events_registering Registering for callbacks 
     
    199243 * \li tdRegisterDeviceChangeEvent() 
    200244 * \li tdRegisterRawDeviceEvent() 
     245 * \li tdRegisterSensorEvent() 
    201246 * 
    202247 * These all work in the same way. The first parameter is a function-pointer to 
     
    213258 * Many devices (for example motion detectors) resends their messages many times 
    214259 * to ensure that they are received correctly. If a deviceeventcallback or 
    215  * rawdeviceeventcallback in turn is calling a controlling function, for example tdTurnOn, 
    216  * it may be neccessary to implement some solution to wait for the device to finish its 
    217  * resending, before executing the controlling function. See how this can be done in the python example. 
     260 * rawdeviceeventcallback in turn is calling a controlling function, for example 
     261 * tdTurnOn, it may be neccessary to implement some solution to wait for the 
     262 * device to finish its resending, before executing the controlling function. 
     263 * See how this can be done in the python example. 
    218264 * 
    219265 * \subsection sec_events_callbacks Callbacks 
    220266 * 
    221  * telldus-core currently implements three different callback function for 
     267 * telldus-core currently implements four different callback function for 
    222268 * different purposes. 
    223269 * 
     
    235281 * this hold the current value. 
    236282 * - int callbackId - id of callback 
    237  * - void *context - see "Registering for callbacks" for description 
     283 * - void *context - see \ref sec_events_registering for description 
    238284 * 
    239285 * \subsubsection sec_events_callbacks_devicechangeevent DeviceChangeEvent 
     286 * 
    240287 * This event is fired when the data around a device is changed. It can only be 
    241288 * triggered by another software. Use this callback to keep your list of devices 
     
    257304 *   - TELLSTICK_CHANGE_MODEL - Use tdGetModel() to read the new value. 
    258305 * - int callbackId - id of callback 
    259  * - void *context - see "Registering for callbacks" for description 
     306 * - void *context - see \ref sec_events_registering for description 
    260307 * 
    261308 * \subsubsection sec_events_callbacks_rawdeviceevent RawDeviceEvent 
    262309 * 
    263  * Use this callback with caution. It outputs everything from the Duo without 
    264  * any preprocessing. This can be used to get events from devices not already 
    265  * configured. 
     310 * Use this callback with caution. It outputs everything from a TellStick Duo 
     311 * without any preprocessing. This can be used to get events from devices not 
     312 * already configured. 
    266313 * 
    267314 * Parameters: 
     
    269316 * - int controllerId - id of receiving controller, can identify the TellStick if several exists in the system 
    270317 * - int callbackId - id of callback 
    271  * - void *context - see "Registering for callbacks" for description 
     318 * - void *context - see \ref sec_events_registering for description 
     319 * 
     320 * \subsubsection sec_events_callbacks_sensorevent SensorEvent 
     321 * 
     322 * This event is fired when a new sensor value is retrieved. 
     323 * 
     324 * Parameters: 
     325 * - const char *protocol - The sensors protocol 
     326 * - const char *model - The model of the sensor 
     327 * - int id - The unique id for the sensor. 
     328 * - int dataType - Flags for which types of data the sensor supports 
     329 * - const char *value - A human readable string of the data 
     330 * - int timestamp - The timestamp when the latest value was received 
     331 * - int callbackId - id of callback 
     332 * - void *context - See \ref sec_events_registering for description 
    272333 * 
    273334 * \subsection sec_events_example Example 
  • telldus-core/client/CallbackDispatcher.cpp

    r9535ec r245864  
    99 
    1010#include "CallbackDispatcher.h" 
     11#include "common.h" 
    1112 
    1213using namespace TelldusCore; 
     
    2930 
    3031void TDDeviceEventDispatcher::run() { 
     32        char *str = wrapStdString(strData); 
    3133        d->event(deviceId, method, strData.c_str(), d->id, d->context); 
     34 
    3235        doneRunning = true; 
    3336} 
  • telldus-core/client/Client.cpp

    r9535ec r46d70a  
    115115int Client::getIntegerFromService(const Message &msg) { 
    116116        std::wstring response = sendToService(msg); 
     117        if (response.compare(L"") == 0) { 
     118                return TELLSTICK_ERROR_COMMUNICATING_SERVICE; 
     119        } 
    117120        return Message::takeInt(&response); 
    118121} 
     
    182185                } 
    183186 
    184                 std::wstring clientMessage = d->eventSocket.read(5000); //testing 5 second timeout 
     187                std::wstring clientMessage = d->eventSocket.read(1000); //testing 5 second timeout 
     188 
    185189                while(clientMessage != L""){ 
    186190                        //a message arrived 
     
    283287 
    284288std::wstring Client::sendToService(const Message &msg) { 
    285         Socket s; 
    286         s.connect(L"TelldusClient"); 
    287         if (!s.isConnected()) { //Connection failed 
    288                 TelldusCore::Message msg; 
    289                 msg.addArgument(TELLSTICK_ERROR_CONNECTING_SERVICE); 
    290                 return msg; 
    291         } 
    292         s.write(msg.data()); 
    293  
    294         return s.read(5000); 
     289         
     290        int tries = 0; 
     291        std::wstring readData; 
     292        while(tries < 20){ 
     293                tries++; 
     294                if(tries == 20){ 
     295                        TelldusCore::Message msg; 
     296                        msg.addArgument(TELLSTICK_ERROR_CONNECTING_SERVICE); 
     297                        return msg; 
     298                } 
     299                Socket s; 
     300                s.connect(L"TelldusClient"); 
     301                if (!s.isConnected()) { //Connection failed 
     302                        printf("Connection failed\n\r"); 
     303                        msleep(500); 
     304                        continue; //retry 
     305                } 
     306                s.write(msg.data()); 
     307                if (!s.isConnected()) { //Connection failed sometime during operation... (better check here, instead of 5 seconds timeout later) 
     308                        printf("Connection failed after write\n\r"); 
     309                        msleep(500); 
     310                        continue; //retry 
     311                } 
     312                readData = s.read(8000);  //TODO changed to 10000 from 5000, how much does this do...? 
     313                if(readData == L""){ 
     314                        printf("Readdata nothing\n\r"); 
     315                        msleep(500); 
     316                        continue; //TODO can we be really sure it SHOULD be anything? 
     317                        //TODO perhaps break here instead? 
     318                } 
     319                 
     320                if (!s.isConnected()) { //Connection failed sometime during operation... 
     321                        printf("Connection failed in the end\n\r"); 
     322                        msleep(500); 
     323                        continue; //retry 
     324                } 
     325                break; 
     326        } 
     327 
     328        return readData; 
    295329} 
    296330 
  • telldus-core/client/telldus-core.cpp

    r8eaaf6 r46d70a  
    5858 * Error code. Returned when the command succeeded. 
    5959 * 
     60 * @def TELLSTICK_ERROR_BROKEN_PIPE 
     61 * Error code. Pipe broken during communication. 
     62 * 
    6063 * @def TELLSTICK_ERROR_NOT_FOUND 
    6164 * Error code. Returned if a TellStick was not found on the system. 
     
    8285 * Error code. The client library received a response from the service 
    8386 * it did not understand. 
     87 * 
     88 * @def TELLSTICK_ERROR_SYNTAX 
     89 * Error code. Input/command could not be parsed or didn't follow 
     90 * input rules. 
     91 * 
     92 * @def TELLSTICK_ERROR_COMMUNICATING_SERVICE 
     93 * Error code. Timeout waiting for response from the Telldus Service. 
    8494 * 
    8595 * @def TELLSTICK_ERROR_UNKNOWN 
     
    480490 * @sa TELLSTICK_ERROR_DEVICE_NOT_FOUND 
    481491 * @sa TELLSTICK_ERROR_METHOD_NOT_SUPPORTED 
     492 * @sa TELLSTICK_ERROR_COMMUNICATION 
     493 * @sa TELLSTICK_ERROR_CONNECTING_SERVICE 
     494 * @sa TELLSTICK_ERROR_UNKNOWN_RESPONSE 
     495 * @sa TELLSTICK_ERROR_SYNTAX 
     496 * @sa TELLSTICK_ERROR_BROKEN_PIPE 
     497 * @sa TELLSTICK_ERROR_COMMUNICATING_SERVICE 
    482498 * @sa TELLSTICK_ERROR_UNKNOWN 
    483499 */ 
    484500char * WINAPI tdGetErrorString(int intErrorNo) { 
    485         const int numResponses = 8; 
     501        const int numResponses = 10; 
    486502        const char *responses[numResponses] = { 
    487503                "Success", 
     
    492508                "An error occurred while communicating with TellStick", 
    493509                "Could not connect to the Telldus Service", 
    494                 "Received an unknown response" 
     510                "Received an unknown response", 
     511                "Syntax error", 
     512                "Broken pipe" 
     513                "An error occured while communicating with the Telldus Service" 
    495514        }; 
    496515        std::string strReturn; 
     
    512531 */ 
    513532int WINAPI tdSendRawCommand(const char *command, int reserved) { 
     533        std::wstring wcommand; 
     534        for(int i = 0; i < strlen(command);++i) { 
     535                wcommand.append(1, (unsigned char)command[i]); 
     536        } 
    514537        Message msg(L"tdSendRawCommand"); 
    515         msg.addArgument(command); 
     538        msg.addArgument(wcommand); 
    516539        msg.addArgument(reserved); 
    517540        return Client::getIntegerFromService(msg); 
     
    535558} 
    536559 
     560/** 
     561 * Use this function to iterate over all sensors. Iterate until 
     562 * TELLSTICK_SUCCESS is not returned 
     563 * @param protocol A byref string where the protocol of the sensor will be placed 
     564 * @param protocolLen The length of the \c protocol parameter 
     565 * @param model A byref string where the model of the sensor will be placed 
     566 * @param modelLen The length of the \c model parameter 
     567 * @param id A byref int where the id of the sensor will be placed 
     568 * @param dataTypes A byref int with flags for the supported sensor values 
     569 * @returns TELLSTICK_SUCCESS if there is more sensors to be fetched 
     570 */ 
    537571int WINAPI tdSensor(char *protocol, int protocolLen, char *model, int modelLen, int *id, int *dataTypes) { 
    538572        Client *client = Client::getInstance(); 
     
    540574} 
    541575 
     576/** 
     577 * Get one of the supported sensor values from a sensor. Make sure it support 
     578 * the value type first by calling tdSensor(). The triplet \c protocol, 
     579 * \c model, and \c id together identifies a sensor. 
     580 * @param protocol The protocol for the sensor 
     581 * @param model The model for the sensor 
     582 * @param id The id of the sensor 
     583 * @param dataType One of the datatype to retrieve 
     584 * @param value A byref string where the value will be places 
     585 * @param len The length of the \c value parameter 
     586 * @param timestamp A byref int where the timestamp of the value will be placed 
     587 * @returns TELLSTICK_SUCCESS if the value could be fetched or one of the 
     588 * errorcodes on failure 
     589 */ 
    542590int WINAPI tdSensorValue(const char *protocol, const char *model, int id, int dataType, char *value, int len, int *timestamp) { 
    543591        Message msg(L"tdSensorValue"); 
     
    563611 
    564612 
    565 /*\@}*/ 
     613/* @} */ 
  • telldus-core/client/telldus-core.h

    r8eaaf6 r46d70a  
    116116#define TELLSTICK_ERROR_CONNECTING_SERVICE -6 
    117117#define TELLSTICK_ERROR_UNKNOWN_RESPONSE -7 
     118#define TELLSTICK_ERROR_SYNTAX -8 
     119#define TELLSTICK_ERROR_BROKEN_PIPE -9 
     120#define TELLSTICK_ERROR_COMMUNICATING_SERVICE -10 
    118121#define TELLSTICK_ERROR_UNKNOWN -99 
    119122 
  • telldus-core/common/Message.cpp

    rfe7f8f r245864  
    2424 
    2525void Message::addArgument(const std::wstring &value) { 
    26         std::wstringstream st; 
    27         st << (int)value.size(); 
    28         this->append(st.str()); 
     26        //std::wstringstream st; 
     27        //st << (int)value.size(); 
     28        this->append(TelldusCore::intToWstring(value.size())); //st.str()); 
    2929        this->append(L":"); 
    3030        this->append(value); 
     
    3232 
    3333void Message::addArgument(int value) { 
    34         std::wstringstream st; 
    35         st << (int)value; 
     34        //std::wstringstream st; 
     35        //st << (int)value; 
    3636        this->append(L"i"); 
    37         this->append(st.str()); 
     37        this->append(TelldusCore::intToWstring(value)); // st.str()); 
    3838        this->append(L"s"); 
    3939} 
     40 
     41/* 
     42void Message::addSpecialArgument(const std::wstring &value){ 
     43        int i = 0; 
     44        while(i<1000000){ 
     45                i++; 
     46 
     47                char numstr[21]; // enough to hold all numbers up to 64-bits 
     48                //sprintf(numstr, "%d", value.size()); 
     49                //this->append(TelldusCore::charToWstring(numstr)); //.str()); 
     50 
     51                itoa(value.size(), numstr, 10); 
     52                std::string test(numstr); 
     53                std::wstring temp(test.length(), L' '); 
     54                std::copy(test.begin(), test.end(), temp.begin()); 
     55 
     56                this->append(temp); 
     57                this->append(L":"); 
     58                this->append(value); 
     59 
     60                /* 
     61                std::wstringstream st; 
     62                st << (int)value.size(); 
     63                this->append(st.str()); 
     64                this->append(L":"); 
     65                this->append(value); 
     66                 
     67        } 
     68} 
     69 
     70void Message::addSpecialArgument(int value){ 
     71        int i = 0; 
     72        while(i<1000000){ 
     73                i++; 
     74                /* 
     75                //std::wstringstream st; 
     76                //st << (int)value; 
     77                this->append(L"i"); 
     78                //this->append(st.str()); 
     79                this->append(L"s"); 
     80                 
     81        } 
     82} 
     83*/ 
     84/* 
     85void Message::addSpecialArgument(const char *value){ 
     86        this->addSpecialArgument(TelldusCore::charToWstring(value)); 
     87} 
     88*/ 
    4089 
    4190void Message::addArgument(const char *value) { 
  • telldus-core/common/Message.h

    rfe7f8f r245864  
    1212 
    1313                void addArgument(const std::wstring &); 
     14                //void addSpecialArgument(const std::wstring &); 
     15                //void addSpecialArgument(int); 
     16                //void addSpecialArgument(const char *); 
    1417                void addArgument(int); 
    1518                void addArgument(const char *); 
  • telldus-core/common/Socket_unix.cpp

    rb25802 r673daf  
    7979        struct timeval tv; 
    8080        char inbuf[BUFSIZE]; 
    81         memset(inbuf, '\0', sizeof(inbuf)); 
    8281 
    8382        FD_SET(d->socket, &d->infds); 
     83        std::string msg; 
    8484        while(isConnected()) { 
    8585                tv.tv_sec = floor(timeout / 1000.0); 
     
    9494                } 
    9595 
    96                 int received = recv(d->socket, inbuf, BUFSIZE - 1, 0); 
    97                 if (received <= 0) { 
     96                int received = BUFSIZE; 
     97                while(received >= (BUFSIZE - 1)){ 
     98                        memset(inbuf, '\0', sizeof(inbuf)); 
     99                        received = recv(d->socket, inbuf, BUFSIZE - 1, 0); 
     100                        if(received > 0){ 
     101                                msg.append(std::string(inbuf)); 
     102                        } 
     103                } 
     104                if (received < 0) { 
    98105                        TelldusCore::MutexLocker locker(&d->mutex); 
    99106                        d->connected = false; 
     
    102109        } 
    103110 
    104         std::string msg(inbuf); 
    105111        return TelldusCore::charToWstring(msg.c_str()); 
    106112} 
     
    109115        TelldusCore::MutexLocker locker(&d->mutex); 
    110116        d->connected = false; 
     117        //TODO somehow signal the socket here? 
    111118} 
    112119 
  • telldus-core/common/Socket_win.cpp

    rffeb0b red502d  
    3838        if (d->hPipe != INVALID_HANDLE_VALUE) { 
    3939                CloseHandle(d->hPipe); 
     40                d->hPipe = 0; 
    4041        } 
    4142        delete d; 
     
    9091        memset(&oOverlap, 0, sizeof(OVERLAPPED)); 
    9192 
    92         d->readEvent = CreateEvent(NULL, TRUE, TRUE, NULL); 
     93        d->readEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
    9394        oOverlap.hEvent = d->readEvent; 
    9495        BOOL fSuccess = false; 
     96        std::wstring returnString; 
     97        bool moreData = true; 
    9598 
    96         memset(&buf, 0, BUFSIZE); 
     99        while(moreData){ 
     100                moreData = false; 
     101                memset(&buf, 0, sizeof(buf)); 
    97102 
    98         ReadFile( d->hPipe, &buf, sizeof(wchar_t)*BUFSIZE, &cbBytesRead, &oOverlap); 
     103                ReadFile( d->hPipe, &buf, sizeof(buf)-sizeof(wchar_t), &cbBytesRead, &oOverlap); 
     104                 
     105                result = WaitForSingleObject(oOverlap.hEvent, timeout); 
     106                 
     107                if(!d->running){ 
     108                        CancelIo(d->hPipe); 
     109                        WaitForSingleObject(oOverlap.hEvent, INFINITE); 
     110                        d->readEvent = 0; 
     111                        CloseHandle(oOverlap.hEvent); 
     112                        return L""; 
     113                } 
    99114 
    100         result = WaitForSingleObject(oOverlap.hEvent, timeout); 
     115                if (result == WAIT_TIMEOUT) { 
     116                        CancelIo(d->hPipe); 
     117                        // Cancel, we still need to cleanup 
     118                } 
     119                fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &cbBytesRead, true); 
    101120         
    102         if(!d->running){ 
    103                 CancelIo(d->hPipe); 
    104                 CloseHandle(d->readEvent); 
    105                 return L""; 
     121                if (!fSuccess) { 
     122                        DWORD err = GetLastError(); 
     123 
     124                        if(err == ERROR_MORE_DATA){ 
     125                                moreData = true; 
     126                        } 
     127                        else{ 
     128                                buf[0] = 0; 
     129                        } 
     130                        if (err == ERROR_BROKEN_PIPE) { 
     131                                d->connected = false; 
     132                        } 
     133                } 
     134                returnString.append(buf); 
    106135        } 
    107  
    108         if (result == WAIT_TIMEOUT) { 
    109                 CancelIo(d->hPipe); 
    110                 CloseHandle(d->readEvent); 
    111                 return L""; 
    112         } 
    113         fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &cbBytesRead, false); 
    114         if (!fSuccess) { 
    115                 DWORD err = GetLastError(); 
    116                 if (err == ERROR_BROKEN_PIPE) { 
    117                         d->connected = false; 
    118                 } 
    119                 buf[0] = 0; 
    120         } 
    121  
    122         CancelIo(d->hPipe); 
    123         CloseHandle(d->readEvent); 
    124         return buf; 
     136        d->readEvent = 0; 
     137        CloseHandle(oOverlap.hEvent); 
     138        return returnString; 
    125139} 
    126140 
     
    130144        DWORD bytesWritten = 0; 
    131145        int result; 
    132         BOOL fSuccess; 
     146        BOOL fSuccess = false; 
    133147 
    134148        memset(&oOverlap, 0, sizeof(OVERLAPPED)); 
    135149 
    136         HANDLE writeEvent = CreateEvent(NULL, TRUE, TRUE, NULL); 
     150        HANDLE writeEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
    137151        oOverlap.hEvent = writeEvent; 
    138152         
    139         WriteFile(d->hPipe, msg.data(), (DWORD)msg.length()*sizeof(wchar_t), &bytesWritten, &oOverlap); 
     153        BOOL writeSuccess = WriteFile(d->hPipe, msg.data(), (DWORD)msg.length()*sizeof(wchar_t), &bytesWritten, &oOverlap); 
     154        result = GetLastError(); 
     155        if (writeSuccess || result == ERROR_IO_PENDING) { 
     156                result = WaitForSingleObject(writeEvent, 500); 
     157                if (result == WAIT_TIMEOUT) { 
     158                        CancelIo(d->hPipe); 
     159                        WaitForSingleObject(oOverlap.hEvent, INFINITE); 
     160                        CloseHandle(writeEvent); 
     161                        CloseHandle(d->hPipe); 
     162                        d->hPipe = 0; 
     163                        d->connected = false; 
     164                        return; 
     165                } 
     166                fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &bytesWritten, TRUE); 
     167        } 
    140168 
    141         result = WaitForSingleObject(writeEvent, 500); 
    142         if (result == WAIT_TIMEOUT) { 
    143                 CancelIo(d->hPipe); 
    144                 CloseHandle(writeEvent); 
    145                 d->connected = false; 
    146                 return; 
    147         } 
    148         fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &bytesWritten, TRUE); 
    149169        CloseHandle(writeEvent); 
    150170        if (!fSuccess) { 
    151                 CancelIo(d->hPipe); 
     171                CloseHandle(d->hPipe); 
     172                d->hPipe = 0; 
    152173                d->connected = false; 
    153174                return;  
  • telldus-core/common/Strings.cpp

    r11dd17 r2ec2da  
    55#include <string> 
    66#include <string.h> 
     7#include <stdio.h> 
    78 
    89#ifdef _WINDOWS 
     
    9293 
    9394std::wstring TelldusCore::intToWstring(int value) { 
     95#ifdef _WINDOWS 
     96        //no stream used 
     97//TODO! Make effective and safe... 
     98        wchar_t numstr[21]; // enough to hold all numbers up to 64-bits 
     99        _itow_s(value, numstr, sizeof(numstr), 10); 
     100        std::wstring newstring(numstr); 
     101        return newstring; 
     102        //return TelldusCore::charToWstring(stdstring.c_str()); 
     103        //std::wstring temp = TelldusCore::charToWstring(stdstring.c_str()); 
     104        //std::wstring temp(stdstring.length(), L' '); 
     105        //std::copy(stdstring.begin(), stdstring.end(), temp.begin()); 
     106        //return temp; 
     107#else 
    94108        std::wstringstream st; 
    95109        st << value; 
    96110        return st.str(); 
     111#endif 
    97112} 
    98113 
    99114std::string TelldusCore::intToString(int value) { 
     115//Not sure if this is neecssary (for ordinary stringstream that is) 
     116#ifdef _WINDOWS 
     117        char numstr[21]; // enough to hold all numbers up to 64-bits 
     118        _itoa_s(value, numstr, sizeof(numstr), 10); 
     119        std::string stdstring(numstr); 
     120        return stdstring; 
     121#else 
    100122        std::stringstream st; 
    101123        st << value; 
    102124        return st.str(); 
    103 } 
     125#endif 
     126} 
     127 
     128/* 
     129std::wstring TelldusCore::intToWStringSafe(int value){ 
     130        #ifdef _WINDOWS 
     131                //no stream used 
     132        //TODO! Make effective and safe... 
     133                char numstr[21]; // enough to hold all numbers up to 64-bits 
     134                itoa(value, numstr, 10); 
     135                std::string stdstring(numstr); 
     136                return TelldusCore::charToWstring(stdstring.c_str()); 
     137                //std::wstring temp = TelldusCore::charToWstring(stdstring.c_str()); 
     138                //std::wstring temp(stdstring.length(), L' '); 
     139                //std::copy(stdstring.begin(), stdstring.end(), temp.begin()); 
     140                //return temp; 
     141        #else 
     142                return TelldusCore::intToWString(value); 
     143        #endif 
     144} 
     145*/ 
    104146 
    105147int TelldusCore::wideToInteger(const std::wstring &input){ 
     
    159201#endif 
    160202} 
     203 
     204std::string TelldusCore::formatf(const char *format, ...) { 
     205        va_list ap; 
     206        va_start(ap, format); 
     207        std::string retval = sformatf(format, ap); 
     208        va_end(ap); 
     209        return retval; 
     210} 
     211 
     212std::string TelldusCore::sformatf(const char *format, va_list ap) { 
     213        //This code is based on code from the Linux man-pages project (man vsprintf) 
     214        int n; 
     215        int size = 100;     /* Guess we need no more than 100 bytes. */ 
     216        char *p, *np; 
     217 
     218        if ((p = (char*)malloc(size)) == NULL) { 
     219                return ""; 
     220        } 
     221 
     222        while (1) { 
     223                /* Try to print in the allocated space. */ 
     224                n = vsnprintf(p, size, format, ap); 
     225 
     226                /* If that worked, return the string. */ 
     227                if (n > -1 && n < size) { 
     228                        std::string retval(p); 
     229                        free(p); 
     230                        return retval; 
     231                } 
     232 
     233                /* Else try again with more space. */ 
     234 
     235                if (n > -1) {   /* glibc 2.1 */ 
     236                        size = n+1; /* precisely what is needed */ 
     237                } else {        /* glibc 2.0 */ 
     238                        size *= 2;  /* twice the old size */ 
     239                } 
     240                if ((np = (char *)realloc (p, size)) == NULL) { 
     241                        free(p); 
     242                        return ""; 
     243                } else { 
     244                        p = np; 
     245                } 
     246        } 
     247} 
  • telldus-core/common/Strings.h

    r11dd17 r716deb  
    33 
    44#include <string> 
     5#include <stdarg.h> 
    56 
    67namespace TelldusCore { 
     
    1112        bool comparei(std::wstring stringA, std::wstring stringB); 
    1213        std::wstring intToWstring(int value); 
     14        //std::wstring intToWStringSafe(int value); 
    1315        std::string intToString(int value); 
    1416        std::string wideToString(const std::wstring &input); 
    1517 
    1618        int wideToInteger(const std::wstring &input); 
     19 
     20        std::string formatf(const char *format, ...); 
     21        std::string sformatf(const char *format, va_list ap); 
    1722} 
    1823 
  • telldus-core/service/CMakeLists.txt

    reb073d r988b44  
    2020        DeviceManager.cpp 
    2121        Event.cpp 
     22        Log.cpp 
    2223        Sensor.cpp 
    2324        Settings.cpp 
    2425        TelldusMain.cpp 
    2526        TellStick.cpp 
     27        Timer.cpp 
    2628        EventUpdateManager.cpp 
    2729) 
     
    3537        ProtocolEverflourish.h 
    3638        ProtocolEverflourish.cpp 
     39        ProtocolFineoffset.h 
     40        ProtocolFineoffset.cpp 
    3741        ProtocolFuhaote.h 
    3842        ProtocolFuhaote.cpp 
     
    4347        ProtocolIkea.h 
    4448        ProtocolIkea.cpp 
     49        ProtocolMandolyn.h 
     50        ProtocolMandolyn.cpp 
    4551        ProtocolNexa.h 
    4652        ProtocolNexa.cpp 
     53        ProtocolOregon.h 
     54        ProtocolOregon.cpp 
    4755        ProtocolRisingSun.h 
    4856        ProtocolRisingSun.cpp 
     
    7381        Event.h 
    7482        EventHandler.h 
     83        EventUpdateManager.h 
     84        Log.h 
    7585        Sensor.h 
    7686        Settings.h 
    7787        TelldusMain.h 
    7888        TellStick.h 
    79         EventUpdateManager.h 
     89        Timer.h 
    8090) 
    8191FIND_PACKAGE(Threads REQUIRED) 
     
    130140                SettingsWinRegistry.cpp 
    131141                TelldusWinService_win.cpp 
     142                Messages.mc 
     143                ${CMAKE_CURRENT_BINARY_DIR}/Messages.rc 
     144                ${CMAKE_CURRENT_BINARY_DIR}/Messages.h 
    132145        ) 
    133146        LIST(APPEND telldus-service_HDRS 
    134147                TelldusWinService_win.h 
    135148        ) 
     149        ADD_CUSTOM_COMMAND( 
     150                OUTPUT Messages.rc Messages.h 
     151                COMMAND mc.exe -u -r ${CMAKE_CURRENT_BINARY_DIR} -h ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc 
     152                DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc 
     153                DEPENDS Messages.rc 
     154                COMMENT "Compiling Messages Resource" 
     155        ) 
     156        INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} ) 
    136157 
    137158ELSE (APPLE) #### Linux #### 
     
    139160        FIND_LIBRARY(CONFUSE_LIBRARY confuse) 
    140161        ADD_DEFINITIONS( -D_CONFUSE ) 
     162        ADD_DEFINITIONS( -D_LINUX ) 
    141163 
    142164        SET( telldus-service_TARGET     telldusd ) 
  • telldus-core/service/ClientCommunicationHandler.cpp

    rad1b18 rb84e8b  
    7777                int deviceId = TelldusCore::Message::takeInt(&msg); 
    7878                (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_TURNON, 0); 
     79 
    7980        } else if (function == L"tdTurnOff") { 
    8081                int deviceId = TelldusCore::Message::takeInt(&msg); 
     
    207208                int reserved = TelldusCore::Message::takeInt(&msg); 
    208209                (*intReturn) = d->deviceManager->sendRawCommand(command, reserved); 
    209                 EventUpdateData *eventData = new EventUpdateData(); 
    210                 eventData->messageType = L"TDRawDeviceEvent"; 
    211                 eventData->controllerId = -1; 
    212                 eventData->eventValue = command; 
    213                 d->deviceUpdateEvent->signal(eventData); 
    214210 
    215211        } else if (function == L"tdConnectTellStickController") { 
  • telldus-core/service/ConnectionListener_win.cpp

    r184d2e r65ef52  
    9292        d->hEvent = CreateEvent(NULL, true, false, NULL); 
    9393        oOverlap.hEvent = d->hEvent; 
     94        bool recreate = true; 
    9495         
    9596        while (1) { 
    96                 hPipe = CreateNamedPipe(  
    97                         (const wchar_t *)d->pipename.c_str(),             // pipe name  
    98                         PIPE_ACCESS_DUPLEX |      // read/write access  
    99                         FILE_FLAG_OVERLAPPED,     //Overlapped mode 
    100                         PIPE_TYPE_MESSAGE |       // message type pipe  
    101                         PIPE_READMODE_MESSAGE |   // message-read mode  
    102                         PIPE_WAIT,                // blocking mode  
    103                         PIPE_UNLIMITED_INSTANCES, // max. instances   
    104                         BUFSIZE,                  // output buffer size  
    105                         BUFSIZE,                  // input buffer size  
    106                         0,                        // client time-out  
    107                         &d->sa);                    // default security attribute  
     97                BOOL alreadyConnected = false; 
     98                if (recreate) { 
     99                        hPipe = CreateNamedPipe( 
     100                                (const wchar_t *)d->pipename.c_str(),             // pipe name 
     101                                PIPE_ACCESS_DUPLEX |      // read/write access 
     102                                FILE_FLAG_OVERLAPPED,     //Overlapped mode 
     103                                PIPE_TYPE_MESSAGE |       // message type pipe 
     104                                PIPE_READMODE_MESSAGE |   // message-read mode 
     105                                PIPE_WAIT,                // blocking mode 
     106                                PIPE_UNLIMITED_INSTANCES, // max. instances 
     107                                BUFSIZE,                  // output buffer size 
     108                                BUFSIZE,                  // input buffer size 
     109                                0,                        // client time-out 
     110                                &d->sa);                    // default security attribute 
    108111 
    109                 if (hPipe == INVALID_HANDLE_VALUE) { 
    110                         //TelldusCore::logMessage("Could not create named pipe");  
    111                         return; 
     112                        if (hPipe == INVALID_HANDLE_VALUE) { 
     113                                return; 
     114                        } 
     115 
     116                        ConnectNamedPipe(hPipe, &oOverlap); 
     117                        alreadyConnected = GetLastError() == ERROR_PIPE_CONNECTED; 
     118                        recreate = false; 
    112119                } 
     120                if(!alreadyConnected){ 
     121                        DWORD result = WaitForSingleObject(oOverlap.hEvent, 1000); 
     122                        if (!d->running) { 
     123                                CancelIo(hPipe); 
     124                                WaitForSingleObject(oOverlap.hEvent, INFINITE); 
     125                                break; 
     126                        } 
     127                         
     128                        if(result == WAIT_TIMEOUT){ 
     129                                //CloseHandle(hPipe); 
     130                                continue; 
     131                        } 
     132                        BOOL connected = GetOverlappedResult(hPipe, &oOverlap, &cbBytesRead, false); 
    113133 
    114                 ConnectNamedPipe(hPipe, &oOverlap); 
    115  
    116                 DWORD result = WaitForSingleObject(oOverlap.hEvent, 1000); 
    117  
    118                 if (!d->running) { 
    119                         break; 
    120                 } 
    121                 if(result == WAIT_TIMEOUT){ 
    122                         CloseHandle(hPipe); 
    123                         continue; 
    124                 } 
    125                 BOOL connected = GetOverlappedResult(hPipe, &oOverlap, &cbBytesRead, false); 
    126  
    127                 if (!connected) { 
    128                         CloseHandle(hPipe); 
    129                         return; 
     134                        if (!connected) { 
     135                                CloseHandle(hPipe); 
     136                                return; 
     137                        } 
    130138                } 
    131139                ConnectionListenerEventData *data = new ConnectionListenerEventData(); 
     140                ResetEvent(oOverlap.hEvent); 
    132141                data->socket = new TelldusCore::Socket(hPipe); 
    133142                d->waitEvent->signal(data); 
     143 
     144                recreate = true; 
    134145        } 
    135146 
  • telldus-core/service/Controller.h

    r99f0b1 r06ac02  
    1717        virtual int firmwareVersion() = 0; 
    1818        virtual int send( const std::string &message ) = 0; 
     19        virtual int reset() = 0; 
    1920 
    2021protected: 
  • telldus-core/service/ControllerManager.cpp

    rbf4589 rb84e8b  
    33#include "Mutex.h" 
    44#include "TellStick.h" 
     5#include "Log.h" 
     6#include "../client/telldus-core.h" 
    57 
    68#include <map> 
     
    120122        } 
    121123} 
     124 
     125void ControllerManager::queryControllerStatus(){ 
     126 
     127        std::list<TellStick *> tellStickControllers; 
     128 
     129        { 
     130                TelldusCore::MutexLocker locker(&d->mutex); 
     131                for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) { 
     132                        TellStick *tellstick = reinterpret_cast<TellStick*>(it->second); 
     133                        if (tellstick) { 
     134                                tellStickControllers.push_back(tellstick); 
     135                        } 
     136                } 
     137        } 
     138 
     139        bool reloadControllers = false; 
     140        std::string noop = "N+"; 
     141        for(std::list<TellStick *>::iterator it = tellStickControllers.begin(); it != tellStickControllers.end(); ++it) { 
     142                int success = (*it)->send(noop); 
     143                if(success == TELLSTICK_ERROR_BROKEN_PIPE){ 
     144                        Log::warning("TellStick query: Error in communication with TellStick, resetting USB"); 
     145                        resetController(*it); 
     146                } 
     147                if(success == TELLSTICK_ERROR_BROKEN_PIPE || success == TELLSTICK_ERROR_NOT_FOUND){ 
     148                        reloadControllers = true; 
     149                } 
     150        } 
     151 
     152        if(!tellStickControllers.size() || reloadControllers){ 
     153                //no tellstick at all found, or controller was reset 
     154                Log::debug("TellStick query: Rescanning USB ports");  //only log as debug, since this will happen all the time if no TellStick is connected 
     155                loadControllers(); 
     156        } 
     157} 
     158 
     159int ControllerManager::resetController(Controller *controller) { 
     160        TellStick *tellstick = reinterpret_cast<TellStick*>(controller); 
     161        if (!tellstick) { 
     162                return true; //not tellstick, nothing to reset at the moment, just return true 
     163        } 
     164        int success = tellstick->reset(); 
     165        deviceInsertedOrRemoved(tellstick->vid(), tellstick->pid(), tellstick->serial(), false); //remove from list and delete 
     166        return success; 
     167} 
  • telldus-core/service/ControllerManager.h

    rcccaf8 r673daf  
    1515 
    1616        Controller *getBestControllerById(int id); 
    17  
    18 protected: 
    1917        void loadControllers(); 
     18        void queryControllerStatus(); 
     19        int resetController(Controller *controller); 
    2020 
    2121private: 
  • telldus-core/service/DeviceManager.cpp

    r1646eb rb84e8b  
    66#include "Strings.h" 
    77#include "Message.h" 
    8 #include "common.h" 
     8#include "Log.h" 
    99 
    1010#include <map> 
     
    433433        else{ 
    434434                Controller *controller = d->controllerManager->getBestControllerById(device->getPreferredControllerId()); 
     435                if(!controller){ 
     436                        Log::warning("Trying to execute action, but no controller found. Rescanning USB ports"); 
     437                        //no controller found, scan for one, and retry once 
     438                        d->controllerManager->loadControllers(); 
     439                        controller = d->controllerManager->getBestControllerById(device->getPreferredControllerId()); 
     440                } 
     441 
    435442                if(controller){ 
    436443                        retval = device->doAction(action, data, controller); 
     444                        if(retval == TELLSTICK_ERROR_BROKEN_PIPE){ 
     445                                Log::warning("Error in communication with TellStick when executing action. Resetting USB"); 
     446                                d->controllerManager->resetController(controller); 
     447                        } 
     448                        if(retval == TELLSTICK_ERROR_BROKEN_PIPE || retval == TELLSTICK_ERROR_NOT_FOUND){ 
     449                                Log::warning("Rescanning USB ports"); 
     450                                d->controllerManager->loadControllers(); 
     451                                controller = d->controllerManager->getBestControllerById(device->getPreferredControllerId()); 
     452                                if(!controller){ 
     453                                        Log::error("No contoller (TellStick) found, even after reset. Giving up."); 
     454                                        return TELLSTICK_ERROR_NOT_FOUND; 
     455                                } 
     456                                retval = device->doAction(action, data, controller); //retry one more time 
     457                        } 
    437458                } else { 
     459                        Log::error("No contoller (TellStick) found after one retry. Giving up."); 
    438460                        return TELLSTICK_ERROR_NOT_FOUND; 
    439461                } 
     
    480502                                } 
    481503                                else if(childType == TELLSTICK_TYPE_SCENE){ 
    482                                         deviceReturnValue = doGroupAction(DeviceManager::getDeviceParameter(deviceId, L"devices", L""), action, data, childType, deviceId, duplicateDeviceIds); //TODO make scenes (and test) infinite loops-safe 
     504                                        deviceReturnValue = doGroupAction(DeviceManager::getDeviceParameter(deviceId, L"devices", L""), action, data, childType, deviceId, duplicateDeviceIds); //TODO make scenes infinite loops-safe 
    483505                                } 
    484506                                else{ 
     
    720742 
    721743        Controller *controller = d->controllerManager->getBestControllerById(-1); 
     744 
     745        if(!controller){ 
     746                //no controller found, scan for one, and retry once 
     747                d->controllerManager->loadControllers(); 
     748                controller = d->controllerManager->getBestControllerById(-1); 
     749        } 
     750 
     751        int retval = TELLSTICK_ERROR_UNKNOWN; 
    722752        if(controller){ 
    723                 return controller->send(TelldusCore::wideToString(command)); 
    724         } 
    725         else{ 
     753                retval = controller->send(TelldusCore::wideToString(command)); 
     754                if(retval == TELLSTICK_ERROR_BROKEN_PIPE){ 
     755                        d->controllerManager->resetController(controller); 
     756                } 
     757                if(retval == TELLSTICK_ERROR_BROKEN_PIPE || retval == TELLSTICK_ERROR_NOT_FOUND){ 
     758                        d->controllerManager->loadControllers(); 
     759                        controller = d->controllerManager->getBestControllerById(-1); 
     760                        if(!controller){ 
     761                                return TELLSTICK_ERROR_NOT_FOUND; 
     762                        } 
     763                        retval = controller->send(TelldusCore::wideToString(command));  //retry one more time 
     764                } 
     765                return retval; 
     766        } else { 
    726767                return TELLSTICK_ERROR_NOT_FOUND; 
    727768        } 
  • telldus-core/service/EventHandler_win.cpp

    r485b1e r65ef52  
    5252 
    5353bool EventHandler::waitForAny() { 
    54         int result = WaitForMultipleObjects(d->eventCount, d->eventArray, FALSE, INFINITE); 
    55  
    56         TelldusCore::MutexLocker locker(&d->mutex); 
    57         if (result == WAIT_TIMEOUT) { 
    58                 return false; 
     54         
     55        while(1){ 
     56                int result = WaitForMultipleObjects(d->eventCount, d->eventArray, FALSE, 1000); 
     57                if (result == WAIT_TIMEOUT) { 
     58                        continue; 
     59                } 
     60                TelldusCore::MutexLocker locker(&d->mutex); 
     61                int eventIndex = result - WAIT_OBJECT_0; 
     62                if (eventIndex >= d->eventCount) { 
     63                        return false; 
     64                } 
     65                return true; 
    5966        } 
    60         int eventIndex = result - WAIT_OBJECT_0; 
    61         if (eventIndex >= d->eventCount) { 
    62                 return false; 
    63         } 
    64         return true; 
    6567} 
  • telldus-core/service/EventUpdateManager.cpp

    rf25ca4 r86554b  
    7474void EventUpdateManager::sendMessageToClients(EventUpdateData *data){ 
    7575 
     76        int connected = 0; 
    7677        for(SocketList::iterator it = d->clients.begin(); it != d->clients.end();){ 
    77  
    7878                if((*it)->isConnected()){ 
    79  
     79                        connected++; 
    8080                        TelldusCore::Message msg; 
    8181 
  • telldus-core/service/Protocol.cpp

    rb92e19 r16a9b8  
    66#include "ProtocolComen.h" 
    77#include "ProtocolEverflourish.h" 
     8#include "ProtocolFineoffset.h" 
    89#include "ProtocolFuhaote.h" 
    910#include "ProtocolGroup.h" 
    1011#include "ProtocolHasta.h" 
    1112#include "ProtocolIkea.h" 
     13#include "ProtocolMandolyn.h" 
    1214#include "ProtocolNexa.h" 
     15#include "ProtocolOregon.h" 
    1316#include "ProtocolRisingSun.h" 
    1417#include "ProtocolSartano.h" 
     
    196199        } else if (TelldusCore::comparei(protocolName, L"yidong")) { 
    197200                parameters.push_back("unit"); 
    198          
     201 
    199202        } else if (TelldusCore::comparei(protocolName, L"group")) { 
    200203                parameters.push_back("devices"); 
    201          
     204 
    202205        }  else if (TelldusCore::comparei(protocolName, L"scene")) { 
    203206                parameters.push_back("devices"); 
     
    210213        std::list<std::string> retval; 
    211214        std::string decoded = ""; 
    212          
     215 
    213216        ControllerMessage dataMsg(fullData); 
    214217        if( TelldusCore::comparei(dataMsg.protocol(), L"arctech") ) { 
     
    232235                } 
    233236        } 
     237        else if(TelldusCore::comparei(dataMsg.protocol(), L"fineoffset") ) { 
     238                decoded = ProtocolFineoffset::decodeData(dataMsg); 
     239                if (decoded != "") { 
     240                        retval.push_back(decoded); 
     241                } 
     242        } 
     243        else if(TelldusCore::comparei(dataMsg.protocol(), L"mandolyn") ) { 
     244                decoded = ProtocolMandolyn::decodeData(dataMsg); 
     245                if (decoded != "") { 
     246                        retval.push_back(decoded); 
     247                } 
     248        } 
     249        else if(TelldusCore::comparei(dataMsg.protocol(), L"oregon") ) { 
     250                decoded = ProtocolOregon::decodeData(dataMsg); 
     251                if (decoded != "") { 
     252                        retval.push_back(decoded); 
     253                } 
     254        } 
    234255        else if(TelldusCore::comparei(dataMsg.protocol(), L"x10") ) { 
    235256                decoded = ProtocolX10::decodeData(dataMsg); 
     
    238259                } 
    239260        } 
    240          
     261 
    241262        return retval; 
    242263} 
  • telldus-core/service/ProtocolNexa.cpp

    ree627e r245864  
    44#include "TellStick.h" 
    55#include "Strings.h" 
    6 #include "common.h" 
    76 
    87int ProtocolNexa::lastArctecCodeSwitchWasTurnOff=0;  //TODO, always removing first turnon now, make more flexible (waveman too) 
  • telldus-core/service/SettingsConfuse.cpp

    rc4ef48 rd7cce5  
    376376                CFG_STR(const_cast<char *>("group"), const_cast<char *>("plugdev"), CFGF_NONE), 
    377377                CFG_STR(const_cast<char *>("deviceNode"), const_cast<char *>("/dev/tellstick"), CFGF_NONE), 
     378                CFG_STR(const_cast<char *>("ignoreControllerConfirmation"), const_cast<char *>("false"), CFGF_NONE), 
    378379                CFG_SEC(const_cast<char *>("device"), device_opts, CFGF_MULTI), 
    379380                CFG_END() 
  • telldus-core/service/SettingsWinRegistry.cpp

    rc36430 r406874  
    11#include "Settings.h" 
     2#include "Strings.h" 
    23#include <Windows.h> 
    34#include <sstream>  
     
    67#include <iostream> 
    78#include <fstream> 
     9#include "common.h" 
    810 
    911#include "../client/telldus-core.h" 
     
    9496        intDeviceId = getNextDeviceId(); 
    9597 
    96         std::wostringstream ssRegPath;  
    97         ssRegPath << d->strRegPathDevice << intDeviceId; 
    98         std::wstring strCompleteRegPath = ssRegPath.str(); 
     98        std::wstring strCompleteRegPath = d->strRegPathDevice; 
     99        strCompleteRegPath.append(TelldusCore::intToWstring(intDeviceId)); 
    99100                 
    100101        if (RegCreateKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, &dwDisp)) { 
     
    123124                DWORD nResult(0); 
    124125 
    125                 long lngStatus = RegQueryValueEx(hk, L"LastUsedId", NULL, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwLength); //(LPBYTE)Buff, &dwLength); 
     126                long lngStatus = RegQueryValueEx(hk, L"LastUsedId", NULL, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwLength); 
    126127 
    127128                if(lngStatus == ERROR_SUCCESS){ 
     
    144145        TelldusCore::MutexLocker locker(&mutex); 
    145146         
    146         std::wostringstream ssRegPath;  
    147         ssRegPath << d->strRegPathDevice << intDeviceId; 
    148         std::wstring strCompleteRegPath = ssRegPath.str(); 
     147        std::wstring strCompleteRegPath = d->strRegPathDevice; 
     148        strCompleteRegPath.append(TelldusCore::intToWstring(intDeviceId)); 
    149149 
    150150        long lngSuccess = RegDeleteKey(d->rootKey, strCompleteRegPath.c_str()); 
     
    158158} 
    159159 
     160std::wstring Settings::getSetting(const std::wstring &strName) const{ 
     161        std::wstring strReturn; 
     162        HKEY hk; 
     163 
     164        std::wstring strCompleteRegPath = d->strRegPath; 
     165        long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk); 
     166                         
     167        if(lnExists == ERROR_SUCCESS){ 
     168                wchar_t* Buff = new wchar_t[intMaxRegValueLength]; 
     169                DWORD dwLength = sizeof(wchar_t)*intMaxRegValueLength; 
     170                long lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); 
     171 
     172                if(lngStatus == ERROR_MORE_DATA){ 
     173                        //The buffer is to small, recreate it 
     174                        delete Buff; 
     175                        Buff = new wchar_t[dwLength]; 
     176                        lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); 
     177                } 
     178                if (lngStatus == ERROR_SUCCESS) { 
     179                        strReturn = Buff; 
     180                } 
     181                delete Buff; 
     182        } 
     183        RegCloseKey(hk); 
     184        return strReturn; 
     185} 
     186 
    160187std::wstring Settings::getStringSetting(int intDeviceId, const std::wstring &name, bool parameter) const { 
    161188        std::wstring strReturn; 
    162189        HKEY hk; 
    163190 
    164         std::wostringstream ssRegPath;  
    165         ssRegPath << d->strRegPathDevice << intDeviceId; 
    166         std::wstring strCompleteRegPath = ssRegPath.str(); 
     191        std::wstring strCompleteRegPath = d->strRegPathDevice; 
     192        strCompleteRegPath.append(TelldusCore::intToWstring(intDeviceId)); 
    167193        long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk); 
    168194                         
     
    192218        int ret = TELLSTICK_SUCCESS; 
    193219                 
    194         std::wostringstream ssRegPath;  
    195         ssRegPath << d->strRegPathDevice << intDeviceId; 
    196         std::wstring strCompleteRegPath = ssRegPath.str(); 
     220        std::wstring bla = TelldusCore::intToWstring(intDeviceId); 
     221        std::wstring strCompleteRegPath = d->strRegPathDevice; 
     222        strCompleteRegPath.append(bla); 
    197223        long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk); 
    198224                                 
     
    224250        HKEY hk; 
    225251 
    226         std::wostringstream ssRegPath;  
    227         ssRegPath << d->strRegPathDevice << intDeviceId; 
    228         std::wstring strCompleteRegPath = ssRegPath.str(); 
     252        std::wstring strCompleteRegPath =  d->strRegPathDevice; 
     253        strCompleteRegPath.append(TelldusCore::intToWstring(intDeviceId)); 
    229254        long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk); 
    230255        if (lnExists == ERROR_SUCCESS) { 
  • telldus-core/service/TellStick.h

    r05a816 r06ac02  
    3030        virtual int firmwareVersion(); 
    3131        virtual int pid() const; 
     32        virtual int vid() const; 
     33        virtual std::string serial() const; 
     34 
    3235        bool isOpen() const; 
    3336        bool isSameAsDescriptor(const TellStickDescriptor &d) const; 
     37        virtual int reset(); 
    3438        virtual int send( const std::string &message ); 
    3539        bool stillConnected() const; 
  • telldus-core/service/TellStick_ftd2xx.cpp

    r777256 r915d47  
    1111// 
    1212#include "TellStick.h" 
     13#include "common.h" 
    1314#include "Mutex.h" 
     15#include "Settings.h" 
    1416#include "Strings.h" 
     17#include "Log.h" 
    1518#include "../client/telldus-core.h" 
    1619#include <string.h> 
     
    2124class TellStick::PrivateData { 
    2225public: 
    23         bool open, running; 
     26        bool open, running, ignoreControllerConfirmation; 
    2427        int vid, pid, fwVersion; 
    2528        std::string serial, message; 
     
    5457        d->fwVersion = 0; 
    5558        d->serial = td.serial; 
     59        Settings set; 
     60        d->ignoreControllerConfirmation = set.getSetting(L"ignoreControllerConfirmation")==L"true"; 
    5661 
    5762        char *tempSerial = new char[td.serial.size()+1]; 
     
    6267        FT_SetVIDPID(td.vid, td.pid); 
    6368#endif 
     69        Log::notice("Connecting to TellStick (%X/%X) with serial %s", d->vid, d->pid, d->serial.c_str()); 
    6470        FT_STATUS ftStatus = FT_OpenEx(tempSerial, FT_OPEN_BY_SERIAL_NUMBER, &d->ftHandle); 
    6571        delete tempSerial; 
     
    7783                } 
    7884                this->start(); 
     85        } else { 
     86                Log::warning("Failed to open TellStick"); 
    7987        } 
    8088} 
    8189 
    8290TellStick::~TellStick() { 
     91        Log::warning("Disconnected TellStick (%X/%X) with serial %s", d->vid, d->pid, d->serial.c_str()); 
    8392        if (d->running) { 
    8493                TelldusCore::MutexLocker locker(&d->mutex); 
     
    107116int TellStick::pid() const { 
    108117        return d->pid; 
     118} 
     119 
     120int TellStick::vid() const { 
     121        return d->vid; 
     122} 
     123 
     124std::string TellStick::serial() const { 
     125        return d->serial; 
    109126} 
    110127 
     
    145162} 
    146163 
     164int TellStick::reset(){ 
     165#ifndef _WINDOWS 
     166        return TELLSTICK_SUCCESS; //nothing to be done on other platforms 
     167#else 
     168        int success = FT_CyclePort( d->ftHandle ); 
     169        if(success == FT_OK){ 
     170                return TELLSTICK_SUCCESS; 
     171        } 
     172        return TELLSTICK_ERROR_UNKNOWN; 
     173#endif 
     174} 
     175 
    147176void TellStick::run() { 
    148177        d->running = true; 
     
    187216                return TELLSTICK_ERROR_NOT_FOUND; 
    188217        } 
    189         bool c = true; 
    190  
     218         
    191219        //This lock does two things 
    192220        // 1 Prevents two calls from different threads to this function 
     
    206234        ftStatus = FT_Write(d->ftHandle, tempMessage, (DWORD)strMessage.length(), &bytesWritten); 
    207235        free(tempMessage); 
    208  
    209         while(c) { 
     236         
     237        if(ftStatus != FT_OK){ 
     238                Log::debug("Broken pipe on send"); 
     239                return TELLSTICK_ERROR_BROKEN_PIPE; 
     240        } 
     241 
     242        if(strMessage.compare("N+") == 0 && ((pid() == 0x0C31 && firmwareVersion() < 5) || (pid() == 0x0C30 && firmwareVersion() < 6))){ 
     243                //these firmware versions doesn't implement ack to noop, just check that the noop can be sent correctly 
     244                return TELLSTICK_SUCCESS; 
     245        } 
     246        if(d->ignoreControllerConfirmation){ 
     247                //wait for TellStick to finish its air-sending 
     248                msleep(1000); 
     249                return TELLSTICK_SUCCESS; 
     250        } 
     251 
     252        while(1) { 
    210253                ftStatus = FT_Read(d->ftHandle,&in,1,&bytesRead); 
    211254                if (ftStatus == FT_OK) { 
    212255                        if (bytesRead == 1) { 
    213256                                if (in == '\n') { 
    214                                         break; 
     257                                        return TELLSTICK_SUCCESS; 
     258                                } else { 
     259                                        continue; 
    215260                                } 
    216261                        } else { //Timeout 
    217                                 c = false; 
     262                                return TELLSTICK_ERROR_COMMUNICATION; 
    218263                        } 
    219264                } else { //Error 
    220                         c = false; 
    221                 } 
    222         } 
    223  
    224         if (!c) { 
    225                 return TELLSTICK_ERROR_COMMUNICATION; 
    226         } 
    227         return TELLSTICK_SUCCESS; 
     265                        Log::debug("Broken pipe on read"); 
     266                        return TELLSTICK_ERROR_BROKEN_PIPE; 
     267                } 
     268        } 
    228269} 
    229270 
  • telldus-core/service/TellStick_libftdi.cpp

    r894997 rd32633  
    1919#include "Thread.h" 
    2020#include "Mutex.h" 
     21#include "Log.h" 
     22#include "Settings.h" 
    2123#include "Strings.h" 
    2224#include "common.h" 
     
    3234class TellStick::PrivateData { 
    3335public: 
    34         bool open; 
     36        bool open, ignoreControllerConfirmation; 
    3537        int vid, pid, fwVersion; 
    3638        std::string serial, message; 
     
    5254        d->running = false; 
    5355 
     56        Settings set; 
     57        d->ignoreControllerConfirmation = set.getSetting(L"ignoreControllerConfirmation")==L"true"; 
     58 
    5459        ftdi_init(&d->ftHandle); 
    5560        ftdi_set_interface(&d->ftHandle, INTERFACE_ANY); 
    5661 
     62        Log::notice("Connecting to TellStick (%X/%X) with serial %s", d->vid, d->pid, d->serial.c_str()); 
    5763        int ret = ftdi_usb_open_desc(&d->ftHandle, td.vid, td.pid, NULL, td.serial.c_str()); 
    5864        if (ret < 0) { 
     
    6369        ftdi_usb_reset( &d->ftHandle ); 
    6470        ftdi_disable_bitbang( &d->ftHandle ); 
     71        ftdi_set_latency_timer(&d->ftHandle, 16); 
    6572 
    6673        if (d->open) { 
     
    7279                } 
    7380                this->start(); 
     81        } else { 
     82                Log::warning("Failed to open TellStick"); 
    7483        } 
    7584} 
    7685 
    7786TellStick::~TellStick() { 
     87        Log::warning("Disconnected TellStick (%X/%X) with serial %s", d->vid, d->pid, d->serial.c_str()); 
    7888        if (d->running) { 
    7989                stop(); 
     
    93103int TellStick::pid() const { 
    94104        return d->pid; 
     105} 
     106 
     107int TellStick::vid() const { 
     108        return d->vid; 
     109} 
     110 
     111std::string TellStick::serial() const { 
     112        return d->serial; 
    95113} 
    96114 
     
    131149} 
    132150 
     151int TellStick::reset(){ 
     152        int success = ftdi_usb_reset( &d->ftHandle ); 
     153        if(success < 0){ 
     154                return TELLSTICK_ERROR_UNKNOWN; //-1 = FTDI reset failed, -2 = USB device unavailable 
     155        } 
     156        return TELLSTICK_SUCCESS; 
     157} 
     158 
    133159void TellStick::run() { 
    134160        int dwBytesRead = 0; 
     
    187213                c = false; 
    188214        } else if(ret != strMessage.length()) { 
    189                 fprintf(stderr, "weird send length? retval %i instead of %d\n", 
    190                 ret, (int)strMessage.length()); 
     215                Log::debug("Weird send length? retval %i instead of %d\n", ret, (int)strMessage.length()); 
    191216        } 
    192217 
    193218        delete[] tempMessage; 
    194219 
    195         int retrycnt = 200; 
     220        if(!c){ 
     221                Log::debug("Broken pipe on send"); 
     222                return TELLSTICK_ERROR_BROKEN_PIPE; 
     223        } 
     224 
     225        if(strMessage.compare("N+") == 0 && ((pid() == 0x0C31 && firmwareVersion() < 5) || (pid() == 0x0C30 && firmwareVersion() < 6))){ 
     226                //these firmware versions doesn't implement ack to noop, just check that the noop can be sent correctly 
     227                return TELLSTICK_SUCCESS; 
     228        } 
     229 
     230        if(d->ignoreControllerConfirmation){ 
     231                //allow TellStick to finish its air-sending 
     232                msleep(1000); 
     233                return TELLSTICK_SUCCESS; 
     234        } 
     235 
     236        int retrycnt = 250; 
    196237        unsigned char in; 
    197         while(c && --retrycnt) { 
     238        while(--retrycnt) { 
    198239                ret = ftdi_read_data( &d->ftHandle, &in, 1); 
    199240                if (ret > 0) { 
    200241                        if (in == '\n') { 
    201                                 break; 
     242                                return TELLSTICK_SUCCESS; 
    202243                        } 
    203244                } else if(ret == 0) { // No data available 
    204245                        usleep(100); 
    205246                } else { //Error 
    206                         c = false; 
    207                 } 
    208         } 
    209         if (!retrycnt) { 
    210                 c = false; 
    211         } 
    212         if (!c) { 
    213                 return TELLSTICK_ERROR_COMMUNICATION; 
    214         } 
    215         return TELLSTICK_SUCCESS; 
     247                        Log::debug("Broken pipe on read"); 
     248                        return TELLSTICK_ERROR_BROKEN_PIPE; 
     249                } 
     250        } 
     251 
     252        return TELLSTICK_ERROR_COMMUNICATION; 
    216253} 
    217254 
  • telldus-core/service/TelldusMain.cpp

    rcccaf8 re2e9ba  
    77#include "ControllerListener.h" 
    88#include "EventUpdateManager.h" 
     9#include "Timer.h" 
     10#include "Log.h" 
    911 
    1012#include <stdio.h> 
     
    4042        EventRef clientEvent = d->eventHandler.addEvent(); 
    4143        EventRef dataEvent = d->eventHandler.addEvent(); 
     44        EventRef janitor = d->eventHandler.addEvent(); //Used for regular cleanups 
     45        Timer supervisor(janitor); //Tells the janitor to go back to work 
     46        supervisor.setInterval(60); //Once every minute 
     47        supervisor.start(); 
    4248 
    4349        ControllerManager controllerManager(dataEvent.get()); 
     
    102108                        } 
    103109                } 
     110                if (janitor->isSignaled()) { 
     111                        //Clear all of them if there is more than one 
     112                        while(janitor->isSignaled()) { 
     113                                janitor->popSignal(); 
     114                        } 
     115                        controllerManager.queryControllerStatus(); 
     116                } 
    104117        } 
     118 
     119        supervisor.stop(); 
    105120} 
    106121 
  • telldus-core/service/TelldusWinService_win.cpp

    r2697fd r986240  
    11#include "TelldusWinService_win.h" 
    22#include "TelldusMain.h" 
     3#include "Log.h" 
    34 
    45#include <Dbt.h> 
     
    112113        TelldusWinService instance; 
    113114 
     115        //Enable debug if we hade this supplied 
     116        for(unsigned int i = 1; i < argc; ++i) { 
     117                if (wcscmp(argv[i], L"--debug") == 0) { 
     118                        Log::setDebug(); 
     119                } 
     120        } 
     121 
    114122        // initialise service status 
    115123        instance.serviceStatus.dwServiceType = SERVICE_WIN32; 
     
    141149                HDEVNOTIFY deviceNotificationHandle = RegisterDeviceNotificationW(instance.serviceStatusHandle, &devInterface, DEVICE_NOTIFY_SERVICE_HANDLE); 
    142150 
     151                Log::notice("TelldusService started"); 
     152 
    143153                //Start our main-loop 
    144154                instance.tm->start(); 
     155 
     156                Log::notice("TelldusService stopping"); 
     157                Log::destroy(); 
    145158                 
    146159                // service was stopped 
  • telldus-core/service/main_mac.cpp

    r83aa0d r727287  
    11#include "TelldusMain.h" 
     2#include "Log.h" 
    23#include <signal.h> 
    3 #include <stdio.h> 
    44 
    55TelldusMain tm; 
    66 
    77void shutdownHandler(int onSignal) { 
    8         printf("Shutting down\n"); 
     8        Log::notice("Shutting down"); 
    99        tm.stop(); 
    1010} 
    1111 
    1212void sigpipeHandler(int onSignal) { 
    13         printf("SIGPIPE received\n"); 
     13        Log::notice("SIGPIPE received"); 
    1414} 
    1515 
     
    2020        signal(SIGPIPE, sigpipeHandler); 
    2121 
     22        Log::notice("telldusd started"); 
    2223        tm.start(); 
    23         printf("telldusd stopped gracefully\n"); 
     24        Log::notice("telldusd stopped gracefully"); 
     25 
     26        Log::destroy(); 
    2427        return 0; 
    2528} 
  • telldus-core/service/main_unix.cpp

    r55f49a r83fb47  
    55#include <stdlib.h> 
    66#include <unistd.h> 
    7 #include <syslog.h> 
    87#include <sys/stat.h> 
    98#include <errno.h> 
     
    1312#include "Settings.h" 
    1413#include "Strings.h" 
     14#include "Log.h" 
    1515 
    1616#define DAEMON_NAME "telldusd" 
     
    2222        switch(sig) { 
    2323                case SIGHUP: 
    24                         syslog(LOG_WARNING, "Received SIGHUP signal."); 
     24                        Log::warning("Received SIGHUP signal."); 
    2525                        break; 
    2626                case SIGTERM: 
    2727                case SIGINT: 
    28                         syslog(LOG_WARNING, "Received SIGTERM or SIGINT signal."); 
    29                         syslog(LOG_WARNING, "Shutting down"); 
     28                        Log::warning("Received SIGTERM or SIGINT signal."); 
     29                        Log::warning("Shutting down"); 
    3030                        tm.stop(); 
    3131                        break; 
    3232                case SIGPIPE: 
    33                         syslog(LOG_WARNING, "Received SIGPIPE signal."); 
     33                        Log::warning("Received SIGPIPE signal."); 
    3434                        break; 
    3535                default: 
    36                         syslog(LOG_WARNING, "Unhandled signal (%d) %s", sig, strsignal(sig)); 
     36                        Log::warning("Unhandled signal (%d) %s", sig, strsignal(sig)); 
    3737                        break; 
    3838        } 
     
    4747                if (strcmp(argv[i], "--nodaemon") == 0) { 
    4848                        deamonize = false; 
    49                 } 
    50                 if (strcmp(argv[i], "--help") == 0) { 
     49                        Log::setLogOutput(Log::StdOut); 
     50                } else if (strcmp(argv[i], "--help") == 0) { 
    5151                        printf("Telldus TellStick background service\n\nStart with --nodaemon to not run as daemon\n\n"); 
    5252                        printf("Report bugs to <info.tech@telldus.com>\n"); 
    5353                        exit(EXIT_SUCCESS); 
    54                 } 
    55                 if (strcmp(argv[i], "--version") == 0) { 
     54                } else if (strcmp(argv[i], "--version") == 0) { 
    5655                        printf("telldusd " VERSION "\n\n"); 
    5756                        printf("Copyright (C) 2011 Telldus Technologies AB\n\n"); 
    5857                        printf("Written by Micke Prag <micke.prag@telldus.se>\n"); 
    5958                        exit(EXIT_SUCCESS); 
     59                } else { 
     60                        printf("Unknown option %s\n", argv[i]); 
     61                        exit(EXIT_FAILURE); 
    6062                } 
    6163        } 
     
    7779                                fclose(fd); 
    7880                        } else { 
    79                                 syslog(LOG_ERR, "Could not open pid file %s: %s", PID_FILE, strerror(errno)); 
     81                                Log::error("Could not open pid file %s: %s", PID_FILE, strerror(errno)); 
    8082                                exit(EXIT_FAILURE); 
    8183                        } 
     
    8486        } 
    8587 
    86         setlogmask(LOG_UPTO(LOG_INFO)); 
    87         openlog(DAEMON_NAME, LOG_CONS, LOG_USER); 
    88  
    89         syslog(LOG_NOTICE, "%s daemon starting up", DAEMON_NAME); 
     88        Log::notice("%s daemon starting up", DAEMON_NAME); 
    9089 
    9190        if (deamonize) { 
     
    116115                        setgid(grp->gr_gid); 
    117116                } else { 
    118                         syslog(LOG_WARNING, "Group %s could not be found", group.c_str()); 
     117                        Log::warning("Group %s could not be found", group.c_str()); 
    119118                        exit(EXIT_FAILURE); 
    120119                } 
     
    123122                        setuid( pw->pw_uid ); 
    124123                } else { 
    125                         syslog(LOG_WARNING, "User %s could not be found", user.c_str()); 
     124                        Log::warning("User %s could not be found", user.c_str()); 
    126125                        exit(EXIT_FAILURE); 
    127126                } 
     
    140139        tm.start(); 
    141140 
    142         syslog(LOG_NOTICE, "%s daemon exited", DAEMON_NAME); 
     141        Log::notice("%s daemon exited", DAEMON_NAME); 
    143142        exit(EXIT_SUCCESS); 
    144143} 
  • telldus-core/service/tellstick.conf

    rbea7b7 rd7cce5  
    11user = "nobody" 
    22group = "plugdev" 
     3ignoreControllerConfirmation = "false" 
    34device { 
    45  id = 1 
  • telldus-core/tdadmin/05-tellstick.rules

    r80dfac rcd6e59  
    1 ID_VENDOR_ID=="1781", SUBSYSTEM=="usb", ACTION=="add", MODE="664", GROUP="plugdev" RUN+="${CMAKE_INSTALL_PREFIX}/share/telldus-core/helpers/udev.sh" 
    2 ID_VENDOR_ID=="1781", SUBSYSTEM=="usb", ACTION=="remove" RUN+="${CMAKE_INSTALL_PREFIX}/share/telldus-core/helpers/udev.sh" 
     1ATTRS{idVendor}=="1781", SUBSYSTEM=="usb", ACTION=="add", MODE="664", GROUP="plugdev" RUN+="${CMAKE_INSTALL_PREFIX}/share/telldus-core/helpers/udev.sh" 
     2ENV{ID_VENDOR_ID}=="1781", SUBSYSTEM=="usb", ACTION=="remove" RUN+="${CMAKE_INSTALL_PREFIX}/share/telldus-core/helpers/udev.sh" 
    33 
  • telldus-core/tdtool/main.cpp

    raf6cc7 r5190c4  
    33#include <stdlib.h> 
    44#include <string.h> 
     5#include <ctime> 
    56#include "../client/telldus-core.h" 
    67 
     
    2223        printf("\n"); 
    2324        printf("       --list (-l short option)\n"); 
    24         printf("             List currently configured devices.\n"); 
     25        printf("             List currently configured devices and all discovered sensors.\n"); 
    2526        printf("\n"); 
    2627        printf("       --help (-h short option)\n"); 
     
    7879 
    7980void print_device( int index ) { 
     81        tdInit(); 
    8082        int intId = tdGetDeviceId(index); 
    8183        char *name = tdGetName(intId); 
     
    102104} 
    103105 
    104 void list_devices() { 
     106int list_devices() { 
     107        tdInit(); 
    105108        int intNum = tdGetNumberOfDevices(); 
    106109        if (intNum < 0) { 
     
    108111                fprintf(stderr, "Error fetching devices: %s\n", errorString); 
    109112                tdReleaseString(errorString); 
    110                 return; 
     113                return intNum; 
    111114        } 
    112115        printf("Number of devices: %i\n", intNum); 
     
    116119                i++; 
    117120        } 
     121 
     122        int DATA_LENGTH = 20; 
     123        char protocol[DATA_LENGTH], model[DATA_LENGTH]; 
     124        int sensorId = 0, dataTypes = 0; 
     125 
     126        int sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes); 
     127        if(sensorStatus == 0){ 
     128                printf("\nSENSORS:\n%-20s\t%-20s\t%-5s\t%-5s\t%-8s\t%-20s\n", "PROTOCOL", "MODEL", "ID", "TEMP", "HUMIDITY", "LAST UPDATED"); 
     129        } 
     130        while(sensorStatus == 0){ 
     131                sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes); 
     132 
     133                char tempvalue[DATA_LENGTH]; 
     134                tempvalue[0] = 0; 
     135                char humidityvalue[DATA_LENGTH]; 
     136                humidityvalue[0] = 0; 
     137                char timeBuf[80]; 
     138                time_t timestamp = 0; 
     139 
     140                if (dataTypes & TELLSTICK_TEMPERATURE) { 
     141                        tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp); 
     142                        strcat(tempvalue, "°"); 
     143                        strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); 
     144                } 
     145 
     146                if (dataTypes & TELLSTICK_HUMIDITY) { 
     147                        tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp); 
     148                        strcat(humidityvalue, "%"); 
     149                        strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); 
     150                } 
     151                printf("%-20s\t%-20s\t%-5i\t%-5s\t%-8s\t%-20s\n", protocol, model, sensorId, tempvalue, humidityvalue, timeBuf); 
     152 
     153                printf("\n"); 
     154        } 
     155        if(sensorStatus != TELLSTICK_ERROR_DEVICE_NOT_FOUND){ 
     156                char *errorString = tdGetErrorString(sensorStatus); 
     157                fprintf(stderr, "Error fetching sensors: %s\n", errorString); 
     158                tdReleaseString(errorString); 
     159                return sensorStatus; 
     160        } 
     161        return TELLSTICK_SUCCESS; 
    118162} 
    119163 
    120164int find_device( char *device ) { 
     165        tdInit(); 
    121166        int deviceId = atoi(device); 
    122167        if (deviceId == 0) { //Try to find the id from the name 
     
    138183} 
    139184 
    140 void switch_device( bool turnOn, char *device ) { 
     185int switch_device( bool turnOn, char *device ) { 
     186        tdInit(); 
    141187        int deviceId = find_device( device ); 
    142188        if (deviceId == 0) { 
    143189                printf("Device '%s', not found!\n", device); 
    144                 return; 
     190                return TELLSTICK_ERROR_DEVICE_NOT_FOUND; 
    145191        } 
    146192 
     
    159205        printf(" - %s\n", errorString); 
    160206        tdReleaseString(errorString); 
    161 } 
    162  
    163 void dim_device( char *device, int level ) { 
     207        return retval; 
     208} 
     209 
     210int dim_device( char *device, int level ) { 
     211        tdInit(); 
    164212        int deviceId = find_device( device ); 
    165213        if (deviceId == 0) { 
    166214                printf("Device '%s', not found!\n", device); 
    167                 return; 
     215                return TELLSTICK_ERROR_DEVICE_NOT_FOUND; 
    168216        } 
    169217        if (level < 0 || level > 255) { 
    170218                printf("Level %i out of range!\n", level); 
    171                 return; 
     219                return TELLSTICK_ERROR_SYNTAX; 
    172220        } 
    173221 
     
    178226        tdReleaseString(name); 
    179227        tdReleaseString(errorString); 
    180 } 
    181  
    182 void bell_device( char *device ) { 
     228        return retval; 
     229} 
     230 
     231int bell_device( char *device ) { 
     232        tdInit(); 
    183233        int deviceId = find_device( device ); 
    184234        if (deviceId == 0) { 
    185235                printf("Device '%s', not found!\n", device); 
    186                 return; 
     236                return TELLSTICK_ERROR_DEVICE_NOT_FOUND; 
    187237        } 
    188238 
     
    193243        tdReleaseString(name); 
    194244        tdReleaseString(errorString); 
    195 } 
    196  
    197 void learn_device( char *device ) { 
     245        return retval; 
     246} 
     247 
     248int learn_device( char *device ) { 
     249        tdInit(); 
    198250        int deviceId = find_device( device ); 
    199251        if (deviceId == 0) { 
    200252                printf("Device '%s', not found!\n", device); 
    201                 return; 
     253                return TELLSTICK_ERROR_DEVICE_NOT_FOUND; 
    202254        } 
    203255 
     
    208260        tdReleaseString(name); 
    209261        tdReleaseString(errorString); 
    210 } 
    211  
    212 void send_raw_command( char *command ) { 
     262        return retval; 
     263} 
     264 
     265int send_raw_command( char *command ) { 
     266        tdInit(); 
    213267        const int MAX_LENGTH = 100; 
    214268        char msg[MAX_LENGTH]; 
     
    222276                if (fd == NULL) { 
    223277                        printf("Error opening file %s\n", command); 
    224                         return; 
     278                        return TELLSTICK_ERROR_UNKNOWN; 
    225279                } 
    226280                fgets(msg, MAX_LENGTH, fd); 
     
    231285        printf("Sending raw command: %s\n", errorString); 
    232286        tdReleaseString(errorString); 
     287        return retval; 
    233288} 
    234289 
     
    254309        if (argc < 2) { 
    255310                print_usage( argv[0] ); 
    256                 return -1; 
    257         } 
    258  
    259         while ( (optch = getopt_long(argc,argv,optstring,long_opts,&longindex)) != -1 ) 
     311                return -TELLSTICK_ERROR_SYNTAX; 
     312        } 
     313 
     314        int returnSuccess = 0; 
     315        while ( (optch = getopt_long(argc,argv,optstring,long_opts,&longindex)) != -1 ){ 
     316                int success = 0; 
    260317                switch (optch) { 
    261318                        case 'b' : 
    262                                 bell_device( &optarg[0] ); 
     319                                success = bell_device( &optarg[0] ); 
    263320                                break; 
    264321                        case 'd' : 
    265322                                if (level >= 0) { 
    266                                         dim_device( &optarg[0], level ); 
     323                                        success = dim_device( &optarg[0], level ); 
     324                                        break; 
    267325                                } 
     326                                printf("Dim level missing or incorrect value.\n"); 
     327                                success = TELLSTICK_ERROR_SYNTAX; 
    268328                                break; 
    269329                        case 'f' : 
    270                                 switch_device(false, &optarg[0]); 
     330                                success = switch_device(false, &optarg[0]); 
    271331                                break; 
    272332                        case 'h' : 
    273333                                print_usage( argv[0] ); 
    274                                 break; 
     334                                success = TELLSTICK_SUCCESS; 
    275335                        case 'i' : 
    276336                                print_version( ); 
    277                                 break; 
     337                                success = TELLSTICK_SUCCESS; 
    278338                        case 'l' : 
    279                                 list_devices(); 
     339                                success = list_devices(); 
    280340                                break; 
    281341                        case 'n' : 
    282                                 switch_device(true, &optarg[0]); 
     342                                success = switch_device(true, &optarg[0]); 
    283343                                break; 
    284344                        case 'e' : 
    285                                 learn_device(&optarg[0]); 
     345                                success = learn_device(&optarg[0]); 
    286346                                break; 
    287347                        case 'r' : 
    288                                 send_raw_command(&optarg[0]); 
     348                                success = send_raw_command(&optarg[0]); 
    289349                                break; 
    290350                        case 'v' : 
     
    293353                        default : 
    294354                                print_usage( argv[0] ); 
    295                                 return -1; 
    296                 } 
    297  
     355                                success = TELLSTICK_ERROR_SYNTAX; 
     356                } 
     357                if(success != TELLSTICK_SUCCESS){ 
     358                        returnSuccess = success;  //return last error message 
     359                } 
     360        } 
    298361        tdClose(); //Cleaning up 
    299         return 0; 
    300 } 
     362        return -returnSuccess; 
     363} 
  • telldus-gui/Plugins/Live/LiveMessageToken.cpp

    raf2ae0 r06bf1a  
    1010        valueType = String; 
    1111        stringVal = value; 
     12} 
     13 
     14LiveMessageToken::LiveMessageToken(int value) { 
     15        valueType = Int; 
     16        intVal = value; 
    1217} 
    1318 
     
    123128} 
    124129 
    125 int LiveMessageTokenScriptWrapper::getInt(const QString &key, int defaultValue) { 
     130int LiveMessageTokenScriptWrapper::getInt(const QString &key, int defaultValue) const { 
    126131        if (p_token.valueType != LiveMessageToken::Dictionary) { 
    127132                return defaultValue; 
     
    131136        } 
    132137        return p_token.dictVal[key].intVal; 
     138} 
     139 
     140QString LiveMessageTokenScriptWrapper::getString(const QString &key, const QString &defaultValue) const { 
     141        if (p_token.valueType != LiveMessageToken::Dictionary) { 
     142                return defaultValue; 
     143        } 
     144        if (!p_token.dictVal.contains(key)) { 
     145                return defaultValue; 
     146        } 
     147        return p_token.dictVal[key].stringVal; 
    133148} 
    134149 
  • telldus-gui/Plugins/Live/LiveMessageToken.h

    rb2212c r06bf1a  
    1313        LiveMessageToken(); 
    1414        LiveMessageToken(const QString &value); 
     15        LiveMessageToken(int value); 
    1516        QByteArray toByteArray() const; 
    1617        static LiveMessageToken parseToken(const QByteArray &string, int* start); 
     
    3536        void add(LiveMessageTokenScriptWrapper *token); 
    3637 
    37         int getInt(const QString &key, int defaultValue = 0); 
     38        int getInt(const QString &key, int defaultValue = 0) const; 
     39        QString getString(const QString &key, const QString &defaultValue = "") const; 
    3840 
    3941        int intVal() const; 
     
    4143        void set(const QString &key, int value); 
    4244        void set(const QString &key, const QString &value); 
    43          
     45 
    4446private: 
    4547        LiveMessageToken p_token; 
  • telldus-gui/Plugins/Live/LiveObject.cpp

    r35d694 r5bb60a  
    1414 
    1515        QSslSocket *socket; 
    16         QTimer timer; 
     16        QTimer pingTimer, pongTimer; 
    1717        bool registered; 
    1818        QUrl registerUrl; 
     
    4747        connect(d->socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &))); 
    4848 
    49         d->timer.setInterval(60000); //Once a minute 
    50         connect(&d->timer, SIGNAL(timeout()), this, SLOT(pingServer())); 
     49        d->pingTimer.setInterval(120000); //Two minutes 
     50        d->pongTimer.setInterval(360000); //Six minutes 
     51        d->pongTimer.setSingleShot(true); 
     52        connect(&d->pingTimer, SIGNAL(timeout()), this, SLOT(pingServer())); 
     53        connect(&d->pongTimer, SIGNAL(timeout()), this, SLOT(pongTimeout())); 
    5154 
    5255        d->manager = new QNetworkAccessManager(this); 
     
    103106                return; 
    104107        } 
     108        d->pongTimer.stop(); 
     109        d->pongTimer.start(); 
    105110 
    106111        if (msg->name() == "") { 
     
    123128                emit notRegistered(); 
    124129                emit errorChanged("Not registered"); 
     130        } else if (msg->name() == "command") { 
     131                if (msg->arg(0).valueType == LiveMessageToken::Dictionary && msg->arg(0).dictVal.contains("ACK")) { 
     132                        int ack = msg->arg(0).dictVal["ACK"].intVal; 
     133                        LiveMessage msg("ACK"); 
     134                        msg.append(ack); 
     135                        this->sendMessage(msg); 
     136                } 
     137                emit messageReceived(msg.data()); 
    125138        } else { 
    126139                emit messageReceived(msg.data()); 
     
    133146        d->serverList.clear(); 
    134147        QUrl url(TELLDUS_LIVE_URI); 
    135         QPair<QString, QString> version("protocolVersion", "1"); 
     148        QPair<QString, QString> version("protocolVersion", "2"); 
    136149        QList<QPair<QString, QString> > query; 
    137150        query.append(version); 
     
    157170        d->socket->write(msg.toByteArray()); 
    158171        d->socket->flush(); 
     172        d->pingTimer.stop(); 
     173        d->pingTimer.start(); 
    159174} 
    160175 
     
    171186        d->uuid = settings.value("Live/UUID", "").toString(); 
    172187 
    173         d->timer.start(); //For pings 
     188        d->pingTimer.start(); //For pings 
     189        d->pongTimer.start(); //For pongs 
    174190        LiveMessage msg("Register"); 
    175191 
     
    189205 
    190206void LiveObject::p_disconnected() { 
    191         d->timer.stop(); 
     207        d->pingTimer.stop(); 
     208        d->pongTimer.stop(); 
     209        if (d->registered) { 
     210                //Clear the registered status 
     211                emit errorChanged("Disconnected from server"); 
     212        } 
    192213        d->registered = false; 
    193214} 
     
    199220void LiveObject::stateChanged( QAbstractSocket::SocketState socketState ) { 
    200221        if (socketState == QAbstractSocket::UnconnectedState) { 
    201                 int timeout = rand() % 20 + 10; //Random timeout from 10-30s to avoid flooding the servers 
     222                int timeout = rand() % 40 + 10; //Random timeout from 10-50s to avoid flooding the servers 
    202223                QTimer::singleShot(timeout*1000, this, SLOT(connectToServer())); 
    203224                emit statusChanged("Reconnecting in " + QString::number(timeout) + " seconds..."); 
    204225        } else if (socketState == QAbstractSocket::ConnectingState) { 
    205226                emit statusChanged("Connecting..."); 
     227                emit errorChanged(""); 
    206228        } 
    207229} 
     
    229251        r->deleteLater(); 
    230252        if (r->error() != QNetworkReply::NoError) { 
     253                int timeout = rand() % 300 + 60; //Random timeout from 60s-6min to avoid flooding the servers 
    231254                emit errorChanged(r->errorString()); 
    232                 emit statusChanged("Error retrieving server list"); 
     255                emit statusChanged("Retrying in " + QString::number(timeout) + " seconds..."); 
     256                QTimer::singleShot(timeout * 1000, this, SLOT(connectToServer())); 
    233257                return; 
    234258        } 
     
    254278                QTimer::singleShot(0, this, SLOT(connectToServer())); 
    255279        } else { 
    256                 int timeout = rand() % 20 + 10; //Random timeout from 10-30s to avoid flooding the servers 
     280                int timeout = rand() % 300 + 60; //Random timeout from 60-6min to avoid flooding the servers 
    257281                emit errorChanged("No servers found"); 
    258282                emit statusChanged("Retrying in " + QString::number(timeout) + " seconds..."); 
     
    271295        LiveMessageToken token; 
    272296        token.valueType = LiveMessageToken::Dictionary; 
    273         token.dictVal["protocol"] = LiveMessageToken("1"); 
     297        token.dictVal["protocol"] = LiveMessageToken(2); 
    274298        token.dictVal["version"] = LiveMessageToken(TELLDUS_CENTER_VERSION); 
    275299#if defined(Q_WS_WIN) 
     
    315339        return token; 
    316340} 
     341 
     342void LiveObject::pongTimeout() { 
     343        this->disconnect(); 
     344} 
  • telldus-gui/Plugins/Live/LiveObject.h

    r0ec9cc r2feeb8  
    4040        void p_disconnected(); 
    4141        void readyRead(); 
     42        void pongTimeout(); 
    4243        void error( QAbstractSocket::SocketError socketError ); 
    4344        void stateChanged( QAbstractSocket::SocketState socketState ); 
  • telldus-gui/Plugins/Live/__init__.js

    r40c330 rd3227e  
    2020                com.telldus.core.deviceEvent.connect(deviceEvent); 
    2121                com.telldus.core.deviceChange.connect(sendDevicesReport); 
     22                configUI.findChild('registrationLink').clicked.connect(socket.activate); 
     23                configUI.findChild('registrationLink').visible = false; 
    2224        } 
    2325 
     
    2931                        com.telldus.systray.menuItem(menuId).triggered.connect(socket.activate); 
    3032                } 
     33                registrationLinkVisible(true); 
    3134        } 
    3235 
     
    4346 
    4447        function messageReceived(msg) { 
    45                 if (msg.name() == "turnon") { 
    46                         com.telldus.core.turnOn( msg.argument(0).intVal() ); 
    47                 } else if (msg.name() == "turnoff") { 
    48                         com.telldus.core.turnOff( msg.argument(0).intVal() ); 
    49                 } else if (msg.name() == "dim") { 
    50                         com.telldus.core.dim( msg.argument(0).intVal(), msg.argument(1).intVal() ); 
    51                 } else if (msg.name() == "bell") { 
    52                         com.telldus.core.bell( msg.argument(0).intVal() ); 
     48                if (msg.name() == "command") { 
     49                        handleCommand(msg.argument(0)); 
    5350                } 
    54                 print("Received: " + msg.name()); 
     51        } 
     52 
     53        function handleCommand(msg) { 
     54                var action = msg.getString('action'); 
     55                if (action == "turnon") { 
     56                        com.telldus.core.turnOn( msg.getInt('id') ); 
     57                } else if (action == "turnoff") { 
     58                        com.telldus.core.turnOff( msg.getInt('id') ); 
     59                } else if (action == "dim") { 
     60                        com.telldus.core.dim( msg.getInt('id'), msg.getInt('value') ); 
     61                } else if (action == "bell") { 
     62                        com.telldus.core.bell( msg.getInt('id') ); 
     63                } else if (action == "up") { 
     64                        com.telldus.core.up( msg.getInt('id') ); 
     65                } else if (action == "down") { 
     66                        com.telldus.core.down( msg.getInt('id') ); 
     67                } else if (action == "stop") { 
     68                        com.telldus.core.stop( msg.getInt('id') ); 
     69                } 
    5570        } 
    5671 
     
    6277                        separatorId = 0; 
    6378                } 
    64                 supportedMethods = msg.getInt('supportedMethods'); 
     79                //Mask to lowest common denominator 
     80                supportedMethods = 
     81                        com.telldus.core.TELLSTICK_TURNON | 
     82                        com.telldus.core.TELLSTICK_TURNOFF | 
     83                        com.telldus.core.TELLSTICK_DIM | 
     84                        com.telldus.core.TELLSTICK_BELL | 
     85                        com.telldus.core.TELLSTICK_UP | 
     86                        com.telldus.core.TELLSTICK_DOWN | 
     87                        com.telldus.core.TELLSTICK_STOP; 
     88                supportedMethods = supportedMethods & msg.getInt('supportedMethods'); 
    6589                isRegistered = true; 
     90                registrationLinkVisible(false); 
    6691                sendDevicesReport(); 
     92        } 
     93 
     94        function registrationLinkVisible(visibleParam){ 
     95                configUI.findChild('registrationLink').visible = visibleParam; 
    6796        } 
    6897 
  • telldus-gui/Plugins/Live/configuration.ui

    r0ec9cc r319e50  
    88    <y>0</y> 
    99    <width>323</width> 
    10     <height>263</height> 
     10    <height>251</height> 
    1111   </rect> 
     12  </property> 
     13  <property name="sizePolicy"> 
     14   <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> 
     15    <horstretch>0</horstretch> 
     16    <verstretch>0</verstretch> 
     17   </sizepolicy> 
    1218  </property> 
    1319  <property name="windowTitle"> 
    1420   <string>Form</string> 
    1521  </property> 
    16   <layout class="QFormLayout" name="formLayout"> 
    17    <item row="0" column="0"> 
    18     <widget class="QLabel" name="label"> 
    19      <property name="text"> 
    20       <string>Status:</string> 
    21      </property> 
    22     </widget> 
    23    </item> 
    24    <item row="0" column="1"> 
    25     <widget class="QLabel" name="statusLabel"> 
    26      <property name="text"> 
    27       <string>unknown</string> 
    28      </property> 
    29     </widget> 
    30    </item> 
    31    <item row="1" column="1"> 
    32     <widget class="QLabel" name="errorLabel"> 
    33      <property name="text"> 
    34       <string/> 
    35      </property> 
    36      <property name="wordWrap"> 
    37       <bool>true</bool> 
    38      </property> 
    39     </widget> 
    40    </item> 
    41   </layout> 
     22  <widget class="QWidget" name=""> 
     23   <property name="geometry"> 
     24    <rect> 
     25     <x>0</x> 
     26     <y>0</y> 
     27     <width>331</width> 
     28     <height>251</height> 
     29    </rect> 
     30   </property> 
     31   <layout class="QHBoxLayout" name="horizontalLayout_2"> 
     32    <item> 
     33     <layout class="QGridLayout" name="gridLayout_3"> 
     34      <item row="0" column="0"> 
     35       <widget class="QLabel" name="label"> 
     36        <property name="text"> 
     37         <string>Status:</string> 
     38        </property> 
     39       </widget> 
     40      </item> 
     41      <item row="0" column="1"> 
     42       <widget class="QLabel" name="statusLabel"> 
     43        <property name="text"> 
     44         <string>unknown</string> 
     45        </property> 
     46        <property name="wordWrap"> 
     47         <bool>true</bool> 
     48        </property> 
     49       </widget> 
     50      </item> 
     51      <item row="2" column="1"> 
     52       <widget class="QLabel" name="errorLabel"> 
     53        <property name="text"> 
     54         <string/> 
     55        </property> 
     56        <property name="wordWrap"> 
     57         <bool>true</bool> 
     58        </property> 
     59       </widget> 
     60      </item> 
     61      <item row="5" column="0" colspan="2"> 
     62       <widget class="QPushButton" name="registrationLink"> 
     63        <property name="text"> 
     64         <string>Activate Telldus Live!</string> 
     65        </property> 
     66       </widget> 
     67      </item> 
     68      <item row="3" column="1"> 
     69       <spacer name="verticalSpacer_2"> 
     70        <property name="orientation"> 
     71         <enum>Qt::Vertical</enum> 
     72        </property> 
     73        <property name="sizeHint" stdset="0"> 
     74         <size> 
     75          <width>20</width> 
     76          <height>40</height> 
     77         </size> 
     78        </property> 
     79       </spacer> 
     80      </item> 
     81      <item row="3" column="0"> 
     82       <spacer name="verticalSpacer"> 
     83        <property name="orientation"> 
     84         <enum>Qt::Vertical</enum> 
     85        </property> 
     86        <property name="sizeHint" stdset="0"> 
     87         <size> 
     88          <width>20</width> 
     89          <height>40</height> 
     90         </size> 
     91        </property> 
     92       </spacer> 
     93      </item> 
     94      <item row="6" column="0"> 
     95       <spacer name="verticalSpacer_3"> 
     96        <property name="orientation"> 
     97         <enum>Qt::Vertical</enum> 
     98        </property> 
     99        <property name="sizeHint" stdset="0"> 
     100         <size> 
     101          <width>20</width> 
     102          <height>40</height> 
     103         </size> 
     104        </property> 
     105       </spacer> 
     106      </item> 
     107     </layout> 
     108    </item> 
     109    <item> 
     110     <spacer name="horizontalSpacer"> 
     111      <property name="orientation"> 
     112       <enum>Qt::Horizontal</enum> 
     113      </property> 
     114      <property name="sizeHint" stdset="0"> 
     115       <size> 
     116        <width>40</width> 
     117        <height>20</height> 
     118       </size> 
     119      </property> 
     120     </spacer> 
     121    </item> 
     122   </layout> 
     123  </widget> 
    42124 </widget> 
    43125 <resources/> 
  • telldus-gui/TelldusCenter/CMakeLists.txt

    rf834ad r084930  
    6666 
    6767IF (APPLE) #### Mac OS X #### 
    68         LIST(APPEND telldus-center_LIBRARIES 
    69                 /usr/lib/libQtUiTools.a 
    70         ) 
    7168        INCLUDE_DIRECTORIES( 
    7269                /usr/include/QtUiTools 
  • telldus-gui/TelldusGui/devicesetting.cpp

    rfea831 r2d1756  
    2222{ 
    2323} 
     24 
     25void DeviceSetting::addProtocolMatch( const QString &protocol, const QString &model ){ 
     26        QString protocolmodel; //concat to one string 
     27        protocolmodel.append(protocol).append(model); 
     28        acceptedProtocolModel << protocolmodel; 
     29} 
     30 
     31void DeviceSetting::setProtocolValue( const QString &name, const QString &value, const QString &protocol, const QString &model ){ 
     32        QString protocolmodel; //concat to one string 
     33        protocolmodel.append(protocol).append(model); 
     34        if(acceptedProtocolModel.contains(protocolmodel)){  //protocol not set yet, or equal 
     35                this->setValue(name, value); 
     36        } 
     37} 
  • telldus-gui/TelldusGui/devicesetting.h

    r6af64f r2d1756  
    3030public slots: 
    3131        virtual void saveParameters() = 0; 
     32        void addProtocolMatch( const QString &protocol, const QString &model ); 
     33 
     34private slots: 
     35        void setProtocolValue( const QString &name, const QString &value, const QString &protocol, const QString &model ); 
    3236        virtual void setValue( const QString &name, const QString &value ) = 0; 
    3337 
    3438protected: 
    3539        Device *p_device; 
     40 
     41private: 
     42        QList<QString> acceptedProtocolModel; 
     43 
    3644}; 
    3745 
  • telldus-gui/TelldusGui/editdevicedialog.cpp

    r7bdbd4 r2d1756  
    174174 
    175175        foreach( DeviceSetting *s, d->deviceSettings ) { 
    176                 connect(d->filteredModel, SIGNAL(setParameter(const QString&, const QString&)), s, SLOT(setValue(const QString&, const QString&))); 
     176                connect(d->filteredModel, SIGNAL(setParameter(const QString&, const QString&, const QString&, const QString&)), s, SLOT(setProtocolValue(const QString&, const QString&, const QString&, const QString&))); 
    177177                d->settingsLayout->addWidget( s ); 
     178        } 
     179 
     180        for (int i=0; i<d->model->rowCount(QModelIndex()); ++i){ 
     181                QModelIndex index = d->model->index(i, 0, QModelIndex()); 
     182                VendorDeviceTreeItem *typeitem = d->model->item(index); 
     183 
     184                for(int j=0; j<typeitem->childCount(); ++j){ 
     185                        VendorDeviceTreeItem *branditem = typeitem->child(j); //d->model->item(index); 
     186 
     187                        for(int k=0; k<branditem->childCount(); ++k){ 
     188                                VendorDeviceTreeItem *deviceitem = branditem->child(k); //d->model->item(index); 
     189 
     190                                int widget = deviceitem->widget(); 
     191                                QString strModel = deviceitem->deviceModel().section(':', 0, 0); 
     192                                if (strModel.startsWith("selflearning-")) { 
     193                                        strModel = "selflearning"; 
     194                                } 
     195                                d->deviceSettings[widget]->addProtocolMatch(deviceitem->deviceProtocol(), strModel); 
     196                        } 
     197                } 
    178198        } 
    179199 
  • telldus-gui/TelldusGui/filtereddeviceproxymodel.cpp

    r217c63 r2d1756  
    5555                } 
    5656                else { 
    57                         emit setParameter(name, value); 
     57                        emit setParameter(name, value, protocol, model); 
    5858                } 
    5959        } 
  • telldus-gui/TelldusGui/filtereddeviceproxymodel.h

    r0a9f46 r2d1756  
    1818 
    1919signals: 
    20         void setParameter(const QString &name, const QString &value); 
     20        void setParameter(const QString &name, const QString &value, const QString &protocol,  const QString &model); 
    2121 
    2222protected: 
  • telldus-gui/Plugins/QML/CMakeLists.txt

    r3738b3 r1e650c  
    2424 
    2525INCLUDE( ../TelldusCenterPlugin.cmake NO_POLICY_SCOPE ) 
     26 
     27IF (WIN32) 
     28        SET(QT_COMPONENTS_OUTPUT_DIR "${LIBRARY_OUTPUT_PATH}/${CMAKE_CFG_INTDIR}/Plugins/declarative") 
     29ELSE() 
     30        SET(QT_COMPONENTS_OUTPUT_DIR "${CMAKE_BINARY_DIR}/TelldusCenter/Plugins/declarative") 
     31ENDIF() 
     32INCLUDE( ${CMAKE_SOURCE_DIR}/3rdparty/qt-components-desktop.cmake NO_POLICY_SCOPE ) 
  • telldus-gui/Plugins/QML/qmlview.cpp

    r61331e r5531d6  
    33#include <QDeclarativeContext> 
    44#include <QScriptValueIterator> 
     5#include <QDeclarativeEngine> 
    56#include <QVariant> 
     7#include <QApplication> 
    68 
    79class QMLView::PrivateData { 
     
    1618        setAttribute(Qt::WA_TranslucentBackground); 
    1719        setStyleSheet("background:transparent;"); 
     20 
     21        QDeclarativeEngine *eng = this->engine(); 
     22        QStringList paths(eng->importPathList()); 
     23        QDir pluginsDir = QDir(qApp->applicationDirPath()); 
     24 
     25#if defined(Q_OS_MAC) 
     26        if (pluginsDir.dirName() == "MacOS") { 
     27                pluginsDir.cdUp(); 
     28        } 
     29#endif 
     30 
     31        if (pluginsDir.cd("Plugins/declarative")) { 
     32                paths << pluginsDir.absolutePath(); 
     33        } 
     34 
     35        eng->setImportPathList(paths); 
    1836 
    1937        d = new PrivateData; 
  • telldus-gui/Plugins/Sensors/CMakeLists.txt

    re7ec37 r394270  
    44SET(QT_USE_QTDECLARATIVE TRUE) 
    55 
    6 SET( Plugin_NAME "sensors" ) 
     6SET( Plugin_NAME "Sensors" ) 
    77 
    88 
     
    3434        qmldir 
    3535        SensorValue.qml 
     36        SensorView.qml 
     37        SensorList.qml 
    3638) 
    3739 
  • telldus-gui/Plugins/Sensors/main.qml

    r8e377a rc90a4c  
    11import Qt 4.7 
     2import QtDesktop 0.1 
    23 
    34Item { 
     
    56        state: "VIEW" 
    67 
    7         Component { 
    8                 id: sensorView 
    9                 Item{ 
    10                         id: sensorViewItem 
    11                         visible: main.state == "EDIT" || modelData.showInList 
    12                         height: childrenRect.height 
    13                         width: parent.width 
     8        ScrollArea { 
     9                id: scrollArea 
     10                anchors.fill: parent 
     11                frame: false 
    1412 
    15                         BorderImage { 
    16                                 source: "row_bg.png" 
    17                                 border.left: 5; border.top: 5 
    18                                 border.right: 5; border.bottom: 5 
    19                                 height: sensorInfo.height 
    20                                 width: parent.width 
     13                contentHeight: sensorList.height 
     14                contentWidth: sensorList.width 
    2115 
    22                                 Text { 
    23                                         visible: main.state == "VIEW" 
    24                                         anchors.left: parent.left 
    25                                         anchors.leftMargin: 15 
    26                                         height: 40 
    27                                         verticalAlignment: Text.AlignVCenter 
    28                                         text: modelData.name; 
    29                                         color: "#004275" 
    30                                 } 
    31                                 Rectangle{ 
    32                                         color: "white" 
    33                                         visible: main.state == "EDIT" 
    34                                         anchors.left: parent.left 
    35                                         anchors.leftMargin: 15 
    36                                         width: nameEdit.width + 4 
    37                                         height: 22 
    38                                         TextInput{ 
    39                                                 id: nameEdit 
    40                                                 anchors.centerIn: parent 
    41                                                 text: modelData.name; 
    42                                                 color: "#004275" 
    43  
    44                                                 onActiveFocusChanged: { 
    45                                                         if(!activeFocus){ 
    46                                                                 //todo other way? 
    47                                                                 modelData.setName(nameEdit.text); 
    48                                                         } 
    49                                                 } 
    50                                                 onAccepted: { 
    51                                                         modelData.setName(nameEdit.text); 
    52                                                 } 
    53                                         } 
    54                                 } 
    55                                 Text{ 
    56                                         anchors.right: model.left 
    57                                         visible: main.state == "EDIT" 
    58                                         height: 40 
    59                                         verticalAlignment: Text.AlignVCenter 
    60                                         text: modelData.id 
    61                                         color: "#004275" 
    62                                         width: 50 
    63                                 } 
    64                                 Text{ 
    65                                         id: model 
    66                                         anchors.right: visibleinlistcheckbox.left 
    67                                         visible: main.state == "EDIT" 
    68                                         height: 40 
    69                                         verticalAlignment: Text.AlignVCenter 
    70                                         text: modelData.model 
    71                                         color: "#004275" 
    72                                         width: 100 
    73                                 } 
    74                                 Item{ 
    75                                         id: visibleinlistcheckbox 
    76                                         anchors.right: sensorInfo.left 
    77                                         visible: main.state == "EDIT" 
    78                                         height: 40 
    79                                         Rectangle{ 
    80                                                 anchors.centerIn: parent 
    81                                                 height: 10 
    82                                                 width: 10 
    83                                                 color: "white" 
    84                                                 Text{ 
    85                                                         anchors.centerIn: parent 
    86                                                         color: "#004275" 
    87                                                         text: modelData.showInList ? "X" : "" 
    88                                                 } 
    89                                                 MouseArea{ 
    90                                                         anchors.fill: parent 
    91                                                         onClicked: { 
    92                                                                 modelData.setShowInList(!modelData.showInList); 
    93                                                         } 
    94                                                 } 
    95                                         } 
    96                                         width: 100 
    97                                 } 
    98  
    99                                 Column { 
    100                                         id: sensorInfo 
    101                                         anchors.right: parent.right 
    102                                         width: 250 
    103                                         SensorValue { 
    104                                                 visible: modelData.hasTemperature 
    105                                                 text: visible ? modelData.sensorValue(1).value + '°C' : '' 
    106                                                 icon: "icon_temp.png" 
    107                                                 lastUpdated: visible ? modelData.sensorValue(1).lastUpdated : new Date() 
    108                                         } 
    109                                         SensorValue { 
    110                                                 visible: modelData.hasHumidity 
    111                                                 text: visible ? modelData.sensorValue(2).value + '%' : '' 
    112                                                 icon: "icon_humidity.png" 
    113                                                 lastUpdated: visible ? modelData.sensorValue(2).lastUpdated : new Date() 
    114                                         } 
    115                                 } 
    116                         } 
     16                SensorList { 
     17                        id: sensorList 
     18                        width: main.width-scrollArea.verticalScrollBar.width 
    11719                } 
    11820        } 
    119  
    120         Column { 
    121                 spacing: 1 
    122                 BorderImage { 
    123                         id: header 
    124                         source: "header_bg.png" 
    125                         width: parent.width; height: 40 
    126                         border.left: 5; border.top: 5 
    127                         border.right: 5; border.bottom: 5 
    128  
    129                         HeaderTitle { 
    130                                 text: "Name" 
    131                                 anchors.left: parent.left 
    132                                 anchors.leftMargin: 15 
    133                         } 
    134                         HeaderTitle { 
    135                                 text: "ID" 
    136                                 anchors.right: modelTitle.left 
    137                                 visible: main.state == "EDIT" 
    138                                 width: 50 
    139                         } 
    140                         HeaderTitle { 
    141                                 id: modelTitle 
    142                                 text: "Model" 
    143                                 anchors.right: visibleinlistTitle.left 
    144                                 visible: main.state == "EDIT" 
    145                                 width: 100 
    146                         } 
    147                         HeaderTitle { 
    148                                 id: visibleinlistTitle 
    149                                 text: "Visible in list" 
    150                                 anchors.right: sensorinformationTitle.left 
    151                                 visible: main.state == "EDIT" 
    152                                 width: 100 
    153                         } 
    154                         HeaderTitle { 
    155                                 id: sensorinformationTitle 
    156                                 text: "Sensor information" 
    157                                 width: 150 
    158                                 anchors.right: timestampTitle.left 
    159                         } 
    160                         HeaderTitle { 
    161                                 id: timestampTitle 
    162                                 text: "Last updated" 
    163                                 width: 100 
    164                                 anchors.right: parent.right 
    165                                 //horizontalAlignment: Text.AlignRight 
    166                         } 
    167                 } 
    168                 Repeater { 
    169                         model: sensorModel 
    170                         delegate: sensorView 
    171                 } 
    172                 Row{ 
    173                         spacing: 20 
    174                         Rectangle { 
    175                                 width: 50 
    176                                 height: 20 
    177                                 Text{ 
    178                                         anchors.centerIn: parent 
    179                                         text: main.state == "VIEW" ? "Edit" : "View" 
    180                                 } 
    181                                 MouseArea{ 
    182                                         anchors.fill: parent 
    183                                         onClicked: { 
    184                                                 if(main.state == "VIEW"){ 
    185                                                         main.state = "EDIT" 
    186                                                 } 
    187                                                 else{ 
    188                                                         main.state  ="VIEW" 
    189                                                 } 
    190                                         } 
    191                                 } 
    192                         } 
    193                         /* 
    194                         Rectangle { 
    195                                 //TODO should this button exist at all, or always save? 
    196                                 width: 50 
    197                                 height: 20 
    198                                 visible: main.state == "EDIT" 
    199                                 Text{ 
    200                                         anchors.centerIn: parent 
    201                                         text: "Cancel" 
    202                                 } 
    203                                 MouseArea{ 
    204                                         anchors.fill: parent 
    205                                         onClicked: { 
    206                                                 main.state  ="VIEW" 
    207                                         } 
    208                                 } 
    209                         } 
    210                         */ 
    211                 } 
    212                 anchors.fill: parent 
    213         } 
    21421} 
  • telldus-gui/Plugins/Sensors/qmldir

    r1bebae r394270  
    11HeaderTitle 1.0 HeaderTitle.qml 
    22SensorValue 1.0 SensorValue.qml 
     3SensorView 1.0 SensorView.qml 
     4SensorList 1.0 SensorList.qml 
  • telldus-gui/Plugins/Sensors/sensor.cpp

    r8e377a r99c2b0  
    4747 
    4848QString Sensor::name() const { 
    49         //return QString("%1 %2").arg(this->protocol()).arg(this->id()); //TODO: Remove when name is fully implemented 
    50         if(d->name == ""){ 
    51                 return "<unnamed>"; 
    52         } 
    5349        return d->name; 
    5450} 
  • telldus-gui/Plugins/TelldusCenterPlugin.cmake

    rf834ad r69b16f  
    6464ENDIF (UPDATE_TRANSLATIONS) 
    6565 
     66IF(Plugin_PATH) 
     67        FOREACH(_FILE ${Plugin_FILES}) 
     68                GET_FILENAME_COMPONENT(_FILENAME ${_FILE} NAME) 
     69                ADD_CUSTOM_COMMAND( OUTPUT ${Plugin_PATH}/${_FILENAME} 
     70                        COMMAND ${CMAKE_COMMAND} -E copy ${_FILE} ${Plugin_PATH}/${_FILENAME} 
     71                        DEPENDS ${_FILE} 
     72                        COMMENT "Copy ${_FILENAME} for plugin ${Plugin_NAME}" 
     73                ) 
     74                LIST(APPEND Plugin_TARGET_FILES "${Plugin_PATH}/${_FILENAME}") 
     75                IF (NOT APPLE) 
     76                        INSTALL(FILES ${_FILE} DESTINATION "${PLUGIN_LIB_FULL_PATH}/script/${Plugin_PATH_relative}") 
     77                ENDIF () 
     78        ENDFOREACH(_FILE) 
     79ENDIF(Plugin_PATH) 
     80 
    6681IF(Plugin_SRCS) 
    6782        ADD_LIBRARY(${Plugin_NAME} SHARED 
     
    7590                ${Plugin_TS} 
    7691                ${Plugin_QM} 
     92                ${Plugin_TARGET_FILES} 
    7793        ) 
    7894        TARGET_LINK_LIBRARIES( ${Plugin_NAME}   ${Plugin_LIBRARIES} ) 
     
    88104                        GET_BUNDLE_AND_EXECUTABLE(\"\${app}\" bundle exe valid) 
    89105                        SET(plugin \"\${bundle}/Contents/Plugins/script/${Plugin_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX}\") 
    90                          
     106 
    91107                        GET_ITEM_KEY(\"\${plugin}\" pkey) 
    92108                        SET(prereqs \"\") 
     
    94110                        FOREACH(pr \${prereqs}) 
    95111                                GET_ITEM_KEY(\"\${pr}\" rkey) 
    96                                  
     112 
    97113                                #Don't change the path to TelldusCore 
    98114                                IF (NOT \"\${rkey}\" STREQUAL \"TelldusCore\") 
     
    118134                ) 
    119135                INSTALL(TARGETS ${Plugin_NAME} 
    120                         LIBRARY DESTINATION "${PLUGIN_LIB_FULL_PATH}/script"  
     136                        LIBRARY DESTINATION "${PLUGIN_LIB_FULL_PATH}/script" 
    121137                ) 
    122138        ENDIF (APPLE) 
     
    124140ELSE(Plugin_SRCS) 
    125141        ADD_CUSTOM_TARGET(${Plugin_NAME} ALL 
    126                 SOURCES ${Plugin_FILES} 
     142                SOURCES ${Plugin_FILES} ${Plugin_TARGET_FILES} 
    127143        ) 
    128144ENDIF(Plugin_SRCS) 
    129  
    130 IF(Plugin_PATH) 
    131         ADD_CUSTOM_COMMAND( TARGET ${Plugin_NAME} 
    132                 POST_BUILD 
    133                 COMMAND ${CMAKE_COMMAND} -E make_directory ${Plugin_PATH} 
    134                 COMMENT "Creating plugin directory ${Plugin_NAME}" 
    135         ) 
    136         FOREACH(_FILE ${Plugin_FILES}) 
    137                 GET_FILENAME_COMPONENT(_FILENAME ${_FILE} NAME) 
    138                 ADD_CUSTOM_COMMAND( TARGET ${Plugin_NAME} 
    139                         POST_BUILD 
    140                         COMMAND ${CMAKE_COMMAND} -E copy ${_FILE} ${Plugin_PATH} 
    141                         COMMENT "Copy ${_FILENAME} for plugin ${Plugin_NAME}" 
    142                 ) 
    143                 IF (NOT APPLE) 
    144                         INSTALL(FILES ${_FILE} DESTINATION "${PLUGIN_LIB_FULL_PATH}/script/${Plugin_PATH_relative}") 
    145                 ENDIF () 
    146         ENDFOREACH(_FILE) 
    147 ENDIF(Plugin_PATH) 
    148  
    149  
Note: See TracChangeset for help on using the changeset viewer.