Convert dos endings to unix in telldus-core, see #160

This commit is contained in:
Micke Prag 2012-02-27 17:37:52 +01:00
parent bdd95b8d78
commit 9500c4c898
72 changed files with 8881 additions and 8881 deletions

View file

@ -1,62 +1,62 @@
PROJECT( telldus-core ) PROJECT( telldus-core )
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.0 ) CMAKE_MINIMUM_REQUIRED( VERSION 2.6.0 )
CMAKE_POLICY(SET CMP0003 NEW) CMAKE_POLICY(SET CMP0003 NEW)
OPTION(FORCE_COMPILE_FROM_TRUNK FALSE "Accept compiling source from trunk. This is unsupported and highly unrecommended") OPTION(FORCE_COMPILE_FROM_TRUNK FALSE "Accept compiling source from trunk. This is unsupported and highly unrecommended")
IF(NOT FORCE_COMPILE_FROM_TRUNK) IF(NOT FORCE_COMPILE_FROM_TRUNK)
MESSAGE(FATAL_ERROR "You are compiling sources from trunk. Don't do that!") MESSAGE(FATAL_ERROR "You are compiling sources from trunk. Don't do that!")
ENDIF(NOT FORCE_COMPILE_FROM_TRUNK) ENDIF(NOT FORCE_COMPILE_FROM_TRUNK)
SET(PACKAGE_MAJOR_VERSION 2) SET(PACKAGE_MAJOR_VERSION 2)
SET(PACKAGE_MINOR_VERSION 1) SET(PACKAGE_MINOR_VERSION 1)
SET(PACKAGE_PATCH_VERSION 1) SET(PACKAGE_PATCH_VERSION 1)
SET(PACKAGE_VERSION "${PACKAGE_MAJOR_VERSION}.${PACKAGE_MINOR_VERSION}.${PACKAGE_PATCH_VERSION}") SET(PACKAGE_VERSION "${PACKAGE_MAJOR_VERSION}.${PACKAGE_MINOR_VERSION}.${PACKAGE_PATCH_VERSION}")
SET(PACKAGE_SUBVERSION "") SET(PACKAGE_SUBVERSION "")
SET(PACKAGE_SOVERSION 2) SET(PACKAGE_SOVERSION 2)
SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
IF (PACKAGE_SUBVERSION) IF (PACKAGE_SUBVERSION)
SET(DISPLAYED_VERSION "${PACKAGE_VERSION}_${PACKAGE_SUBVERSION}") SET(DISPLAYED_VERSION "${PACKAGE_VERSION}_${PACKAGE_SUBVERSION}")
ELSE (PACKAGE_SUBVERSION) ELSE (PACKAGE_SUBVERSION)
SET(DISPLAYED_VERSION ${PACKAGE_VERSION}) SET(DISPLAYED_VERSION ${PACKAGE_VERSION})
ENDIF(PACKAGE_SUBVERSION) ENDIF(PACKAGE_SUBVERSION)
SET(BUILD_LIBTELLDUS-CORE TRUE CACHE BOOL "Build libtelldus-core") SET(BUILD_LIBTELLDUS-CORE TRUE CACHE BOOL "Build libtelldus-core")
IF (WIN32) IF (WIN32)
SET(TDADMIN_DEFAULT FALSE) SET(TDADMIN_DEFAULT FALSE)
ELSEIF(APPLE) ELSEIF(APPLE)
SET(TDADMIN_DEFAULT FALSE) SET(TDADMIN_DEFAULT FALSE)
ELSE (WIN32) ELSE (WIN32)
SET(TDADMIN_DEFAULT TRUE) SET(TDADMIN_DEFAULT TRUE)
ENDIF (WIN32) ENDIF (WIN32)
IF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD") IF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
INCLUDE_DIRECTORIES(/usr/local/include) INCLUDE_DIRECTORIES(/usr/local/include)
LINK_DIRECTORIES(/usr/local/lib) LINK_DIRECTORIES(/usr/local/lib)
ENDIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD") ENDIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
SET(BUILD_TDTOOL TRUE CACHE BOOL "Build tdtool") SET(BUILD_TDTOOL TRUE CACHE BOOL "Build tdtool")
SET(BUILD_TDADMIN ${TDADMIN_DEFAULT} CACHE BOOL "Build tdadmin") SET(BUILD_TDADMIN ${TDADMIN_DEFAULT} CACHE BOOL "Build tdadmin")
SET(GENERATE_MAN FALSE CACHE BOOL "Enable generation of man-files") SET(GENERATE_MAN FALSE CACHE BOOL "Enable generation of man-files")
ADD_SUBDIRECTORY(common) ADD_SUBDIRECTORY(common)
ADD_SUBDIRECTORY(service) ADD_SUBDIRECTORY(service)
ADD_SUBDIRECTORY(client) ADD_SUBDIRECTORY(client)
IF(BUILD_TDTOOL) IF(BUILD_TDTOOL)
IF(WIN32) IF(WIN32)
ADD_SUBDIRECTORY(3rdparty/openbsd-getopt) ADD_SUBDIRECTORY(3rdparty/openbsd-getopt)
ENDIF() ENDIF()
ADD_SUBDIRECTORY(tdtool) ADD_SUBDIRECTORY(tdtool)
ENDIF(BUILD_TDTOOL) ENDIF(BUILD_TDTOOL)
IF(BUILD_TDADMIN) IF(BUILD_TDADMIN)
ADD_SUBDIRECTORY(tdadmin) ADD_SUBDIRECTORY(tdadmin)
ENDIF(BUILD_TDADMIN) ENDIF(BUILD_TDADMIN)
ENABLE_TESTING() ENABLE_TESTING()
ADD_SUBDIRECTORY(tests) ADD_SUBDIRECTORY(tests)

View file

@ -1,132 +1,132 @@
IF(COMMAND cmake_policy) IF(COMMAND cmake_policy)
cmake_policy(SET CMP0003 NEW) cmake_policy(SET CMP0003 NEW)
ENDIF(COMMAND cmake_policy) ENDIF(COMMAND cmake_policy)
FIND_PACKAGE( SignTool REQUIRED ) FIND_PACKAGE( SignTool REQUIRED )
######## Non configurable options ######## ######## Non configurable options ########
SET( telldus-core_SRCS SET( telldus-core_SRCS
CallbackDispatcher.cpp CallbackDispatcher.cpp
CallbackMainDispatcher.cpp CallbackMainDispatcher.cpp
Client.cpp Client.cpp
telldus-core.cpp telldus-core.cpp
) )
SET( telldus-core_HDRS SET( telldus-core_HDRS
CallbackDispatcher.h CallbackDispatcher.h
CallbackMainDispatcher.cpp CallbackMainDispatcher.cpp
Client.h Client.h
) )
SET( telldus-core_PUB_HDRS SET( telldus-core_PUB_HDRS
telldus-core.h telldus-core.h
) )
FIND_PACKAGE(Threads) FIND_PACKAGE(Threads)
LIST(APPEND telldus-core_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) LIST(APPEND telldus-core_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_SOURCE_DIR}/../common ${CMAKE_CURRENT_SOURCE_DIR}/../common
) )
######## Configurable options for the platform ######## ######## Configurable options for the platform ########
######## Platforms-specific, non configurable ######## ######## Platforms-specific, non configurable ########
IF (APPLE) IF (APPLE)
#### Mac OS X #### #### Mac OS X ####
SET( telldus-core_TARGET TelldusCore ) SET( telldus-core_TARGET TelldusCore )
ADD_DEFINITIONS( ADD_DEFINITIONS(
-D_MACOSX -D_MACOSX
) )
LIST(APPEND telldus-core_LIBRARIES LIST(APPEND telldus-core_LIBRARIES
TelldusCommon TelldusCommon
) )
ELSEIF (WIN32) ELSEIF (WIN32)
#### Windows #### #### Windows ####
ADD_DEFINITIONS( -DUNICODE ) ADD_DEFINITIONS( -DUNICODE )
ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No
SET( telldus-core_TARGET TelldusCore ) SET( telldus-core_TARGET TelldusCore )
LIST(APPEND telldus-core_LIBRARIES LIST(APPEND telldus-core_LIBRARIES
TelldusCommon TelldusCommon
) )
CONFIGURE_FILE( CONFIGURE_FILE(
${CMAKE_CURRENT_SOURCE_DIR}/telldus-core.rc.in ${CMAKE_CURRENT_SOURCE_DIR}/telldus-core.rc.in
${CMAKE_CURRENT_BINARY_DIR}/telldus-core.rc ${CMAKE_CURRENT_BINARY_DIR}/telldus-core.rc
) )
LIST(APPEND telldus-core_SRCS LIST(APPEND telldus-core_SRCS
libtelldus-core.def libtelldus-core.def
${CMAKE_CURRENT_SOURCE_DIR}/telldus-core.rc.in ${CMAKE_CURRENT_SOURCE_DIR}/telldus-core.rc.in
${CMAKE_CURRENT_BINARY_DIR}/telldus-core.rc ${CMAKE_CURRENT_BINARY_DIR}/telldus-core.rc
) )
ADD_DEFINITIONS( ADD_DEFINITIONS(
-D_WINDOWS -D_WINDOWS
-DTELLDUSCORE_EXPORTS -DTELLDUSCORE_EXPORTS
) )
IF (CMAKE_CL_64) IF (CMAKE_CL_64)
ADD_DEFINITIONS(-D_CL64) ADD_DEFINITIONS(-D_CL64)
ENDIF(CMAKE_CL_64) ENDIF(CMAKE_CL_64)
ELSE (APPLE) ELSE (APPLE)
#### Linux #### #### Linux ####
SET( telldus-core_TARGET telldus-core ) SET( telldus-core_TARGET telldus-core )
LIST(APPEND telldus-core_LIBRARIES LIST(APPEND telldus-core_LIBRARIES
TelldusCommon TelldusCommon
) )
ADD_DEFINITIONS( ADD_DEFINITIONS(
-D_LINUX -D_LINUX
) )
ENDIF (APPLE) ENDIF (APPLE)
######## Configuring ######## ######## Configuring ########
ADD_LIBRARY(${telldus-core_TARGET} SHARED ADD_LIBRARY(${telldus-core_TARGET} SHARED
${telldus-core_SRCS} ${telldus-core_SRCS}
${telldus-core_HDRS} ${telldus-core_HDRS}
${telldus-core_PUB_HDRS} ${telldus-core_PUB_HDRS}
) )
#Copy public headers files on windows #Copy public headers files on windows
IF (WIN32) IF (WIN32)
FOREACH(_FILE ${telldus-core_PUB_HDRS}) FOREACH(_FILE ${telldus-core_PUB_HDRS})
ADD_CUSTOM_COMMAND( TARGET ${telldus-core_TARGET} ADD_CUSTOM_COMMAND( TARGET ${telldus-core_TARGET}
POST_BUILD POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy \"${CMAKE_CURRENT_SOURCE_DIR}/${_FILE}\" \"${LIBRARY_OUTPUT_PATH}/${CMAKE_CFG_INTDIR}\" COMMAND ${CMAKE_COMMAND} -E copy \"${CMAKE_CURRENT_SOURCE_DIR}/${_FILE}\" \"${LIBRARY_OUTPUT_PATH}/${CMAKE_CFG_INTDIR}\"
COMMENT "Copy ${_FILE}" COMMENT "Copy ${_FILE}"
) )
ENDFOREACH(_FILE) ENDFOREACH(_FILE)
ENDIF () ENDIF ()
ADD_DEPENDENCIES(${telldus-core_TARGET} TelldusCommon) ADD_DEPENDENCIES(${telldus-core_TARGET} TelldusCommon)
IF (UNIX) IF (UNIX)
SET_TARGET_PROPERTIES( ${telldus-core_TARGET} PROPERTIES COMPILE_FLAGS "-fPIC -fvisibility=hidden") SET_TARGET_PROPERTIES( ${telldus-core_TARGET} PROPERTIES COMPILE_FLAGS "-fPIC -fvisibility=hidden")
ENDIF (UNIX) ENDIF (UNIX)
TARGET_LINK_LIBRARIES( ${telldus-core_TARGET} ${telldus-core_LIBRARIES} ) TARGET_LINK_LIBRARIES( ${telldus-core_TARGET} ${telldus-core_LIBRARIES} )
SET_TARGET_PROPERTIES(${telldus-core_TARGET} PROPERTIES SET_TARGET_PROPERTIES(${telldus-core_TARGET} PROPERTIES
FRAMEWORK TRUE FRAMEWORK TRUE
INSTALL_NAME_DIR "/Library/Frameworks" INSTALL_NAME_DIR "/Library/Frameworks"
PUBLIC_HEADER ${telldus-core_PUB_HDRS} PUBLIC_HEADER ${telldus-core_PUB_HDRS}
VERSION ${PACKAGE_VERSION} VERSION ${PACKAGE_VERSION}
SOVERSION ${PACKAGE_SOVERSION} SOVERSION ${PACKAGE_SOVERSION}
) )
SIGN(${telldus-core_TARGET}) SIGN(${telldus-core_TARGET})
IF (NOT LIB_INSTALL_DIR) IF (NOT LIB_INSTALL_DIR)
SET(LIB_INSTALL_DIR "lib") SET(LIB_INSTALL_DIR "lib")
ENDIF (NOT LIB_INSTALL_DIR) ENDIF (NOT LIB_INSTALL_DIR)
IF (UNIX) IF (UNIX)
INSTALL(TARGETS ${telldus-core_TARGET} INSTALL(TARGETS ${telldus-core_TARGET}
LIBRARY DESTINATION ${LIB_INSTALL_DIR} LIBRARY DESTINATION ${LIB_INSTALL_DIR}
ARCHIVE DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR}
FRAMEWORK DESTINATION "/Library/Frameworks" FRAMEWORK DESTINATION "/Library/Frameworks"
PUBLIC_HEADER DESTINATION include PUBLIC_HEADER DESTINATION include
) )
ENDIF (UNIX) ENDIF (UNIX)

View file

@ -1,266 +1,266 @@
#include "Client.h" #include "Client.h"
#include "CallbackDispatcher.h" #include "CallbackDispatcher.h"
#include "CallbackMainDispatcher.h" #include "CallbackMainDispatcher.h"
#include "Socket.h" #include "Socket.h"
#include "Strings.h" #include "Strings.h"
#include "Mutex.h" #include "Mutex.h"
#include <list> #include <list>
using namespace TelldusCore; using namespace TelldusCore;
class Client::PrivateData { class Client::PrivateData {
public: public:
Socket eventSocket; Socket eventSocket;
bool running, sensorCached, controllerCached; bool running, sensorCached, controllerCached;
std::wstring sensorCache, controllerCache; std::wstring sensorCache, controllerCache;
TelldusCore::Mutex mutex; TelldusCore::Mutex mutex;
CallbackMainDispatcher callbackMainDispatcher; CallbackMainDispatcher callbackMainDispatcher;
}; };
Client *Client::instance = 0; Client *Client::instance = 0;
Client::Client() Client::Client()
: Thread() : Thread()
{ {
d = new PrivateData; d = new PrivateData;
d->running = true; d->running = true;
d->sensorCached = false; d->sensorCached = false;
d->controllerCached = false; d->controllerCached = false;
d->callbackMainDispatcher.start(); d->callbackMainDispatcher.start();
start(); start();
} }
Client::~Client(void) { Client::~Client(void) {
stopThread(); stopThread();
wait(); wait();
{ {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
} }
delete d; delete d;
} }
void Client::close() { void Client::close() {
if (Client::instance != 0) { if (Client::instance != 0) {
delete Client::instance; delete Client::instance;
Client::instance = 0; Client::instance = 0;
} }
} }
Client *Client::getInstance() { Client *Client::getInstance() {
if (Client::instance == 0) { if (Client::instance == 0) {
Client::instance = new Client(); Client::instance = new Client();
} }
return Client::instance; return Client::instance;
} }
bool Client::getBoolFromService(const Message &msg) { bool Client::getBoolFromService(const Message &msg) {
return getIntegerFromService(msg) == TELLSTICK_SUCCESS; return getIntegerFromService(msg) == TELLSTICK_SUCCESS;
} }
int Client::getIntegerFromService(const Message &msg) { int Client::getIntegerFromService(const Message &msg) {
std::wstring response = sendToService(msg); std::wstring response = sendToService(msg);
if (response.compare(L"") == 0) { if (response.compare(L"") == 0) {
return TELLSTICK_ERROR_COMMUNICATING_SERVICE; return TELLSTICK_ERROR_COMMUNICATING_SERVICE;
} }
return Message::takeInt(&response); return Message::takeInt(&response);
} }
std::wstring Client::getWStringFromService(const Message &msg) { std::wstring Client::getWStringFromService(const Message &msg) {
std::wstring response = sendToService(msg); std::wstring response = sendToService(msg);
return Message::takeString(&response); return Message::takeString(&response);
} }
int Client::registerEvent( CallbackStruct::CallbackType type, void *eventFunction, void *context ) { int Client::registerEvent( CallbackStruct::CallbackType type, void *eventFunction, void *context ) {
return d->callbackMainDispatcher.registerCallback(type, eventFunction, context ); return d->callbackMainDispatcher.registerCallback(type, eventFunction, context );
} }
void Client::run(){ void Client::run(){
//listen here //listen here
d->eventSocket.connect(L"TelldusEvents"); d->eventSocket.connect(L"TelldusEvents");
while(d->running){ while(d->running){
if(!d->eventSocket.isConnected()){ if(!d->eventSocket.isConnected()){
d->eventSocket.connect(L"TelldusEvents"); //try to reconnect to service d->eventSocket.connect(L"TelldusEvents"); //try to reconnect to service
if(!d->eventSocket.isConnected()){ if(!d->eventSocket.isConnected()){
//reconnect didn't succeed, wait a while and try again //reconnect didn't succeed, wait a while and try again
msleep(2000); msleep(2000);
continue; continue;
} }
} }
std::wstring clientMessage = d->eventSocket.read(1000); //testing 5 second timeout std::wstring clientMessage = d->eventSocket.read(1000); //testing 5 second timeout
while(clientMessage != L""){ while(clientMessage != L""){
//a message arrived //a message arrived
std::wstring type = Message::takeString(&clientMessage); std::wstring type = Message::takeString(&clientMessage);
if(type == L"TDDeviceChangeEvent"){ if(type == L"TDDeviceChangeEvent"){
DeviceChangeEventCallbackData *data = new DeviceChangeEventCallbackData(); DeviceChangeEventCallbackData *data = new DeviceChangeEventCallbackData();
data->deviceId = Message::takeInt(&clientMessage); data->deviceId = Message::takeInt(&clientMessage);
data->changeEvent = Message::takeInt(&clientMessage); data->changeEvent = Message::takeInt(&clientMessage);
data->changeType = Message::takeInt(&clientMessage); data->changeType = Message::takeInt(&clientMessage);
d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data); d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data);
} else if(type == L"TDDeviceEvent"){ } else if(type == L"TDDeviceEvent"){
DeviceEventCallbackData *data = new DeviceEventCallbackData(); DeviceEventCallbackData *data = new DeviceEventCallbackData();
data->deviceId = Message::takeInt(&clientMessage); data->deviceId = Message::takeInt(&clientMessage);
data->deviceState = Message::takeInt(&clientMessage); data->deviceState = Message::takeInt(&clientMessage);
data->deviceStateValue = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->deviceStateValue = TelldusCore::wideToString(Message::takeString(&clientMessage));
d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data); d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data);
} else if(type == L"TDRawDeviceEvent"){ } else if(type == L"TDRawDeviceEvent"){
RawDeviceEventCallbackData *data = new RawDeviceEventCallbackData(); RawDeviceEventCallbackData *data = new RawDeviceEventCallbackData();
data->data = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->data = TelldusCore::wideToString(Message::takeString(&clientMessage));
data->controllerId = Message::takeInt(&clientMessage); data->controllerId = Message::takeInt(&clientMessage);
d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data); d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data);
} else if(type == L"TDSensorEvent"){ } else if(type == L"TDSensorEvent"){
SensorEventCallbackData *data = new SensorEventCallbackData(); SensorEventCallbackData *data = new SensorEventCallbackData();
data->protocol = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->protocol = TelldusCore::wideToString(Message::takeString(&clientMessage));
data->model = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->model = TelldusCore::wideToString(Message::takeString(&clientMessage));
data->id = Message::takeInt(&clientMessage); data->id = Message::takeInt(&clientMessage);
data->dataType = Message::takeInt(&clientMessage); data->dataType = Message::takeInt(&clientMessage);
data->value = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->value = TelldusCore::wideToString(Message::takeString(&clientMessage));
data->timestamp = Message::takeInt(&clientMessage); data->timestamp = Message::takeInt(&clientMessage);
d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data); d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data);
} else if(type == L"TDControllerEvent") { } else if(type == L"TDControllerEvent") {
ControllerEventCallbackData *data = new ControllerEventCallbackData(); ControllerEventCallbackData *data = new ControllerEventCallbackData();
data->controllerId = Message::takeInt(&clientMessage); data->controllerId = Message::takeInt(&clientMessage);
data->changeEvent = Message::takeInt(&clientMessage); data->changeEvent = Message::takeInt(&clientMessage);
data->changeType = Message::takeInt(&clientMessage); data->changeType = Message::takeInt(&clientMessage);
data->newValue = TelldusCore::wideToString(Message::takeString(&clientMessage)); data->newValue = TelldusCore::wideToString(Message::takeString(&clientMessage));
d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data); d->callbackMainDispatcher.retrieveCallbackEvent()->signal(data);
} else { } else {
clientMessage = L""; //cleanup, if message contained garbage/unhandled data clientMessage = L""; //cleanup, if message contained garbage/unhandled data
} }
} }
} }
} }
std::wstring Client::sendToService(const Message &msg) { std::wstring Client::sendToService(const Message &msg) {
int tries = 0; int tries = 0;
std::wstring readData; std::wstring readData;
while(tries < 20){ while(tries < 20){
tries++; tries++;
if(tries == 20){ if(tries == 20){
TelldusCore::Message msg; TelldusCore::Message msg;
msg.addArgument(TELLSTICK_ERROR_CONNECTING_SERVICE); msg.addArgument(TELLSTICK_ERROR_CONNECTING_SERVICE);
return msg; return msg;
} }
Socket s; Socket s;
s.connect(L"TelldusClient"); s.connect(L"TelldusClient");
if (!s.isConnected()) { //Connection failed if (!s.isConnected()) { //Connection failed
msleep(500); msleep(500);
continue; //retry continue; //retry
} }
s.write(msg.data()); s.write(msg.data());
if (!s.isConnected()) { //Connection failed sometime during operation... (better check here, instead of 5 seconds timeout later) if (!s.isConnected()) { //Connection failed sometime during operation... (better check here, instead of 5 seconds timeout later)
msleep(500); msleep(500);
continue; //retry continue; //retry
} }
readData = s.read(8000); //TODO changed to 10000 from 5000, how much does this do...? readData = s.read(8000); //TODO changed to 10000 from 5000, how much does this do...?
if(readData == L""){ if(readData == L""){
msleep(500); msleep(500);
continue; //TODO can we be really sure it SHOULD be anything? continue; //TODO can we be really sure it SHOULD be anything?
//TODO perhaps break here instead? //TODO perhaps break here instead?
} }
if (!s.isConnected()) { //Connection failed sometime during operation... if (!s.isConnected()) { //Connection failed sometime during operation...
msleep(500); msleep(500);
continue; //retry continue; //retry
} }
break; break;
} }
return readData; return readData;
} }
void Client::stopThread(){ void Client::stopThread(){
d->running = false; d->running = false;
d->eventSocket.stopReadWait(); d->eventSocket.stopReadWait();
} }
bool Client::unregisterCallback( int callbackId ) { bool Client::unregisterCallback( int callbackId ) {
return d->callbackMainDispatcher.unregisterCallback(callbackId); return d->callbackMainDispatcher.unregisterCallback(callbackId);
} }
int Client::getSensor(char *protocol, int protocolLen, char *model, int modelLen, int *sensorId, int *dataTypes) { int Client::getSensor(char *protocol, int protocolLen, char *model, int modelLen, int *sensorId, int *dataTypes) {
if (!d->sensorCached) { if (!d->sensorCached) {
Message msg(L"tdSensor"); Message msg(L"tdSensor");
std::wstring response = Client::getWStringFromService(msg); std::wstring response = Client::getWStringFromService(msg);
int count = Message::takeInt(&response); int count = Message::takeInt(&response);
d->sensorCached = true; d->sensorCached = true;
d->sensorCache = L""; d->sensorCache = L"";
if (count > 0) { if (count > 0) {
d->sensorCache = response; d->sensorCache = response;
} }
} }
if (d->sensorCache == L"") { if (d->sensorCache == L"") {
d->sensorCached = false; d->sensorCached = false;
return TELLSTICK_ERROR_DEVICE_NOT_FOUND; return TELLSTICK_ERROR_DEVICE_NOT_FOUND;
} }
std::wstring p = Message::takeString(&d->sensorCache); std::wstring p = Message::takeString(&d->sensorCache);
std::wstring m = Message::takeString(&d->sensorCache); std::wstring m = Message::takeString(&d->sensorCache);
int id = Message::takeInt(&d->sensorCache); int id = Message::takeInt(&d->sensorCache);
int dt = Message::takeInt(&d->sensorCache); int dt = Message::takeInt(&d->sensorCache);
if (protocol && protocolLen) { if (protocol && protocolLen) {
strncpy(protocol, TelldusCore::wideToString(p).c_str(), protocolLen); strncpy(protocol, TelldusCore::wideToString(p).c_str(), protocolLen);
} }
if (model && modelLen) { if (model && modelLen) {
strncpy(model, TelldusCore::wideToString(m).c_str(), modelLen); strncpy(model, TelldusCore::wideToString(m).c_str(), modelLen);
} }
if (sensorId) { if (sensorId) {
(*sensorId) = id; (*sensorId) = id;
} }
if (dataTypes) { if (dataTypes) {
(*dataTypes) = dt; (*dataTypes) = dt;
} }
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
int Client::getController(int *controllerId, int *controllerType, char *name, int nameLen, int *available) { int Client::getController(int *controllerId, int *controllerType, char *name, int nameLen, int *available) {
if (!d->controllerCached) { if (!d->controllerCached) {
Message msg(L"tdController"); Message msg(L"tdController");
std::wstring response = Client::getWStringFromService(msg); std::wstring response = Client::getWStringFromService(msg);
int count = Message::takeInt(&response); int count = Message::takeInt(&response);
d->controllerCached = true; d->controllerCached = true;
d->controllerCache = L""; d->controllerCache = L"";
if (count > 0) { if (count > 0) {
d->controllerCache = response; d->controllerCache = response;
} }
} }
if (d->controllerCache == L"") { if (d->controllerCache == L"") {
d->controllerCached = false; d->controllerCached = false;
return TELLSTICK_ERROR_NOT_FOUND; return TELLSTICK_ERROR_NOT_FOUND;
} }
int id = Message::takeInt(&d->controllerCache); int id = Message::takeInt(&d->controllerCache);
int type = Message::takeInt(&d->controllerCache); int type = Message::takeInt(&d->controllerCache);
std::wstring n = Message::takeString(&d->controllerCache); std::wstring n = Message::takeString(&d->controllerCache);
int a = Message::takeInt(&d->controllerCache); int a = Message::takeInt(&d->controllerCache);
if (controllerId) { if (controllerId) {
(*controllerId) = id; (*controllerId) = id;
} }
if (controllerType) { if (controllerType) {
(*controllerType) = type; (*controllerType) = type;
} }
if (name && nameLen) { if (name && nameLen) {
strncpy(name, TelldusCore::wideToString(n).c_str(), nameLen); strncpy(name, TelldusCore::wideToString(n).c_str(), nameLen);
} }
if (available) { if (available) {
(*available) = a; (*available) = a;
} }
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }

View file

@ -1,42 +1,42 @@
#ifndef CLIENT_H #ifndef CLIENT_H
#define CLIENT_H #define CLIENT_H
#include "Message.h" #include "Message.h"
#include "telldus-core.h" #include "telldus-core.h"
#include "Thread.h" #include "Thread.h"
#include "CallbackDispatcher.h" #include "CallbackDispatcher.h"
namespace TelldusCore { namespace TelldusCore {
class Client : public Thread class Client : public Thread
{ {
public: public:
~Client(void); ~Client(void);
static Client *getInstance(); static Client *getInstance();
static void close(); static void close();
int registerEvent(CallbackStruct::CallbackType type, void *eventFunction, void *context ); int registerEvent(CallbackStruct::CallbackType type, void *eventFunction, void *context );
void stopThread(void); void stopThread(void);
bool unregisterCallback( int callbackId ); bool unregisterCallback( int callbackId );
int getSensor(char *protocol, int protocolLen, char *model, int modelLen, int *id, int *dataTypes); int getSensor(char *protocol, int protocolLen, char *model, int modelLen, int *id, int *dataTypes);
int getController(int *controllerId, int *controllerType, char *name, int nameLen, int *available); int getController(int *controllerId, int *controllerType, char *name, int nameLen, int *available);
static bool getBoolFromService(const Message &msg); static bool getBoolFromService(const Message &msg);
static int getIntegerFromService(const Message &msg); static int getIntegerFromService(const Message &msg);
static std::wstring getWStringFromService(const Message &msg); static std::wstring getWStringFromService(const Message &msg);
protected: protected:
void run(void); void run(void);
private: private:
Client(); Client();
static std::wstring sendToService(const Message &msg); static std::wstring sendToService(const Message &msg);
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
static Client *instance; static Client *instance;
}; };
} }
#endif //CLIENT_H #endif //CLIENT_H

View file

@ -1,60 +1,60 @@
LIBRARY tellduscore LIBRARY tellduscore
EXPORTS EXPORTS
tdGetNumberOfDevices @1 tdGetNumberOfDevices @1
tdGetDeviceId @2 tdGetDeviceId @2
tdGetName @3 tdGetName @3
tdGetProtocol @4 tdGetProtocol @4
tdGetModel @5 tdGetModel @5
tdGetDeviceParameter @6 tdGetDeviceParameter @6
tdSetName @7 tdSetName @7
tdSetProtocol @8 tdSetProtocol @8
tdSetModel @9 tdSetModel @9
tdSetDeviceParameter @10 tdSetDeviceParameter @10
tdAddDevice @11 tdAddDevice @11
tdRemoveDevice @12 tdRemoveDevice @12
tdMethods @13 tdMethods @13
tdTurnOn @14 tdTurnOn @14
tdTurnOff @15 tdTurnOff @15
tdBell @16 tdBell @16
tdDim @17 tdDim @17
tdGetErrorString @18 tdGetErrorString @18
tdClose @19 tdClose @19
tdInit @20 tdInit @20
tdRegisterDeviceEvent @21 tdRegisterDeviceEvent @21
tdLastSentCommand @22 tdLastSentCommand @22
tdGetDeviceType @23 tdGetDeviceType @23
tdSendRawCommand @24 tdSendRawCommand @24
tdRegisterRawDeviceEvent @25 tdRegisterRawDeviceEvent @25
tdLearn @26 tdLearn @26
tdLastSentValue @27 tdLastSentValue @27
tdReleaseString @28 tdReleaseString @28
tdUnregisterCallback @29 tdUnregisterCallback @29
tdConnectTellStickController @30 tdConnectTellStickController @30
tdDisconnectTellStickController @31 tdDisconnectTellStickController @31
tdRegisterDeviceChangeEvent @32 tdRegisterDeviceChangeEvent @32
tdExecute @33 tdExecute @33
tdUp @34 tdUp @34
tdDown @35 tdDown @35
tdStop @36 tdStop @36
tdRegisterSensorEvent @37 tdRegisterSensorEvent @37
tdSensor @38 tdSensor @38
tdSensorValue @39 tdSensorValue @39
tdController @40 tdController @40
tdControllerValue @41 tdControllerValue @41
tdSetControllerValue @42 tdSetControllerValue @42
tdRemoveController @43 tdRemoveController @43
tdRegisterControllerEvent @44 tdRegisterControllerEvent @44

View file

@ -1,19 +1,19 @@
IF(WIN32) IF(WIN32)
SET(SIGN_FILES FALSE CACHE BOOL "Sign the generated files. This requires a certificate to be installed on the computer!") SET(SIGN_FILES FALSE CACHE BOOL "Sign the generated files. This requires a certificate to be installed on the computer!")
ENDIF() ENDIF()
FUNCTION(SIGN TARGET) FUNCTION(SIGN TARGET)
IF (NOT WIN32) IF (NOT WIN32)
RETURN() RETURN()
ENDIF() ENDIF()
IF (NOT SIGN_FILES) IF (NOT SIGN_FILES)
RETURN() RETURN()
ENDIF() ENDIF()
GET_TARGET_PROPERTY(file ${TARGET} LOCATION) GET_TARGET_PROPERTY(file ${TARGET} LOCATION)
GET_FILENAME_COMPONENT(filename ${file} NAME) GET_FILENAME_COMPONENT(filename ${file} NAME)
ADD_CUSTOM_COMMAND( TARGET ${TARGET} POST_BUILD ADD_CUSTOM_COMMAND( TARGET ${TARGET} POST_BUILD
COMMAND signtool.exe sign /a /t http://timestamp.verisign.com/scripts/timstamp.dll ${file} COMMAND signtool.exe sign /a /t http://timestamp.verisign.com/scripts/timstamp.dll ${file}
COMMENT "Signing file ${filename}" COMMENT "Signing file ${filename}"
) )
ENDFUNCTION() ENDFUNCTION()

View file

@ -1,87 +1,87 @@
IF(COMMAND cmake_policy) IF(COMMAND cmake_policy)
CMAKE_POLICY(SET CMP0003 NEW) CMAKE_POLICY(SET CMP0003 NEW)
ENDIF(COMMAND cmake_policy) ENDIF(COMMAND cmake_policy)
######## Non configurable options ######## ######## Non configurable options ########
SET( telldus-common_SRCS SET( telldus-common_SRCS
Event.cpp Event.cpp
Message.cpp Message.cpp
Mutex.cpp Mutex.cpp
Strings.cpp Strings.cpp
Thread.cpp Thread.cpp
) )
SET( telldus-common_HDRS SET( telldus-common_HDRS
common.h common.h
Event.h Event.h
EventHandler.h EventHandler.h
Message.h Message.h
Mutex.h Mutex.h
Socket.h Socket.h
Strings.h Strings.h
Thread.h Thread.h
) )
######## Configurable options for the platform ######## ######## Configurable options for the platform ########
######## Platforms-specific, non configurable ######## ######## Platforms-specific, non configurable ########
IF (APPLE) IF (APPLE)
#### Mac OS X #### #### Mac OS X ####
FIND_LIBRARY(ICONV_LIBRARY iconv) FIND_LIBRARY(ICONV_LIBRARY iconv)
ADD_DEFINITIONS( -D_MACOSX ) ADD_DEFINITIONS( -D_MACOSX )
LIST(APPEND telldus-common_SRCS LIST(APPEND telldus-common_SRCS
Event_unix.cpp Event_unix.cpp
EventHandler_unix.cpp EventHandler_unix.cpp
Socket_unix.cpp Socket_unix.cpp
stdlibc_workaround.cpp #Remove this when we drop support for 10.5 stdlibc_workaround.cpp #Remove this when we drop support for 10.5
) )
LIST(APPEND telldus-common_LIBRARIES LIST(APPEND telldus-common_LIBRARIES
${ICONV_LIBRARY} ${ICONV_LIBRARY}
) )
ELSEIF (WIN32) ELSEIF (WIN32)
#### Windows #### #### Windows ####
ADD_DEFINITIONS( -DUNICODE ) ADD_DEFINITIONS( -DUNICODE )
ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No
ADD_DEFINITIONS( -D_WINDOWS ) ADD_DEFINITIONS( -D_WINDOWS )
LIST(APPEND telldus-common_SRCS LIST(APPEND telldus-common_SRCS
Event_win.cpp Event_win.cpp
EventHandler_win.cpp EventHandler_win.cpp
Socket_win.cpp Socket_win.cpp
) )
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD") ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
#### FreeBSD #### #### FreeBSD ####
FIND_LIBRARY(ICONV_LIBRARY iconv) FIND_LIBRARY(ICONV_LIBRARY iconv)
ADD_DEFINITIONS( -D_FREEBSD ) ADD_DEFINITIONS( -D_FREEBSD )
LIST(APPEND telldus-common_SRCS LIST(APPEND telldus-common_SRCS
Event_unix.cpp Event_unix.cpp
EventHandler_unix.cpp EventHandler_unix.cpp
Socket_unix.cpp Socket_unix.cpp
) )
LIST(APPEND telldus-common_LIBRARIES LIST(APPEND telldus-common_LIBRARIES
${ICONV_LIBRARY} ${ICONV_LIBRARY}
) )
ELSE (APPLE) ELSE (APPLE)
#### Linux #### #### Linux ####
ADD_DEFINITIONS( -D_LINUX ) ADD_DEFINITIONS( -D_LINUX )
LIST(APPEND telldus-common_SRCS LIST(APPEND telldus-common_SRCS
Event_unix.cpp Event_unix.cpp
EventHandler_unix.cpp EventHandler_unix.cpp
Socket_unix.cpp Socket_unix.cpp
) )
ENDIF (APPLE) ENDIF (APPLE)
######## Configuring ######## ######## Configuring ########
ADD_LIBRARY(TelldusCommon STATIC ADD_LIBRARY(TelldusCommon STATIC
${telldus-common_SRCS} ${telldus-common_SRCS}
${telldus-common_HDRS} ${telldus-common_HDRS}
) )
IF (UNIX) IF (UNIX)
SET_TARGET_PROPERTIES( TelldusCommon PROPERTIES COMPILE_FLAGS "-fPIC -fvisibility=hidden") SET_TARGET_PROPERTIES( TelldusCommon PROPERTIES COMPILE_FLAGS "-fPIC -fvisibility=hidden")
ENDIF (UNIX) ENDIF (UNIX)
TARGET_LINK_LIBRARIES( TelldusCommon ${telldus-common_LIBRARIES} ) TARGET_LINK_LIBRARIES( TelldusCommon ${telldus-common_LIBRARIES} )

View file

@ -1,77 +1,77 @@
#include "Event.h" #include "Event.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "Mutex.h" #include "Mutex.h"
#include <list> #include <list>
using namespace TelldusCore; using namespace TelldusCore;
EventData::~EventData() { EventData::~EventData() {
} }
bool EventData::isValid() const { bool EventData::isValid() const {
return false; return false;
}; };
bool EventDataBase::isValid() const { bool EventDataBase::isValid() const {
return true; return true;
}; };
class EventBase::PrivateData { class EventBase::PrivateData {
public: public:
TelldusCore::Mutex mutex; TelldusCore::Mutex mutex;
EventHandler *handler; EventHandler *handler;
std::list<EventDataRef> eventDataList; std::list<EventDataRef> eventDataList;
}; };
EventBase::EventBase(TelldusCore::EventHandler *handler) { EventBase::EventBase(TelldusCore::EventHandler *handler) {
d = new PrivateData; d = new PrivateData;
d->handler = handler; d->handler = handler;
} }
EventBase::~EventBase(void) { EventBase::~EventBase(void) {
delete d; delete d;
} }
void EventBase::clearHandler() { void EventBase::clearHandler() {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->handler = 0; d->handler = 0;
} }
void EventBase::popSignal() { void EventBase::popSignal() {
this->takeSignal(); this->takeSignal();
} }
EventHandler *EventBase::handler() const { EventHandler *EventBase::handler() const {
return d->handler; return d->handler;
} }
bool EventBase::isSignaled() { bool EventBase::isSignaled() {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
return (d->eventDataList.size() > 0); return (d->eventDataList.size() > 0);
} }
void EventBase::signal() { void EventBase::signal() {
signal(new EventData()); signal(new EventData());
} }
void EventBase::signal(EventData *eventData) { void EventBase::signal(EventData *eventData) {
{ {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->eventDataList.push_back(EventDataRef(eventData)); d->eventDataList.push_back(EventDataRef(eventData));
} }
sendSignal(); sendSignal();
} }
EventDataRef EventBase::takeSignal() { EventDataRef EventBase::takeSignal() {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
if (d->eventDataList.size() == 0) { if (d->eventDataList.size() == 0) {
return EventDataRef(new EventData()); return EventDataRef(new EventData());
} }
EventDataRef data = d->eventDataList.front(); EventDataRef data = d->eventDataList.front();
d->eventDataList.pop_front(); d->eventDataList.pop_front();
if (d->eventDataList.size() == 0) { if (d->eventDataList.size() == 0) {
this->clearSignal(); this->clearSignal();
} }
return data; return data;
} }

View file

@ -1,29 +1,29 @@
#ifndef EVENTHANDLER_H #ifndef EVENTHANDLER_H
#define EVENTHANDLER_H #define EVENTHANDLER_H
#include "Event.h" #include "Event.h"
namespace TelldusCore { namespace TelldusCore {
class EventHandler { class EventHandler {
public: public:
EventHandler(); EventHandler();
virtual ~EventHandler(void); virtual ~EventHandler(void);
EventRef addEvent(); EventRef addEvent();
bool waitForAny(); bool waitForAny();
protected: protected:
void signal(Event *event); void signal(Event *event);
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
bool listIsSignalled(); bool listIsSignalled();
friend class Event; friend class Event;
}; };
} }
#endif //EVENTHANDLER_H #endif //EVENTHANDLER_H

View file

@ -1,72 +1,72 @@
#include "EventHandler.h" #include "EventHandler.h"
#include "Event.h" #include "Event.h"
#include "Mutex.h" #include "Mutex.h"
#include "Thread.h" #include "Thread.h"
#include <list> #include <list>
#include <pthread.h> #include <pthread.h>
#include <stdio.h> #include <stdio.h>
using namespace TelldusCore; using namespace TelldusCore;
class EventHandler::PrivateData { class EventHandler::PrivateData {
public: public:
pthread_cond_t event; pthread_cond_t event;
pthread_mutex_t mutex; pthread_mutex_t mutex;
std::list<EventRef> eventList; std::list<EventRef> eventList;
TelldusCore::Mutex listMutex; TelldusCore::Mutex listMutex;
}; };
EventHandler::EventHandler() { EventHandler::EventHandler() {
d = new PrivateData; d = new PrivateData;
pthread_cond_init(&d->event, NULL); pthread_cond_init(&d->event, NULL);
pthread_mutex_init(&d->mutex, NULL); pthread_mutex_init(&d->mutex, NULL);
} }
EventHandler::~EventHandler(void) { EventHandler::~EventHandler(void) {
pthread_mutex_destroy(&d->mutex); pthread_mutex_destroy(&d->mutex);
pthread_cond_destroy(&d->event); pthread_cond_destroy(&d->event);
std::list<EventRef>::const_iterator it = d->eventList.begin(); std::list<EventRef>::const_iterator it = d->eventList.begin();
for(; it != d->eventList.end(); ++it) { for(; it != d->eventList.end(); ++it) {
//We clear the handler if someone else still has a reference to the event //We clear the handler if someone else still has a reference to the event
(*it)->clearHandler(); (*it)->clearHandler();
} }
delete d; delete d;
} }
EventRef EventHandler::addEvent() { EventRef EventHandler::addEvent() {
EventRef event(new Event(this)); EventRef event(new Event(this));
TelldusCore::MutexLocker locker(&d->listMutex); TelldusCore::MutexLocker locker(&d->listMutex);
d->eventList.push_back(event); d->eventList.push_back(event);
return event; return event;
} }
bool EventHandler::listIsSignalled(){ bool EventHandler::listIsSignalled(){
TelldusCore::MutexLocker locker(&d->listMutex); TelldusCore::MutexLocker locker(&d->listMutex);
std::list<EventRef>::const_iterator it = d->eventList.begin(); std::list<EventRef>::const_iterator it = d->eventList.begin();
for(; it != d->eventList.end(); ++it) { for(; it != d->eventList.end(); ++it) {
if((*it)->isSignaled()){ if((*it)->isSignaled()){
return true; return true;
} }
} }
return false; return false;
} }
void EventHandler::signal(Event *event) { void EventHandler::signal(Event *event) {
pthread_mutex_lock(&d->mutex); pthread_mutex_lock(&d->mutex);
//event->setSignaled(); //event->setSignaled();
pthread_cond_signal(&d->event); pthread_cond_signal(&d->event);
pthread_mutex_unlock(&d->mutex); pthread_mutex_unlock(&d->mutex);
} }
bool EventHandler::waitForAny() { bool EventHandler::waitForAny() {
pthread_mutex_lock(&d->mutex); pthread_mutex_lock(&d->mutex);
while(!listIsSignalled()) { while(!listIsSignalled()) {
pthread_cond_wait(&d->event, &d->mutex); pthread_cond_wait(&d->event, &d->mutex);
} }
pthread_mutex_unlock(&d->mutex); pthread_mutex_unlock(&d->mutex);
return true; return true;
} }

View file

@ -1,69 +1,69 @@
#include "EventHandler.h" #include "EventHandler.h"
#include "Event.h" #include "Event.h"
#include "Mutex.h" #include "Mutex.h"
#include <windows.h> #include <windows.h>
#include <list> #include <list>
using namespace TelldusCore; using namespace TelldusCore;
class EventHandler::PrivateData { class EventHandler::PrivateData {
public: public:
HANDLE *eventArray; HANDLE *eventArray;
EventRef *eventObjectArray; EventRef *eventObjectArray;
TelldusCore::Mutex mutex; TelldusCore::Mutex mutex;
int eventCount; int eventCount;
}; };
EventHandler::EventHandler() { EventHandler::EventHandler() {
d = new PrivateData; d = new PrivateData;
d->eventCount = 0; d->eventCount = 0;
d->eventArray = new HANDLE[0]; d->eventArray = new HANDLE[0];
d->eventObjectArray = new EventRef[0]; d->eventObjectArray = new EventRef[0];
} }
EventHandler::~EventHandler(void) { EventHandler::~EventHandler(void) {
delete[] d->eventObjectArray; delete[] d->eventObjectArray;
delete[] d->eventArray; delete[] d->eventArray;
delete d; delete d;
} }
EventRef EventHandler::addEvent() { EventRef EventHandler::addEvent() {
EventRef event(new Event(this)); EventRef event(new Event(this));
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
HANDLE *newArray = new HANDLE[d->eventCount+1]; HANDLE *newArray = new HANDLE[d->eventCount+1];
EventRef *newObjectArray = new EventRef[d->eventCount+1]; EventRef *newObjectArray = new EventRef[d->eventCount+1];
for (int i = 0; i < d->eventCount; ++i) { for (int i = 0; i < d->eventCount; ++i) {
newArray[i] = d->eventArray[i]; newArray[i] = d->eventArray[i];
newObjectArray[i] = d->eventObjectArray[i]; newObjectArray[i] = d->eventObjectArray[i];
} }
delete[] d->eventArray; delete[] d->eventArray;
delete[] d->eventObjectArray; delete[] d->eventObjectArray;
d->eventArray = newArray; d->eventArray = newArray;
d->eventObjectArray = newObjectArray; d->eventObjectArray = newObjectArray;
d->eventArray[d->eventCount] = event->retrieveNative(); d->eventArray[d->eventCount] = event->retrieveNative();
d->eventObjectArray[d->eventCount] = event; d->eventObjectArray[d->eventCount] = event;
++d->eventCount; ++d->eventCount;
return event; return event;
} }
void EventHandler::signal(Event *) { void EventHandler::signal(Event *) {
} }
bool EventHandler::waitForAny() { bool EventHandler::waitForAny() {
while(1){ while(1){
int result = WaitForMultipleObjects(d->eventCount, d->eventArray, FALSE, 1000); int result = WaitForMultipleObjects(d->eventCount, d->eventArray, FALSE, 1000);
if (result == WAIT_TIMEOUT) { if (result == WAIT_TIMEOUT) {
continue; continue;
} }
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
int eventIndex = result - WAIT_OBJECT_0; int eventIndex = result - WAIT_OBJECT_0;
if (eventIndex >= d->eventCount) { if (eventIndex >= d->eventCount) {
return false; return false;
} }
return true; return true;
} }
} }

View file

@ -1,28 +1,28 @@
#include "Event.h" #include "Event.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "Thread.h" #include "Thread.h"
using namespace TelldusCore; using namespace TelldusCore;
class Event::PrivateData { class Event::PrivateData {
public: public:
}; };
Event::Event(EventHandler *handler) Event::Event(EventHandler *handler)
:EventBase(handler){ :EventBase(handler){
d = new PrivateData; d = new PrivateData;
} }
Event::~Event(void) { Event::~Event(void) {
delete d; delete d;
} }
void Event::clearSignal() { void Event::clearSignal() {
} }
void Event::sendSignal() { void Event::sendSignal() {
EventHandler *handler = this->handler(); EventHandler *handler = this->handler();
if (handler) { if (handler) {
handler->signal(this); handler->signal(this);
} }
} }

View file

@ -1,35 +1,35 @@
#include "Event.h" #include "Event.h"
#include "Thread.h" #include "Thread.h"
using namespace TelldusCore; using namespace TelldusCore;
class Event::PrivateData { class Event::PrivateData {
public: public:
EVENT_T event; EVENT_T event;
}; };
Event::Event(EventHandler *handler) Event::Event(EventHandler *handler)
:EventBase(handler) :EventBase(handler)
{ {
d = new PrivateData; d = new PrivateData;
d->event = CreateEvent(NULL, true, false, NULL); d->event = CreateEvent(NULL, true, false, NULL);
} }
Event::~Event(void) { Event::~Event(void) {
CloseHandle(d->event); CloseHandle(d->event);
delete d; delete d;
} }
EVENT_T Event::retrieveNative() { EVENT_T Event::retrieveNative() {
return d->event; return d->event;
} }
void Event::clearSignal() { void Event::clearSignal() {
ResetEvent(d->event); ResetEvent(d->event);
} }
void Event::sendSignal() { void Event::sendSignal() {
SetEvent(d->event); SetEvent(d->event);
} }

View file

@ -1,128 +1,128 @@
#include "Message.h" #include "Message.h"
#include "Socket.h" #include "Socket.h"
#include "Strings.h" #include "Strings.h"
#include <sstream> #include <sstream>
#include <wctype.h> #include <wctype.h>
#include <stdlib.h> #include <stdlib.h>
using namespace TelldusCore; using namespace TelldusCore;
Message::Message() Message::Message()
: std::wstring() : std::wstring()
{ {
} }
Message::Message(const std::wstring &functionName) Message::Message(const std::wstring &functionName)
:std::wstring() :std::wstring()
{ {
this->addArgument(functionName); this->addArgument(functionName);
} }
Message::~Message(void) { Message::~Message(void) {
} }
void Message::addArgument(const std::wstring &value) { void Message::addArgument(const std::wstring &value) {
//std::wstringstream st; //std::wstringstream st;
//st << (int)value.size(); //st << (int)value.size();
this->append(TelldusCore::intToWstring(value.size())); //st.str()); this->append(TelldusCore::intToWstring(value.size())); //st.str());
this->append(L":"); this->append(L":");
this->append(value); this->append(value);
} }
void Message::addArgument(int value) { void Message::addArgument(int value) {
//std::wstringstream st; //std::wstringstream st;
//st << (int)value; //st << (int)value;
this->append(L"i"); this->append(L"i");
this->append(TelldusCore::intToWstring(value)); // st.str()); this->append(TelldusCore::intToWstring(value)); // st.str());
this->append(L"s"); this->append(L"s");
} }
/* /*
void Message::addSpecialArgument(const std::wstring &value){ void Message::addSpecialArgument(const std::wstring &value){
int i = 0; int i = 0;
while(i<1000000){ while(i<1000000){
i++; i++;
char numstr[21]; // enough to hold all numbers up to 64-bits char numstr[21]; // enough to hold all numbers up to 64-bits
//sprintf(numstr, "%d", value.size()); //sprintf(numstr, "%d", value.size());
//this->append(TelldusCore::charToWstring(numstr)); //.str()); //this->append(TelldusCore::charToWstring(numstr)); //.str());
itoa(value.size(), numstr, 10); itoa(value.size(), numstr, 10);
std::string test(numstr); std::string test(numstr);
std::wstring temp(test.length(), L' '); std::wstring temp(test.length(), L' ');
std::copy(test.begin(), test.end(), temp.begin()); std::copy(test.begin(), test.end(), temp.begin());
this->append(temp); this->append(temp);
this->append(L":"); this->append(L":");
this->append(value); this->append(value);
/* /*
std::wstringstream st; std::wstringstream st;
st << (int)value.size(); st << (int)value.size();
this->append(st.str()); this->append(st.str());
this->append(L":"); this->append(L":");
this->append(value); this->append(value);
} }
} }
void Message::addSpecialArgument(int value){ void Message::addSpecialArgument(int value){
int i = 0; int i = 0;
while(i<1000000){ while(i<1000000){
i++; i++;
/* /*
//std::wstringstream st; //std::wstringstream st;
//st << (int)value; //st << (int)value;
this->append(L"i"); this->append(L"i");
//this->append(st.str()); //this->append(st.str());
this->append(L"s"); this->append(L"s");
} }
} }
*/ */
/* /*
void Message::addSpecialArgument(const char *value){ void Message::addSpecialArgument(const char *value){
this->addSpecialArgument(TelldusCore::charToWstring(value)); this->addSpecialArgument(TelldusCore::charToWstring(value));
} }
*/ */
void Message::addArgument(const char *value) { void Message::addArgument(const char *value) {
this->addArgument(TelldusCore::charToWstring(value)); this->addArgument(TelldusCore::charToWstring(value));
} }
bool Message::nextIsInt(const std::wstring &message) { bool Message::nextIsInt(const std::wstring &message) {
if (message.length() == 0) { if (message.length() == 0) {
return false; return false;
} }
return (message.at(0) == 'i'); return (message.at(0) == 'i');
} }
bool Message::nextIsString(const std::wstring &message) { bool Message::nextIsString(const std::wstring &message) {
if (message.length() == 0) { if (message.length() == 0) {
return false; return false;
} }
return (iswdigit(message.at(0)) != 0); return (iswdigit(message.at(0)) != 0);
} }
std::wstring Message::takeString(std::wstring *message) { std::wstring Message::takeString(std::wstring *message) {
if (!Message::nextIsString(*message)) { if (!Message::nextIsString(*message)) {
return L""; return L"";
} }
size_t index = message->find(':'); size_t index = message->find(':');
int length = wideToInteger(message->substr(0, index)); int length = wideToInteger(message->substr(0, index));
std::wstring retval(message->substr(index+1, length)); std::wstring retval(message->substr(index+1, length));
message->erase(0, index+length+1); message->erase(0, index+length+1);
return retval; return retval;
} }
int Message::takeInt(std::wstring *message) { int Message::takeInt(std::wstring *message) {
if (!Message::nextIsInt(*message)) { if (!Message::nextIsInt(*message)) {
return 0; return 0;
} }
size_t index = message->find('s'); size_t index = message->find('s');
int value = wideToInteger(message->substr(1, index - 1)); int value = wideToInteger(message->substr(1, index - 1));
message->erase(0, index+1); message->erase(0, index+1);
return value; return value;
} }

View file

@ -1,31 +1,31 @@
#ifndef MESSAGE_H #ifndef MESSAGE_H
#define MESSAGE_H #define MESSAGE_H
#include <string> #include <string>
namespace TelldusCore { namespace TelldusCore {
class Message : public std::wstring { class Message : public std::wstring {
public: public:
Message(); Message();
Message(const std::wstring &); Message(const std::wstring &);
~Message(void); ~Message(void);
void addArgument(const std::wstring &); void addArgument(const std::wstring &);
//void addSpecialArgument(const std::wstring &); //void addSpecialArgument(const std::wstring &);
//void addSpecialArgument(int); //void addSpecialArgument(int);
//void addSpecialArgument(const char *); //void addSpecialArgument(const char *);
void addArgument(int); void addArgument(int);
void addArgument(const char *); void addArgument(const char *);
static bool nextIsInt(const std::wstring &); static bool nextIsInt(const std::wstring &);
static bool nextIsString(const std::wstring &); static bool nextIsString(const std::wstring &);
static std::wstring takeString(std::wstring *); static std::wstring takeString(std::wstring *);
static int takeInt(std::wstring *); static int takeInt(std::wstring *);
private: private:
}; };
} }
#endif //MESSAGE_H #endif //MESSAGE_H

View file

@ -1,33 +1,33 @@
#ifndef SOCKET_H #ifndef SOCKET_H
#define SOCKET_H #define SOCKET_H
#include <string> #include <string>
#ifdef _WINDOWS #ifdef _WINDOWS
#include <windows.h> #include <windows.h>
typedef HANDLE SOCKET_T; typedef HANDLE SOCKET_T;
#else #else
typedef int SOCKET_T; typedef int SOCKET_T;
#endif #endif
namespace TelldusCore { namespace TelldusCore {
class Socket class Socket
{ {
public: public:
Socket(); Socket();
Socket(SOCKET_T hPipe); Socket(SOCKET_T hPipe);
virtual ~Socket(void); virtual ~Socket(void);
void connect(const std::wstring &server); void connect(const std::wstring &server);
bool isConnected(); bool isConnected();
std::wstring read(); std::wstring read();
std::wstring read(int timeout); std::wstring read(int timeout);
void stopReadWait(); void stopReadWait();
void write(const std::wstring &msg); void write(const std::wstring &msg);
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
} }
#endif //SOCKET_H #endif //SOCKET_H

View file

@ -1,127 +1,127 @@
#include "Socket.h" #include "Socket.h"
#include "Mutex.h" #include "Mutex.h"
#include "Strings.h" #include "Strings.h"
#include <stdio.h> #include <stdio.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <math.h> #include <math.h>
#define BUFSIZE 512 #define BUFSIZE 512
using namespace TelldusCore; using namespace TelldusCore;
int connectWrapper(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { int connectWrapper(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
return connect(sockfd, addr, addrlen); return connect(sockfd, addr, addrlen);
} }
class Socket::PrivateData { class Socket::PrivateData {
public: public:
SOCKET_T socket; SOCKET_T socket;
bool connected; bool connected;
fd_set infds; fd_set infds;
Mutex mutex; Mutex mutex;
}; };
Socket::Socket() { Socket::Socket() {
d = new PrivateData; d = new PrivateData;
d->socket = 0; d->socket = 0;
d->connected = false; d->connected = false;
FD_ZERO(&d->infds); FD_ZERO(&d->infds);
} }
Socket::Socket(SOCKET_T socket) Socket::Socket(SOCKET_T socket)
{ {
d = new PrivateData; d = new PrivateData;
d->socket = socket; d->socket = socket;
FD_ZERO(&d->infds); FD_ZERO(&d->infds);
d->connected = true; d->connected = true;
} }
Socket::~Socket(void) { Socket::~Socket(void) {
if(d->socket){ if(d->socket){
close(d->socket); close(d->socket);
} }
delete d; delete d;
} }
void Socket::connect(const std::wstring &server) { void Socket::connect(const std::wstring &server) {
struct sockaddr_un remote; struct sockaddr_un remote;
socklen_t len; socklen_t len;
if ((d->socket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { if ((d->socket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
return; return;
} }
std::string name = "/tmp/" + std::string(server.begin(), server.end()); std::string name = "/tmp/" + std::string(server.begin(), server.end());
remote.sun_family = AF_UNIX; remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, name.c_str()); strcpy(remote.sun_path, name.c_str());
len = SUN_LEN(&remote); len = SUN_LEN(&remote);
if (connectWrapper(d->socket, (struct sockaddr *)&remote, len) == -1) { if (connectWrapper(d->socket, (struct sockaddr *)&remote, len) == -1) {
return; return;
} }
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->connected = true; d->connected = true;
} }
bool Socket::isConnected(){ bool Socket::isConnected(){
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
return d->connected; return d->connected;
} }
std::wstring Socket::read() { std::wstring Socket::read() {
return this->read(0); return this->read(0);
} }
std::wstring Socket::read(int timeout) { std::wstring Socket::read(int timeout) {
struct timeval tv; struct timeval tv;
char inbuf[BUFSIZE]; char inbuf[BUFSIZE];
FD_SET(d->socket, &d->infds); FD_SET(d->socket, &d->infds);
std::string msg; std::string msg;
while(isConnected()) { while(isConnected()) {
tv.tv_sec = floor(timeout / 1000.0); tv.tv_sec = floor(timeout / 1000.0);
tv.tv_usec = timeout % 1000; tv.tv_usec = timeout % 1000;
int response = select(d->socket+1, &d->infds, NULL, NULL, &tv); int response = select(d->socket+1, &d->infds, NULL, NULL, &tv);
if (response == 0 && timeout > 0) { if (response == 0 && timeout > 0) {
return L""; return L"";
} else if (response <= 0) { } else if (response <= 0) {
FD_SET(d->socket, &d->infds); FD_SET(d->socket, &d->infds);
continue; continue;
} }
int received = BUFSIZE; int received = BUFSIZE;
while(received >= (BUFSIZE - 1)){ while(received >= (BUFSIZE - 1)){
memset(inbuf, '\0', sizeof(inbuf)); memset(inbuf, '\0', sizeof(inbuf));
received = recv(d->socket, inbuf, BUFSIZE - 1, 0); received = recv(d->socket, inbuf, BUFSIZE - 1, 0);
if(received > 0){ if(received > 0){
msg.append(std::string(inbuf)); msg.append(std::string(inbuf));
} }
} }
if (received < 0) { if (received < 0) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->connected = false; d->connected = false;
} }
break; break;
} }
return TelldusCore::charToWstring(msg.c_str()); return TelldusCore::charToWstring(msg.c_str());
} }
void Socket::stopReadWait(){ void Socket::stopReadWait(){
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->connected = false; d->connected = false;
//TODO somehow signal the socket here? //TODO somehow signal the socket here?
} }
void Socket::write(const std::wstring &msg) { void Socket::write(const std::wstring &msg) {
std::string newMsg(TelldusCore::wideToString(msg)); std::string newMsg(TelldusCore::wideToString(msg));
int sent = send(d->socket, newMsg.c_str(), newMsg.length(), 0); int sent = send(d->socket, newMsg.c_str(), newMsg.length(), 0);
if (sent < 0) { if (sent < 0) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
d->connected = false; d->connected = false;
} }
} }

View file

@ -1,180 +1,180 @@
#include "Socket.h" #include "Socket.h"
#include <windows.h> #include <windows.h>
#include <AccCtrl.h> #include <AccCtrl.h>
#include <Aclapi.h> #include <Aclapi.h>
#define BUFSIZE 512 #define BUFSIZE 512
using namespace TelldusCore; using namespace TelldusCore;
class Socket::PrivateData { class Socket::PrivateData {
public: public:
HANDLE hPipe; HANDLE hPipe;
HANDLE readEvent; HANDLE readEvent;
bool connected; bool connected;
bool running; bool running;
}; };
Socket::Socket() { Socket::Socket() {
d = new PrivateData; d = new PrivateData;
d->hPipe = INVALID_HANDLE_VALUE; d->hPipe = INVALID_HANDLE_VALUE;
d->connected = false; d->connected = false;
d->running = true; d->running = true;
} }
Socket::Socket(SOCKET_T hPipe) Socket::Socket(SOCKET_T hPipe)
{ {
d = new PrivateData; d = new PrivateData;
d->hPipe = hPipe; d->hPipe = hPipe;
d->connected = true; d->connected = true;
d->running = true; d->running = true;
} }
Socket::~Socket(void){ Socket::~Socket(void){
d->running = false; d->running = false;
SetEvent(d->readEvent); //signal for break SetEvent(d->readEvent); //signal for break
if (d->hPipe != INVALID_HANDLE_VALUE) { if (d->hPipe != INVALID_HANDLE_VALUE) {
CloseHandle(d->hPipe); CloseHandle(d->hPipe);
d->hPipe = 0; d->hPipe = 0;
} }
delete d; delete d;
} }
void Socket::connect(const std::wstring &server){ void Socket::connect(const std::wstring &server){
BOOL fSuccess = false; BOOL fSuccess = false;
std::wstring name(L"\\\\.\\pipe\\" + server); std::wstring name(L"\\\\.\\pipe\\" + server);
d->hPipe = CreateFile( d->hPipe = CreateFile(
(const wchar_t *)name.c_str(), // pipe name (const wchar_t *)name.c_str(), // pipe name
GENERIC_READ | // read and write access GENERIC_READ | // read and write access
GENERIC_WRITE, GENERIC_WRITE,
0, // no sharing 0, // no sharing
NULL, // default security attributes NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe OPEN_EXISTING, // opens existing pipe
FILE_FLAG_OVERLAPPED, // default attributes FILE_FLAG_OVERLAPPED, // default attributes
NULL); // no template file NULL); // no template file
if (d->hPipe == INVALID_HANDLE_VALUE) { if (d->hPipe == INVALID_HANDLE_VALUE) {
return; return;
} }
DWORD dwMode = PIPE_READMODE_MESSAGE; DWORD dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState( fSuccess = SetNamedPipeHandleState(
d->hPipe, // pipe handle d->hPipe, // pipe handle
&dwMode, // new pipe mode &dwMode, // new pipe mode
NULL, // don't set maximum bytes NULL, // don't set maximum bytes
NULL); // don't set maximum time NULL); // don't set maximum time
if (!fSuccess) { if (!fSuccess) {
return; return;
} }
d->connected = true; d->connected = true;
} }
void Socket::stopReadWait(){ void Socket::stopReadWait(){
d->running = false; d->running = false;
SetEvent(d->readEvent); SetEvent(d->readEvent);
} }
std::wstring Socket::read() { std::wstring Socket::read() {
return read(INFINITE); return read(INFINITE);
} }
std::wstring Socket::read(int timeout){ std::wstring Socket::read(int timeout){
wchar_t buf[BUFSIZE]; wchar_t buf[BUFSIZE];
int result; int result;
DWORD cbBytesRead = 0; DWORD cbBytesRead = 0;
OVERLAPPED oOverlap; OVERLAPPED oOverlap;
memset(&oOverlap, 0, sizeof(OVERLAPPED)); memset(&oOverlap, 0, sizeof(OVERLAPPED));
d->readEvent = CreateEvent(NULL, TRUE, FALSE, NULL); d->readEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
oOverlap.hEvent = d->readEvent; oOverlap.hEvent = d->readEvent;
BOOL fSuccess = false; BOOL fSuccess = false;
std::wstring returnString; std::wstring returnString;
bool moreData = true; bool moreData = true;
while(moreData){ while(moreData){
moreData = false; moreData = false;
memset(&buf, 0, sizeof(buf)); memset(&buf, 0, sizeof(buf));
ReadFile( d->hPipe, &buf, sizeof(buf)-sizeof(wchar_t), &cbBytesRead, &oOverlap); ReadFile( d->hPipe, &buf, sizeof(buf)-sizeof(wchar_t), &cbBytesRead, &oOverlap);
result = WaitForSingleObject(oOverlap.hEvent, timeout); result = WaitForSingleObject(oOverlap.hEvent, timeout);
if(!d->running){ if(!d->running){
CancelIo(d->hPipe); CancelIo(d->hPipe);
WaitForSingleObject(oOverlap.hEvent, INFINITE); WaitForSingleObject(oOverlap.hEvent, INFINITE);
d->readEvent = 0; d->readEvent = 0;
CloseHandle(oOverlap.hEvent); CloseHandle(oOverlap.hEvent);
return L""; return L"";
} }
if (result == WAIT_TIMEOUT) { if (result == WAIT_TIMEOUT) {
CancelIo(d->hPipe); CancelIo(d->hPipe);
// Cancel, we still need to cleanup // Cancel, we still need to cleanup
} }
fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &cbBytesRead, true); fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &cbBytesRead, true);
if (!fSuccess) { if (!fSuccess) {
DWORD err = GetLastError(); DWORD err = GetLastError();
if(err == ERROR_MORE_DATA){ if(err == ERROR_MORE_DATA){
moreData = true; moreData = true;
} }
else{ else{
buf[0] = 0; buf[0] = 0;
} }
if (err == ERROR_BROKEN_PIPE) { if (err == ERROR_BROKEN_PIPE) {
d->connected = false; d->connected = false;
} }
} }
returnString.append(buf); returnString.append(buf);
} }
d->readEvent = 0; d->readEvent = 0;
CloseHandle(oOverlap.hEvent); CloseHandle(oOverlap.hEvent);
return returnString; return returnString;
} }
void Socket::write(const std::wstring &msg){ void Socket::write(const std::wstring &msg){
OVERLAPPED oOverlap; OVERLAPPED oOverlap;
DWORD bytesWritten = 0; DWORD bytesWritten = 0;
int result; int result;
BOOL fSuccess = false; BOOL fSuccess = false;
memset(&oOverlap, 0, sizeof(OVERLAPPED)); memset(&oOverlap, 0, sizeof(OVERLAPPED));
HANDLE writeEvent = CreateEvent(NULL, TRUE, FALSE, NULL); HANDLE writeEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
oOverlap.hEvent = writeEvent; oOverlap.hEvent = writeEvent;
BOOL writeSuccess = WriteFile(d->hPipe, msg.data(), (DWORD)msg.length()*sizeof(wchar_t), &bytesWritten, &oOverlap); BOOL writeSuccess = WriteFile(d->hPipe, msg.data(), (DWORD)msg.length()*sizeof(wchar_t), &bytesWritten, &oOverlap);
result = GetLastError(); result = GetLastError();
if (writeSuccess || result == ERROR_IO_PENDING) { if (writeSuccess || result == ERROR_IO_PENDING) {
result = WaitForSingleObject(writeEvent, 500); result = WaitForSingleObject(writeEvent, 500);
if (result == WAIT_TIMEOUT) { if (result == WAIT_TIMEOUT) {
CancelIo(d->hPipe); CancelIo(d->hPipe);
WaitForSingleObject(oOverlap.hEvent, INFINITE); WaitForSingleObject(oOverlap.hEvent, INFINITE);
CloseHandle(writeEvent); CloseHandle(writeEvent);
CloseHandle(d->hPipe); CloseHandle(d->hPipe);
d->hPipe = 0; d->hPipe = 0;
d->connected = false; d->connected = false;
return; return;
} }
fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &bytesWritten, TRUE); fSuccess = GetOverlappedResult(d->hPipe, &oOverlap, &bytesWritten, TRUE);
} }
CloseHandle(writeEvent); CloseHandle(writeEvent);
if (!fSuccess) { if (!fSuccess) {
CloseHandle(d->hPipe); CloseHandle(d->hPipe);
d->hPipe = 0; d->hPipe = 0;
d->connected = false; d->connected = false;
return; return;
} }
} }
bool Socket::isConnected(){ bool Socket::isConnected(){
return d->connected; return d->connected;
} }

View file

@ -1,257 +1,257 @@
#include "Strings.h" #include "Strings.h"
#include <algorithm> #include <algorithm>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#ifdef _WINDOWS #ifdef _WINDOWS
#include <windows.h> #include <windows.h>
#else #else
#include <iconv.h> #include <iconv.h>
#endif #endif
#ifdef _MACOSX #ifdef _MACOSX
#define WCHAR_T_ENCODING "UCS-4-INTERNAL" #define WCHAR_T_ENCODING "UCS-4-INTERNAL"
#else #else
#define WCHAR_T_ENCODING "WCHAR_T" #define WCHAR_T_ENCODING "WCHAR_T"
#endif #endif
std::wstring TelldusCore::charToWstring(const char *value) { std::wstring TelldusCore::charToWstring(const char *value) {
#ifdef _WINDOWS #ifdef _WINDOWS
//Determine size //Determine size
int size = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0); int size = MultiByteToWideChar(CP_UTF8, 0, value, -1, NULL, 0);
if (size == 0) { if (size == 0) {
return L""; return L"";
} }
wchar_t *buffer; wchar_t *buffer;
buffer = new wchar_t[size]; buffer = new wchar_t[size];
memset(buffer, 0, sizeof(wchar_t)*(size)); memset(buffer, 0, sizeof(wchar_t)*(size));
int bytes = MultiByteToWideChar(CP_UTF8, 0, value, -1, buffer, size); int bytes = MultiByteToWideChar(CP_UTF8, 0, value, -1, buffer, size);
std::wstring retval(buffer); std::wstring retval(buffer);
delete[] buffer; delete[] buffer;
return retval; return retval;
#else #else
size_t utf8Length = strlen(value); size_t utf8Length = strlen(value);
size_t outbytesLeft = utf8Length*sizeof(wchar_t); size_t outbytesLeft = utf8Length*sizeof(wchar_t);
//Copy the instring //Copy the instring
char *inString = new char[strlen(value)+1]; char *inString = new char[strlen(value)+1];
strcpy(inString, value); strcpy(inString, value);
//Create buffer for output //Create buffer for output
char *outString = (char*)new wchar_t[utf8Length+1]; char *outString = (char*)new wchar_t[utf8Length+1];
memset(outString, 0, sizeof(wchar_t)*(utf8Length+1)); memset(outString, 0, sizeof(wchar_t)*(utf8Length+1));
#ifdef _FREEBSD #ifdef _FREEBSD
const char *inPointer = inString; const char *inPointer = inString;
#else #else
char *inPointer = inString; char *inPointer = inString;
#endif #endif
char *outPointer = outString; char *outPointer = outString;
iconv_t convDesc = iconv_open(WCHAR_T_ENCODING, "UTF-8"); iconv_t convDesc = iconv_open(WCHAR_T_ENCODING, "UTF-8");
iconv(convDesc, &inPointer, &utf8Length, &outPointer, &outbytesLeft); iconv(convDesc, &inPointer, &utf8Length, &outPointer, &outbytesLeft);
iconv_close(convDesc); iconv_close(convDesc);
std::wstring retval( (wchar_t *)outString ); std::wstring retval( (wchar_t *)outString );
//Cleanup //Cleanup
delete[] inString; delete[] inString;
delete[] outString; delete[] outString;
return retval; return retval;
#endif #endif
} }
int TelldusCore::charToInteger(const char *input){ int TelldusCore::charToInteger(const char *input){
std::stringstream inputstream; std::stringstream inputstream;
inputstream << input; inputstream << input;
int retval; int retval;
inputstream >> retval; inputstream >> retval;
return retval; return retval;
} }
std::wstring TelldusCore::charUnsignedToWstring(const unsigned char value) { std::wstring TelldusCore::charUnsignedToWstring(const unsigned char value) {
std::wstringstream st; std::wstringstream st;
st << value; st << value;
return st.str(); return st.str();
} }
/** /**
* This method doesn't support all locales * This method doesn't support all locales
*/ */
bool TelldusCore::comparei(std::wstring stringA, std::wstring stringB) { bool TelldusCore::comparei(std::wstring stringA, std::wstring stringB) {
transform(stringA.begin(), stringA.end(), stringA.begin(), toupper); transform(stringA.begin(), stringA.end(), stringA.begin(), toupper);
transform(stringB.begin(), stringB.end(), stringB.begin(), toupper); transform(stringB.begin(), stringB.end(), stringB.begin(), toupper);
return stringA == stringB; return stringA == stringB;
} }
std::wstring TelldusCore::intToWstring(int value) { std::wstring TelldusCore::intToWstring(int value) {
#ifdef _WINDOWS #ifdef _WINDOWS
//no stream used //no stream used
//TODO! Make effective and safe... //TODO! Make effective and safe...
wchar_t numstr[21]; // enough to hold all numbers up to 64-bits wchar_t numstr[21]; // enough to hold all numbers up to 64-bits
_itow_s(value, numstr, sizeof(numstr), 10); _itow_s(value, numstr, sizeof(numstr), 10);
std::wstring newstring(numstr); std::wstring newstring(numstr);
return newstring; return newstring;
//return TelldusCore::charToWstring(stdstring.c_str()); //return TelldusCore::charToWstring(stdstring.c_str());
//std::wstring temp = TelldusCore::charToWstring(stdstring.c_str()); //std::wstring temp = TelldusCore::charToWstring(stdstring.c_str());
//std::wstring temp(stdstring.length(), L' '); //std::wstring temp(stdstring.length(), L' ');
//std::copy(stdstring.begin(), stdstring.end(), temp.begin()); //std::copy(stdstring.begin(), stdstring.end(), temp.begin());
//return temp; //return temp;
#else #else
std::wstringstream st; std::wstringstream st;
st << value; st << value;
return st.str(); return st.str();
#endif #endif
} }
std::string TelldusCore::intToString(int value) { std::string TelldusCore::intToString(int value) {
//Not sure if this is neecssary (for ordinary stringstream that is) //Not sure if this is neecssary (for ordinary stringstream that is)
#ifdef _WINDOWS #ifdef _WINDOWS
char numstr[21]; // enough to hold all numbers up to 64-bits char numstr[21]; // enough to hold all numbers up to 64-bits
_itoa_s(value, numstr, sizeof(numstr), 10); _itoa_s(value, numstr, sizeof(numstr), 10);
std::string stdstring(numstr); std::string stdstring(numstr);
return stdstring; return stdstring;
#else #else
std::stringstream st; std::stringstream st;
st << value; st << value;
return st.str(); return st.str();
#endif #endif
} }
/* /*
std::wstring TelldusCore::intToWStringSafe(int value){ std::wstring TelldusCore::intToWStringSafe(int value){
#ifdef _WINDOWS #ifdef _WINDOWS
//no stream used //no stream used
//TODO! Make effective and safe... //TODO! Make effective and safe...
char numstr[21]; // enough to hold all numbers up to 64-bits char numstr[21]; // enough to hold all numbers up to 64-bits
itoa(value, numstr, 10); itoa(value, numstr, 10);
std::string stdstring(numstr); std::string stdstring(numstr);
return TelldusCore::charToWstring(stdstring.c_str()); return TelldusCore::charToWstring(stdstring.c_str());
//std::wstring temp = TelldusCore::charToWstring(stdstring.c_str()); //std::wstring temp = TelldusCore::charToWstring(stdstring.c_str());
//std::wstring temp(stdstring.length(), L' '); //std::wstring temp(stdstring.length(), L' ');
//std::copy(stdstring.begin(), stdstring.end(), temp.begin()); //std::copy(stdstring.begin(), stdstring.end(), temp.begin());
//return temp; //return temp;
#else #else
return TelldusCore::intToWString(value); return TelldusCore::intToWString(value);
#endif #endif
} }
*/ */
uint64_t TelldusCore::hexTo64l(const std::string data){ uint64_t TelldusCore::hexTo64l(const std::string data){
#ifdef _WINDOWS #ifdef _WINDOWS
return _strtoui64(data.c_str(), NULL, 16); return _strtoui64(data.c_str(), NULL, 16);
#elif defined(_MACOSX) #elif defined(_MACOSX)
return strtoq(data.c_str(), NULL, 16); return strtoq(data.c_str(), NULL, 16);
#else #else
return strtoull(data.c_str(), NULL, 16); return strtoull(data.c_str(), NULL, 16);
#endif #endif
} }
int TelldusCore::wideToInteger(const std::wstring &input){ int TelldusCore::wideToInteger(const std::wstring &input){
std::wstringstream inputstream; std::wstringstream inputstream;
inputstream << input; inputstream << input;
int retval; int retval;
inputstream >> retval; inputstream >> retval;
return retval; return retval;
} }
std::string TelldusCore::wideToString(const std::wstring &input) { std::string TelldusCore::wideToString(const std::wstring &input) {
#ifdef _WINDOWS #ifdef _WINDOWS
//Determine size //Determine size
int size = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL); int size = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL);
if (size == 0) { if (size == 0) {
return ""; return "";
} }
char *buffer; char *buffer;
buffer = new char[size]; buffer = new char[size];
memset(buffer, 0, sizeof(char)*size); memset(buffer, 0, sizeof(char)*size);
int bytes = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, buffer, size, NULL, NULL); int bytes = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, buffer, size, NULL, NULL);
std::string retval(buffer); std::string retval(buffer);
delete[] buffer; delete[] buffer;
return retval; return retval;
#else #else
size_t wideSize = sizeof(wchar_t)*input.length(); size_t wideSize = sizeof(wchar_t)*input.length();
size_t outbytesLeft = wideSize+sizeof(char); //We cannot know how many wide character there is yet size_t outbytesLeft = wideSize+sizeof(char); //We cannot know how many wide character there is yet
//Copy the instring //Copy the instring
char *inString = (char*)new wchar_t[input.length()+1]; char *inString = (char*)new wchar_t[input.length()+1];
memcpy(inString, input.c_str(), wideSize+sizeof(wchar_t)); memcpy(inString, input.c_str(), wideSize+sizeof(wchar_t));
//Create buffer for output //Create buffer for output
char *outString = new char[outbytesLeft]; char *outString = new char[outbytesLeft];
memset(outString, 0, sizeof(char)*(outbytesLeft)); memset(outString, 0, sizeof(char)*(outbytesLeft));
#ifdef _FREEBSD #ifdef _FREEBSD
const char *inPointer = inString; const char *inPointer = inString;
#else #else
char *inPointer = inString; char *inPointer = inString;
#endif #endif
char *outPointer = outString; char *outPointer = outString;
iconv_t convDesc = iconv_open("UTF-8", WCHAR_T_ENCODING); iconv_t convDesc = iconv_open("UTF-8", WCHAR_T_ENCODING);
iconv(convDesc, &inPointer, &wideSize, &outPointer, &outbytesLeft); iconv(convDesc, &inPointer, &wideSize, &outPointer, &outbytesLeft);
iconv_close(convDesc); iconv_close(convDesc);
std::string retval(outString); std::string retval(outString);
//Cleanup //Cleanup
delete[] inString; delete[] inString;
delete[] outString; delete[] outString;
return retval; return retval;
#endif #endif
} }
std::string TelldusCore::formatf(const char *format, ...) { std::string TelldusCore::formatf(const char *format, ...) {
va_list ap; va_list ap;
va_start(ap, format); va_start(ap, format);
std::string retval = sformatf(format, ap); std::string retval = sformatf(format, ap);
va_end(ap); va_end(ap);
return retval; return retval;
} }
std::string TelldusCore::sformatf(const char *format, va_list ap) { std::string TelldusCore::sformatf(const char *format, va_list ap) {
//This code is based on code from the Linux man-pages project (man vsprintf) //This code is based on code from the Linux man-pages project (man vsprintf)
int n; int n;
int size = 100; /* Guess we need no more than 100 bytes. */ int size = 100; /* Guess we need no more than 100 bytes. */
char *p, *np; char *p, *np;
if ((p = (char*)malloc(size)) == NULL) { if ((p = (char*)malloc(size)) == NULL) {
return ""; return "";
} }
while (1) { while (1) {
/* Try to print in the allocated space. */ /* Try to print in the allocated space. */
n = vsnprintf(p, size, format, ap); n = vsnprintf(p, size, format, ap);
/* If that worked, return the string. */ /* If that worked, return the string. */
if (n > -1 && n < size) { if (n > -1 && n < size) {
std::string retval(p); std::string retval(p);
free(p); free(p);
return retval; return retval;
} }
/* Else try again with more space. */ /* Else try again with more space. */
if (n > -1) { /* glibc 2.1 */ if (n > -1) { /* glibc 2.1 */
size = n+1; /* precisely what is needed */ size = n+1; /* precisely what is needed */
} else { /* glibc 2.0 */ } else { /* glibc 2.0 */
size *= 2; /* twice the old size */ size *= 2; /* twice the old size */
} }
if ((np = (char *)realloc (p, size)) == NULL) { if ((np = (char *)realloc (p, size)) == NULL) {
free(p); free(p);
return ""; return "";
} else { } else {
p = np; p = np;
} }
} }
} }

View file

@ -1,33 +1,33 @@
#ifndef STRING_H #ifndef STRING_H
#define STRING_H #define STRING_H
#include <string> #include <string>
#include <stdarg.h> #include <stdarg.h>
#ifdef _MSC_VER #ifdef _MSC_VER
typedef unsigned __int8 uint8_t; typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t; typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t; typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t; typedef unsigned __int64 uint64_t;
#else #else
#include <stdint.h> #include <stdint.h>
#endif #endif
namespace TelldusCore { namespace TelldusCore {
std::wstring charToWstring(const char *value); std::wstring charToWstring(const char *value);
int charToInteger(const char *value); int charToInteger(const char *value);
std::wstring charUnsignedToWstring(const unsigned char value); std::wstring charUnsignedToWstring(const unsigned char value);
bool comparei(std::wstring stringA, std::wstring stringB); bool comparei(std::wstring stringA, std::wstring stringB);
std::wstring intToWstring(int value); std::wstring intToWstring(int value);
//std::wstring intToWStringSafe(int value); //std::wstring intToWStringSafe(int value);
std::string intToString(int value); std::string intToString(int value);
uint64_t hexTo64l(const std::string data); uint64_t hexTo64l(const std::string data);
std::string wideToString(const std::wstring &input); std::string wideToString(const std::wstring &input);
int wideToInteger(const std::wstring &input); int wideToInteger(const std::wstring &input);
std::string formatf(const char *format, ...); std::string formatf(const char *format, ...);
std::string sformatf(const char *format, va_list ap); std::string sformatf(const char *format, va_list ap);
} }
#endif //STRING_H #endif //STRING_H

View file

@ -1,252 +1,252 @@
IF(COMMAND cmake_policy) IF(COMMAND cmake_policy)
CMAKE_POLICY(SET CMP0003 NEW) CMAKE_POLICY(SET CMP0003 NEW)
ENDIF(COMMAND cmake_policy) ENDIF(COMMAND cmake_policy)
FIND_PACKAGE( SignTool REQUIRED ) FIND_PACKAGE( SignTool REQUIRED )
SET (telldusd_DESCRIPTION SET (telldusd_DESCRIPTION
"background service for Telldus TellStick, must be running to control TellStick" "background service for Telldus TellStick, must be running to control TellStick"
) )
ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" ) ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" )
######## Non configurable options ######## ######## Non configurable options ########
SET( telldus-service_SRCS SET( telldus-service_SRCS
ClientCommunicationHandler.cpp ClientCommunicationHandler.cpp
Controller.cpp Controller.cpp
ControllerManager.cpp ControllerManager.cpp
ControllerMessage.cpp ControllerMessage.cpp
Device.cpp Device.cpp
DeviceManager.cpp DeviceManager.cpp
Log.cpp Log.cpp
Sensor.cpp Sensor.cpp
Settings.cpp Settings.cpp
TelldusMain.cpp TelldusMain.cpp
TellStick.cpp TellStick.cpp
Timer.cpp Timer.cpp
EventUpdateManager.cpp EventUpdateManager.cpp
) )
SET( telldus-service_protocol_SRCS SET( telldus-service_protocol_SRCS
Protocol.h Protocol.h
Protocol.cpp Protocol.cpp
ProtocolBrateck.h ProtocolBrateck.h
ProtocolBrateck.cpp ProtocolBrateck.cpp
ProtocolComen.h ProtocolComen.h
ProtocolComen.cpp ProtocolComen.cpp
ProtocolEverflourish.h ProtocolEverflourish.h
ProtocolEverflourish.cpp ProtocolEverflourish.cpp
ProtocolFineoffset.h ProtocolFineoffset.h
ProtocolFineoffset.cpp ProtocolFineoffset.cpp
ProtocolFuhaote.h ProtocolFuhaote.h
ProtocolFuhaote.cpp ProtocolFuhaote.cpp
ProtocolGroup.h ProtocolGroup.h
ProtocolGroup.cpp ProtocolGroup.cpp
ProtocolHasta.h ProtocolHasta.h
ProtocolHasta.cpp ProtocolHasta.cpp
ProtocolIkea.h ProtocolIkea.h
ProtocolIkea.cpp ProtocolIkea.cpp
ProtocolMandolyn.h ProtocolMandolyn.h
ProtocolMandolyn.cpp ProtocolMandolyn.cpp
ProtocolNexa.h ProtocolNexa.h
ProtocolNexa.cpp ProtocolNexa.cpp
ProtocolOregon.h ProtocolOregon.h
ProtocolOregon.cpp ProtocolOregon.cpp
ProtocolRisingSun.h ProtocolRisingSun.h
ProtocolRisingSun.cpp ProtocolRisingSun.cpp
ProtocolSartano.h ProtocolSartano.h
ProtocolSartano.cpp ProtocolSartano.cpp
ProtocolScene.h ProtocolScene.h
ProtocolScene.cpp ProtocolScene.cpp
ProtocolSilvanChip.h ProtocolSilvanChip.h
ProtocolSilvanChip.cpp ProtocolSilvanChip.cpp
ProtocolUpm.h ProtocolUpm.h
ProtocolUpm.cpp ProtocolUpm.cpp
ProtocolWaveman.h ProtocolWaveman.h
ProtocolWaveman.cpp ProtocolWaveman.cpp
ProtocolX10.h ProtocolX10.h
ProtocolX10.cpp ProtocolX10.cpp
ProtocolYidong.h ProtocolYidong.h
ProtocolYidong.cpp ProtocolYidong.cpp
) )
SET( telldus-service_HDRS SET( telldus-service_HDRS
ClientCommunicationHandler.h ClientCommunicationHandler.h
ConnectionListener.h ConnectionListener.h
Controller.h Controller.h
ControllerListener.h ControllerListener.h
ControllerManager.h ControllerManager.h
ControllerMessage.h ControllerMessage.h
Device.h Device.h
DeviceManager.h DeviceManager.h
EventUpdateManager.h EventUpdateManager.h
Log.h Log.h
Sensor.h Sensor.h
Settings.h Settings.h
TelldusMain.h TelldusMain.h
TellStick.h TellStick.h
Timer.h Timer.h
) )
FIND_PACKAGE(Threads REQUIRED) FIND_PACKAGE(Threads REQUIRED)
LIST(APPEND telldus-service_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) LIST(APPEND telldus-service_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_SOURCE_DIR}/../common ${CMAKE_CURRENT_SOURCE_DIR}/../common
) )
######## Configurable options for the platform ######## ######## Configurable options for the platform ########
######## Platforms-specific, non configurable ######## ######## Platforms-specific, non configurable ########
IF (APPLE) #### Mac OS X #### IF (APPLE) #### Mac OS X ####
SET(DEFAULT_FTDI_ENGINE "ftd2xx") SET(DEFAULT_FTDI_ENGINE "ftd2xx")
SET( telldus-service_TARGET TelldusService ) SET( telldus-service_TARGET TelldusService )
ADD_DEFINITIONS( -D_MACOSX ) ADD_DEFINITIONS( -D_MACOSX )
FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation) FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation)
FIND_LIBRARY(IOKIT_LIBRARY IOKit) FIND_LIBRARY(IOKIT_LIBRARY IOKit)
SET( telldus-service_LIBRARIES SET( telldus-service_LIBRARIES
${telldus-service_LIBRARIES} ${telldus-service_LIBRARIES}
${COREFOUNDATION_LIBRARY} ${COREFOUNDATION_LIBRARY}
${IOKIT_LIBRARY} ${IOKIT_LIBRARY}
TelldusCommon TelldusCommon
) )
LIST(APPEND telldus-service_SRCS LIST(APPEND telldus-service_SRCS
main_mac.cpp main_mac.cpp
ConnectionListener_unix.cpp ConnectionListener_unix.cpp
ControllerListener_mac.cpp ControllerListener_mac.cpp
SettingsCoreFoundationPreferences.cpp SettingsCoreFoundationPreferences.cpp
) )
ELSEIF (WIN32) #### Windows #### ELSEIF (WIN32) #### Windows ####
SET(DEFAULT_FTDI_ENGINE "ftd2xx") SET(DEFAULT_FTDI_ENGINE "ftd2xx")
SET( telldus-service_TARGET TelldusService ) SET( telldus-service_TARGET TelldusService )
ADD_DEFINITIONS( -DUNICODE ) ADD_DEFINITIONS( -DUNICODE )
ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No ADD_DEFINITIONS( /Zc:wchar_t- ) # Treat wchar_t as Built-in Type' = No
SET(CMAKE_EXE_LINKER_FLAGS SET(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE" "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE"
) )
LIST(APPEND telldus-service_LIBRARIES LIST(APPEND telldus-service_LIBRARIES
TelldusCommon TelldusCommon
) )
LIST(APPEND telldus-service_SRCS LIST(APPEND telldus-service_SRCS
ConnectionListener_win.cpp ConnectionListener_win.cpp
main_win.cpp main_win.cpp
SettingsWinRegistry.cpp SettingsWinRegistry.cpp
TelldusWinService_win.cpp TelldusWinService_win.cpp
Messages.mc Messages.mc
${CMAKE_CURRENT_BINARY_DIR}/Messages.rc ${CMAKE_CURRENT_BINARY_DIR}/Messages.rc
${CMAKE_CURRENT_BINARY_DIR}/Messages.h ${CMAKE_CURRENT_BINARY_DIR}/Messages.h
) )
LIST(APPEND telldus-service_HDRS LIST(APPEND telldus-service_HDRS
TelldusWinService_win.h TelldusWinService_win.h
) )
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
OUTPUT Messages.rc Messages.h OUTPUT Messages.rc Messages.h
COMMAND mc.exe -u -r \"${CMAKE_CURRENT_BINARY_DIR}\" -h \"${CMAKE_CURRENT_BINARY_DIR}\" \"${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc\" COMMAND mc.exe -u -r \"${CMAKE_CURRENT_BINARY_DIR}\" -h \"${CMAKE_CURRENT_BINARY_DIR}\" \"${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc\"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Messages.mc
DEPENDS Messages.rc DEPENDS Messages.rc
COMMENT "Compiling Messages Resource" COMMENT "Compiling Messages Resource"
) )
INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} ) INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_BINARY_DIR} )
ELSE (APPLE) #### Linux #### ELSE (APPLE) #### Linux ####
SET(DEFAULT_FTDI_ENGINE "libftdi") SET(DEFAULT_FTDI_ENGINE "libftdi")
FIND_LIBRARY(CONFUSE_LIBRARY confuse) FIND_LIBRARY(CONFUSE_LIBRARY confuse)
ADD_DEFINITIONS( -D_CONFUSE ) ADD_DEFINITIONS( -D_CONFUSE )
ADD_DEFINITIONS( -D_LINUX ) ADD_DEFINITIONS( -D_LINUX )
SET( telldus-service_TARGET telldusd ) SET( telldus-service_TARGET telldusd )
LIST(APPEND telldus-service_SRCS LIST(APPEND telldus-service_SRCS
ConnectionListener_unix.cpp ConnectionListener_unix.cpp
main_unix.cpp main_unix.cpp
SettingsConfuse.cpp SettingsConfuse.cpp
) )
LIST(APPEND telldus-service_LIBRARIES LIST(APPEND telldus-service_LIBRARIES
${CONFUSE_LIBRARY} ${CONFUSE_LIBRARY}
TelldusCommon TelldusCommon
) )
ENDIF (APPLE) ENDIF (APPLE)
SET(FTDI_ENGINE ${DEFAULT_FTDI_ENGINE} CACHE STRING "Which FTDI engine to use. This could be either 'libftdi' or 'ftd2xx'") SET(FTDI_ENGINE ${DEFAULT_FTDI_ENGINE} CACHE STRING "Which FTDI engine to use. This could be either 'libftdi' or 'ftd2xx'")
IF (FTDI_ENGINE STREQUAL "ftd2xx") IF (FTDI_ENGINE STREQUAL "ftd2xx")
FIND_LIBRARY(FTD2XX_LIBRARY ftd2xx) FIND_LIBRARY(FTD2XX_LIBRARY ftd2xx)
ADD_DEFINITIONS( -DLIBFTD2XX ) ADD_DEFINITIONS( -DLIBFTD2XX )
LIST(APPEND telldus-service_SRCS TellStick_ftd2xx.cpp ) LIST(APPEND telldus-service_SRCS TellStick_ftd2xx.cpp )
LIST(APPEND telldus-service_LIBRARIES ${FTD2XX_LIBRARY}) LIST(APPEND telldus-service_LIBRARIES ${FTD2XX_LIBRARY})
ELSE (FTDI_ENGINE STREQUAL "ftd2xx") ELSE (FTDI_ENGINE STREQUAL "ftd2xx")
FIND_LIBRARY(FTDI_LIBRARY ftdi) FIND_LIBRARY(FTDI_LIBRARY ftdi)
INCLUDE(FindPkgConfig) INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(FTDI libftdi) PKG_SEARCH_MODULE(FTDI libftdi)
INCLUDE_DIRECTORIES( ${FTDI_INCLUDEDIR} ) INCLUDE_DIRECTORIES( ${FTDI_INCLUDEDIR} )
ADD_DEFINITIONS( -DLIBFTDI ) ADD_DEFINITIONS( -DLIBFTDI )
LIST(APPEND telldus-service_SRCS TellStick_libftdi.cpp ) LIST(APPEND telldus-service_SRCS TellStick_libftdi.cpp )
LIST(APPEND telldus-service_LIBRARIES ${FTDI_LIBRARY}) LIST(APPEND telldus-service_LIBRARIES ${FTDI_LIBRARY})
ENDIF (FTDI_ENGINE STREQUAL "ftd2xx") ENDIF (FTDI_ENGINE STREQUAL "ftd2xx")
######## Configuring ######## ######## Configuring ########
SOURCE_GROUP("Protocol Files" FILES ${telldus-service_protocol_SRCS}) SOURCE_GROUP("Protocol Files" FILES ${telldus-service_protocol_SRCS})
ADD_EXECUTABLE(${telldus-service_TARGET} ADD_EXECUTABLE(${telldus-service_TARGET}
${telldus-service_SRCS} ${telldus-service_SRCS}
${telldus-service_protocol_SRCS} ${telldus-service_protocol_SRCS}
${telldus-service_HDRS} ${telldus-service_HDRS}
) )
ADD_DEPENDENCIES(${telldus-service_TARGET} TelldusCommon) ADD_DEPENDENCIES(${telldus-service_TARGET} TelldusCommon)
SET_SOURCE_FILES_PROPERTIES(${telldus-service_RESOURCES} PROPERTIES MACOSX_PACKAGE_LOCATION Resources) SET_SOURCE_FILES_PROPERTIES(${telldus-service_RESOURCES} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
TARGET_LINK_LIBRARIES( ${telldus-service_TARGET} ${telldus-service_LIBRARIES} ) TARGET_LINK_LIBRARIES( ${telldus-service_TARGET} ${telldus-service_LIBRARIES} )
SIGN(${telldus-service_TARGET}) SIGN(${telldus-service_TARGET})
SET_TARGET_PROPERTIES(${telldus-service_TARGET} PROPERTIES SET_TARGET_PROPERTIES(${telldus-service_TARGET} PROPERTIES
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist
) )
IF (APPLE) IF (APPLE)
SET(TELLDUS_SERVICE_TARGET_PATH "/Library/Telldus" CACHE STRING "Path to install TelldusService") SET(TELLDUS_SERVICE_TARGET_PATH "/Library/Telldus" CACHE STRING "Path to install TelldusService")
SET_TARGET_PROPERTIES(${telldus-service_TARGET} PROPERTIES SET_TARGET_PROPERTIES(${telldus-service_TARGET} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
) )
INSTALL(TARGETS ${telldus-service_TARGET} INSTALL(TARGETS ${telldus-service_TARGET}
RUNTIME DESTINATION ${TELLDUS_SERVICE_TARGET_PATH} RUNTIME DESTINATION ${TELLDUS_SERVICE_TARGET_PATH}
) )
INSTALL(CODE " INSTALL(CODE "
INCLUDE(GetPrerequisites) INCLUDE(GetPrerequisites)
GET_FILENAME_COMPONENT(DESTDIR \$ENV{DESTDIR} ABSOLUTE) GET_FILENAME_COMPONENT(DESTDIR \$ENV{DESTDIR} ABSOLUTE)
GET_PREREQUISITES(\"\${DESTDIR}/${TELLDUS_SERVICE_TARGET_PATH}/${telldus-service_TARGET}\" prereqs 1 0 \"\$\" \"\$\") GET_PREREQUISITES(\"\${DESTDIR}/${TELLDUS_SERVICE_TARGET_PATH}/${telldus-service_TARGET}\" prereqs 1 0 \"\$\" \"\$\")
FOREACH(pr \${prereqs}) FOREACH(pr \${prereqs})
GET_FILENAME_COMPONENT(lib \${pr} NAME) GET_FILENAME_COMPONENT(lib \${pr} NAME)
FILE(INSTALL \${pr} DESTINATION ${TELLDUS_SERVICE_TARGET_PATH}) FILE(INSTALL \${pr} DESTINATION ${TELLDUS_SERVICE_TARGET_PATH})
EXECUTE_PROCESS(COMMAND install_name_tool EXECUTE_PROCESS(COMMAND install_name_tool
-change \"\${pr}\" \"${TELLDUS_SERVICE_TARGET_PATH}/\${lib}\" \"\${DESTDIR}/${TELLDUS_SERVICE_TARGET_PATH}/${telldus-service_TARGET}\" -change \"\${pr}\" \"${TELLDUS_SERVICE_TARGET_PATH}/\${lib}\" \"\${DESTDIR}/${TELLDUS_SERVICE_TARGET_PATH}/${telldus-service_TARGET}\"
) )
ENDFOREACH () ENDFOREACH ()
") ")
INSTALL(FILES com.telldus.service.plist DESTINATION /Library/LaunchDaemons) INSTALL(FILES com.telldus.service.plist DESTINATION /Library/LaunchDaemons)
ENDIF (APPLE) ENDIF (APPLE)
IF (UNIX) IF (UNIX)
IF (GENERATE_MAN) IF (GENERATE_MAN)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET ${telldus-service_TARGET} TARGET ${telldus-service_TARGET}
POST_BUILD POST_BUILD
COMMAND help2man -n ${telldusd_DESCRIPTION} ./telldusd > telldusd.1 COMMAND help2man -n ${telldusd_DESCRIPTION} ./telldusd > telldusd.1
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating man file telldusd.1" COMMENT "Generating man file telldusd.1"
) )
INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/telldusd.1 DESTINATION share/man/man1) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/telldusd.1 DESTINATION share/man/man1)
ENDIF (GENERATE_MAN) ENDIF (GENERATE_MAN)
ENDIF (UNIX) ENDIF (UNIX)
IF (UNIX AND NOT APPLE) IF (UNIX AND NOT APPLE)
INSTALL(TARGETS ${telldus-service_TARGET} RUNTIME DESTINATION sbin) INSTALL(TARGETS ${telldus-service_TARGET} RUNTIME DESTINATION sbin)
SET(SYSCONF_INSTALL_DIR "/etc" CACHE PATH "The sysconfig install dir (default prefix/etc)" ) SET(SYSCONF_INSTALL_DIR "/etc" CACHE PATH "The sysconfig install dir (default prefix/etc)" )
SET(STATE_INSTALL_DIR "/var/state" CACHE PATH "The directory to store state information of the devices" ) SET(STATE_INSTALL_DIR "/var/state" CACHE PATH "The directory to store state information of the devices" )
INSTALL(FILES tellstick.conf INSTALL(FILES tellstick.conf
DESTINATION ${SYSCONF_INSTALL_DIR} DESTINATION ${SYSCONF_INSTALL_DIR}
) )
INSTALL(FILES telldus-core.conf INSTALL(FILES telldus-core.conf
DESTINATION ${STATE_INSTALL_DIR} DESTINATION ${STATE_INSTALL_DIR}
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE WORLD_READ WORLD_WRITE PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE WORLD_READ WORLD_WRITE
) )
ENDIF (UNIX AND NOT APPLE) ENDIF (UNIX AND NOT APPLE)

View file

@ -1,265 +1,265 @@
#include "ClientCommunicationHandler.h" #include "ClientCommunicationHandler.h"
#include "Message.h" #include "Message.h"
#include "Strings.h" #include "Strings.h"
#include <stdlib.h> #include <stdlib.h>
class ClientCommunicationHandler::PrivateData { class ClientCommunicationHandler::PrivateData {
public: public:
TelldusCore::Socket *clientSocket; TelldusCore::Socket *clientSocket;
TelldusCore::EventRef event, deviceUpdateEvent; TelldusCore::EventRef event, deviceUpdateEvent;
bool done; bool done;
DeviceManager *deviceManager; DeviceManager *deviceManager;
ControllerManager *controllerManager; ControllerManager *controllerManager;
}; };
ClientCommunicationHandler::ClientCommunicationHandler(){ ClientCommunicationHandler::ClientCommunicationHandler(){
} }
ClientCommunicationHandler::ClientCommunicationHandler(TelldusCore::Socket *clientSocket, TelldusCore::EventRef event, DeviceManager *deviceManager, TelldusCore::EventRef deviceUpdateEvent, ControllerManager *controllerManager) ClientCommunicationHandler::ClientCommunicationHandler(TelldusCore::Socket *clientSocket, TelldusCore::EventRef event, DeviceManager *deviceManager, TelldusCore::EventRef deviceUpdateEvent, ControllerManager *controllerManager)
:Thread() :Thread()
{ {
d = new PrivateData; d = new PrivateData;
d->clientSocket = clientSocket; d->clientSocket = clientSocket;
d->event = event; d->event = event;
d->done = false; d->done = false;
d->deviceManager = deviceManager; d->deviceManager = deviceManager;
d->deviceUpdateEvent = deviceUpdateEvent; d->deviceUpdateEvent = deviceUpdateEvent;
d->controllerManager = controllerManager; d->controllerManager = controllerManager;
} }
ClientCommunicationHandler::~ClientCommunicationHandler(void) ClientCommunicationHandler::~ClientCommunicationHandler(void)
{ {
wait(); wait();
delete(d->clientSocket); delete(d->clientSocket);
delete d; delete d;
} }
void ClientCommunicationHandler::run(){ void ClientCommunicationHandler::run(){
//run thread //run thread
std::wstring clientMessage = d->clientSocket->read(2000); std::wstring clientMessage = d->clientSocket->read(2000);
int intReturn; int intReturn;
std::wstring strReturn; std::wstring strReturn;
strReturn = L""; strReturn = L"";
parseMessage(clientMessage, &intReturn, &strReturn); parseMessage(clientMessage, &intReturn, &strReturn);
TelldusCore::Message msg; TelldusCore::Message msg;
if(strReturn == L""){ if(strReturn == L""){
msg.addArgument(intReturn); msg.addArgument(intReturn);
} }
else{ else{
msg.addArgument(strReturn); msg.addArgument(strReturn);
} }
msg.append(L"\n"); msg.append(L"\n");
d->clientSocket->write(msg); d->clientSocket->write(msg);
//We are done, signal for removal //We are done, signal for removal
d->done = true; d->done = true;
d->event->signal(); d->event->signal();
} }
bool ClientCommunicationHandler::isDone(){ bool ClientCommunicationHandler::isDone(){
return d->done; return d->done;
} }
void ClientCommunicationHandler::parseMessage(const std::wstring &clientMessage, int *intReturn, std::wstring *wstringReturn){ void ClientCommunicationHandler::parseMessage(const std::wstring &clientMessage, int *intReturn, std::wstring *wstringReturn){
(*intReturn) = 0; (*intReturn) = 0;
(*wstringReturn) = L""; (*wstringReturn) = L"";
std::wstring msg(clientMessage); //Copy std::wstring msg(clientMessage); //Copy
std::wstring function(TelldusCore::Message::takeString(&msg)); std::wstring function(TelldusCore::Message::takeString(&msg));
if (function == L"tdTurnOn") { if (function == L"tdTurnOn") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_TURNON, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_TURNON, 0);
} else if (function == L"tdTurnOff") { } else if (function == L"tdTurnOff") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_TURNOFF, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_TURNOFF, 0);
} else if (function == L"tdBell") { } else if (function == L"tdBell") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_BELL, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_BELL, 0);
} else if (function == L"tdDim") { } else if (function == L"tdDim") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
int level = TelldusCore::Message::takeInt(&msg); int level = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_DIM, level); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_DIM, level);
} else if (function == L"tdExecute") { } else if (function == L"tdExecute") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_EXECUTE, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_EXECUTE, 0);
} else if (function == L"tdUp") { } else if (function == L"tdUp") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_UP, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_UP, 0);
} else if (function == L"tdDown") { } else if (function == L"tdDown") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_DOWN, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_DOWN, 0);
} else if (function == L"tdStop") { } else if (function == L"tdStop") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_STOP, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_STOP, 0);
} else if (function == L"tdLearn") { } else if (function == L"tdLearn") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_LEARN, 0); (*intReturn) = d->deviceManager->doAction(deviceId, TELLSTICK_LEARN, 0);
} else if (function == L"tdLastSentCommand") { } else if (function == L"tdLastSentCommand") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
int methodsSupported = TelldusCore::Message::takeInt(&msg); int methodsSupported = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->getDeviceLastSentCommand(deviceId, methodsSupported); (*intReturn) = d->deviceManager->getDeviceLastSentCommand(deviceId, methodsSupported);
} else if (function == L"tdLastSentValue") { } else if (function == L"tdLastSentValue") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*wstringReturn) = d->deviceManager->getDeviceStateValue(deviceId); (*wstringReturn) = d->deviceManager->getDeviceStateValue(deviceId);
} else if(function == L"tdGetNumberOfDevices"){ } else if(function == L"tdGetNumberOfDevices"){
(*intReturn) = d->deviceManager->getNumberOfDevices(); (*intReturn) = d->deviceManager->getNumberOfDevices();
} else if (function == L"tdGetDeviceId") { } else if (function == L"tdGetDeviceId") {
int deviceIndex = TelldusCore::Message::takeInt(&msg); int deviceIndex = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->getDeviceId(deviceIndex); (*intReturn) = d->deviceManager->getDeviceId(deviceIndex);
} else if (function == L"tdGetDeviceType") { } else if (function == L"tdGetDeviceType") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->getDeviceType(deviceId); (*intReturn) = d->deviceManager->getDeviceType(deviceId);
} else if (function == L"tdGetName") { } else if (function == L"tdGetName") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*wstringReturn) = d->deviceManager->getDeviceName(deviceId); (*wstringReturn) = d->deviceManager->getDeviceName(deviceId);
} else if (function == L"tdSetName") { } else if (function == L"tdSetName") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
std::wstring name = TelldusCore::Message::takeString(&msg); std::wstring name = TelldusCore::Message::takeString(&msg);
(*intReturn) = d->deviceManager->setDeviceName(deviceId, name); (*intReturn) = d->deviceManager->setDeviceName(deviceId, name);
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_NAME); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_NAME);
} else if (function == L"tdGetProtocol") { } else if (function == L"tdGetProtocol") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*wstringReturn) = d->deviceManager->getDeviceProtocol(deviceId); (*wstringReturn) = d->deviceManager->getDeviceProtocol(deviceId);
} else if (function == L"tdSetProtocol") { } else if (function == L"tdSetProtocol") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
std::wstring protocol = TelldusCore::Message::takeString(&msg); std::wstring protocol = TelldusCore::Message::takeString(&msg);
int oldMethods = d->deviceManager->getDeviceMethods(deviceId); int oldMethods = d->deviceManager->getDeviceMethods(deviceId);
(*intReturn) = d->deviceManager->setDeviceProtocol(deviceId, protocol); (*intReturn) = d->deviceManager->setDeviceProtocol(deviceId, protocol);
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_PROTOCOL); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_PROTOCOL);
if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){ if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD);
} }
} else if (function == L"tdGetModel") { } else if (function == L"tdGetModel") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*wstringReturn) = d->deviceManager->getDeviceModel(deviceId); (*wstringReturn) = d->deviceManager->getDeviceModel(deviceId);
} else if (function == L"tdSetModel") { } else if (function == L"tdSetModel") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
std::wstring model = TelldusCore::Message::takeString(&msg); std::wstring model = TelldusCore::Message::takeString(&msg);
int oldMethods = d->deviceManager->getDeviceMethods(deviceId); int oldMethods = d->deviceManager->getDeviceMethods(deviceId);
(*intReturn) = d->deviceManager->setDeviceModel(deviceId, model); (*intReturn) = d->deviceManager->setDeviceModel(deviceId, model);
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_MODEL); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_MODEL);
if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){ if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD);
} }
} else if (function == L"tdGetDeviceParameter") { } else if (function == L"tdGetDeviceParameter") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
std::wstring name = TelldusCore::Message::takeString(&msg); std::wstring name = TelldusCore::Message::takeString(&msg);
std::wstring defaultValue = TelldusCore::Message::takeString(&msg); std::wstring defaultValue = TelldusCore::Message::takeString(&msg);
(*wstringReturn) = d->deviceManager->getDeviceParameter(deviceId, name, defaultValue); (*wstringReturn) = d->deviceManager->getDeviceParameter(deviceId, name, defaultValue);
} else if (function == L"tdSetDeviceParameter") { } else if (function == L"tdSetDeviceParameter") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
std::wstring name = TelldusCore::Message::takeString(&msg); std::wstring name = TelldusCore::Message::takeString(&msg);
std::wstring value = TelldusCore::Message::takeString(&msg); std::wstring value = TelldusCore::Message::takeString(&msg);
int oldMethods = d->deviceManager->getDeviceMethods(deviceId); int oldMethods = d->deviceManager->getDeviceMethods(deviceId);
(*intReturn) = d->deviceManager->setDeviceParameter(deviceId, name, value); (*intReturn) = d->deviceManager->setDeviceParameter(deviceId, name, value);
if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){ if(oldMethods != d->deviceManager->getDeviceMethods(deviceId)){
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_METHOD);
} }
} else if (function == L"tdAddDevice") { } else if (function == L"tdAddDevice") {
(*intReturn) = d->deviceManager->addDevice(); (*intReturn) = d->deviceManager->addDevice();
if((*intReturn) >= 0){ if((*intReturn) >= 0){
sendDeviceSignal((*intReturn), TELLSTICK_DEVICE_ADDED, 0); sendDeviceSignal((*intReturn), TELLSTICK_DEVICE_ADDED, 0);
} }
} else if (function == L"tdRemoveDevice") { } else if (function == L"tdRemoveDevice") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->removeDevice(deviceId); (*intReturn) = d->deviceManager->removeDevice(deviceId);
if((*intReturn) == TELLSTICK_SUCCESS){ if((*intReturn) == TELLSTICK_SUCCESS){
sendDeviceSignal(deviceId, TELLSTICK_DEVICE_REMOVED, 0); sendDeviceSignal(deviceId, TELLSTICK_DEVICE_REMOVED, 0);
} }
} else if (function == L"tdMethods") { } else if (function == L"tdMethods") {
int deviceId = TelldusCore::Message::takeInt(&msg); int deviceId = TelldusCore::Message::takeInt(&msg);
int intMethodsSupported = TelldusCore::Message::takeInt(&msg); int intMethodsSupported = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->getDeviceMethods(deviceId, intMethodsSupported); (*intReturn) = d->deviceManager->getDeviceMethods(deviceId, intMethodsSupported);
} else if (function == L"tdSendRawCommand") { } else if (function == L"tdSendRawCommand") {
std::wstring command = TelldusCore::Message::takeString(&msg); std::wstring command = TelldusCore::Message::takeString(&msg);
int reserved = TelldusCore::Message::takeInt(&msg); int reserved = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->deviceManager->sendRawCommand(command, reserved); (*intReturn) = d->deviceManager->sendRawCommand(command, reserved);
} else if (function == L"tdConnectTellStickController") { } else if (function == L"tdConnectTellStickController") {
int vid = TelldusCore::Message::takeInt(&msg); int vid = TelldusCore::Message::takeInt(&msg);
int pid = TelldusCore::Message::takeInt(&msg); int pid = TelldusCore::Message::takeInt(&msg);
std::string serial = TelldusCore::wideToString(TelldusCore::Message::takeString(&msg)); std::string serial = TelldusCore::wideToString(TelldusCore::Message::takeString(&msg));
d->deviceManager->connectTellStickController(vid, pid, serial); d->deviceManager->connectTellStickController(vid, pid, serial);
} else if (function == L"tdDisconnectTellStickController") { } else if (function == L"tdDisconnectTellStickController") {
int vid = TelldusCore::Message::takeInt(&msg); int vid = TelldusCore::Message::takeInt(&msg);
int pid = TelldusCore::Message::takeInt(&msg); int pid = TelldusCore::Message::takeInt(&msg);
std::string serial = TelldusCore::wideToString(TelldusCore::Message::takeString(&msg)); std::string serial = TelldusCore::wideToString(TelldusCore::Message::takeString(&msg));
d->deviceManager->disconnectTellStickController(vid, pid, serial); d->deviceManager->disconnectTellStickController(vid, pid, serial);
} else if (function == L"tdSensor") { } else if (function == L"tdSensor") {
(*wstringReturn) = d->deviceManager->getSensors(); (*wstringReturn) = d->deviceManager->getSensors();
} else if (function == L"tdSensorValue") { } else if (function == L"tdSensorValue") {
std::wstring protocol = TelldusCore::Message::takeString(&msg); std::wstring protocol = TelldusCore::Message::takeString(&msg);
std::wstring model = TelldusCore::Message::takeString(&msg); std::wstring model = TelldusCore::Message::takeString(&msg);
int id = TelldusCore::Message::takeInt(&msg); int id = TelldusCore::Message::takeInt(&msg);
int dataType = TelldusCore::Message::takeInt(&msg); int dataType = TelldusCore::Message::takeInt(&msg);
(*wstringReturn) = d->deviceManager->getSensorValue(protocol, model, id, dataType); (*wstringReturn) = d->deviceManager->getSensorValue(protocol, model, id, dataType);
} else if (function == L"tdController") { } else if (function == L"tdController") {
(*wstringReturn) = d->controllerManager->getControllers(); (*wstringReturn) = d->controllerManager->getControllers();
} else if (function == L"tdControllerValue") { } else if (function == L"tdControllerValue") {
int id = TelldusCore::Message::takeInt(&msg); int id = TelldusCore::Message::takeInt(&msg);
std::wstring name = TelldusCore::Message::takeString(&msg); std::wstring name = TelldusCore::Message::takeString(&msg);
(*wstringReturn) = d->controllerManager->getControllerValue(id, name); (*wstringReturn) = d->controllerManager->getControllerValue(id, name);
} else if (function == L"tdSetControllerValue") { } else if (function == L"tdSetControllerValue") {
int id = TelldusCore::Message::takeInt(&msg); int id = TelldusCore::Message::takeInt(&msg);
std::wstring name = TelldusCore::Message::takeString(&msg); std::wstring name = TelldusCore::Message::takeString(&msg);
std::wstring value = TelldusCore::Message::takeString(&msg); std::wstring value = TelldusCore::Message::takeString(&msg);
(*intReturn) = d->controllerManager->setControllerValue(id, name, value); (*intReturn) = d->controllerManager->setControllerValue(id, name, value);
} else if (function == L"tdRemoveController") { } else if (function == L"tdRemoveController") {
int controllerId = TelldusCore::Message::takeInt(&msg); int controllerId = TelldusCore::Message::takeInt(&msg);
(*intReturn) = d->controllerManager->removeController(controllerId); (*intReturn) = d->controllerManager->removeController(controllerId);
} else{ } else{
(*intReturn) = TELLSTICK_ERROR_UNKNOWN; (*intReturn) = TELLSTICK_ERROR_UNKNOWN;
} }
} }
void ClientCommunicationHandler::sendDeviceSignal(int deviceId, int eventDeviceChanges, int eventChangeType){ void ClientCommunicationHandler::sendDeviceSignal(int deviceId, int eventDeviceChanges, int eventChangeType){
EventUpdateData *eventData = new EventUpdateData(); EventUpdateData *eventData = new EventUpdateData();
eventData->messageType = L"TDDeviceChangeEvent"; eventData->messageType = L"TDDeviceChangeEvent";
eventData->deviceId = deviceId; eventData->deviceId = deviceId;
eventData->eventDeviceChanges = eventDeviceChanges; eventData->eventDeviceChanges = eventDeviceChanges;
eventData->eventChangeType = eventChangeType; eventData->eventChangeType = eventChangeType;
d->deviceUpdateEvent->signal(eventData); d->deviceUpdateEvent->signal(eventData);
} }

View file

@ -1,31 +1,31 @@
#ifndef CONNECTIONLISTENER_H #ifndef CONNECTIONLISTENER_H
#define CONNECTIONLISTENER_H #define CONNECTIONLISTENER_H
#include <string> #include <string>
#include "Thread.h" #include "Thread.h"
#include "Event.h" #include "Event.h"
class Event; class Event;
namespace TelldusCore { namespace TelldusCore {
class Socket; class Socket;
}; };
class ConnectionListenerEventData : public TelldusCore::EventDataBase { class ConnectionListenerEventData : public TelldusCore::EventDataBase {
public: public:
TelldusCore::Socket *socket; TelldusCore::Socket *socket;
}; };
class ConnectionListener : public TelldusCore::Thread { class ConnectionListener : public TelldusCore::Thread {
public: public:
ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent); ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent);
virtual ~ConnectionListener(void); virtual ~ConnectionListener(void);
protected: protected:
void run(); void run();
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
#endif //CONNECTIONLISTENER_H #endif //CONNECTIONLISTENER_H

View file

@ -1,91 +1,91 @@
#include "ConnectionListener.h" #include "ConnectionListener.h"
#include "Socket.h" #include "Socket.h"
#include <string> #include <string>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
#include <errno.h> #include <errno.h>
class ConnectionListener::PrivateData { class ConnectionListener::PrivateData {
public: public:
TelldusCore::EventRef waitEvent; TelldusCore::EventRef waitEvent;
std::string name; std::string name;
bool running; bool running;
}; };
ConnectionListener::ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent) ConnectionListener::ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent)
{ {
d = new PrivateData; d = new PrivateData;
d->waitEvent = waitEvent; d->waitEvent = waitEvent;
d->name = "/tmp/" + std::string(name.begin(), name.end()); d->name = "/tmp/" + std::string(name.begin(), name.end());
d->running = true; d->running = true;
this->start(); this->start();
} }
ConnectionListener::~ConnectionListener(void) { ConnectionListener::~ConnectionListener(void) {
d->running = false; d->running = false;
this->wait(); this->wait();
unlink(d->name.c_str()); unlink(d->name.c_str());
delete d; delete d;
} }
void ConnectionListener::run(){ void ConnectionListener::run(){
struct timeval tv = { 0, 0 }; struct timeval tv = { 0, 0 };
//Timeout for select //Timeout for select
SOCKET_T serverSocket; SOCKET_T serverSocket;
struct sockaddr_un name; struct sockaddr_un name;
socklen_t len; socklen_t len;
serverSocket = socket(PF_LOCAL, SOCK_STREAM, 0); serverSocket = socket(PF_LOCAL, SOCK_STREAM, 0);
if (serverSocket < 0) { if (serverSocket < 0) {
return; return;
} }
name.sun_family = AF_LOCAL; name.sun_family = AF_LOCAL;
memset(name.sun_path, '\0', sizeof(name.sun_path)); memset(name.sun_path, '\0', sizeof(name.sun_path));
strncpy(name.sun_path, d->name.c_str(), sizeof(name.sun_path)); strncpy(name.sun_path, d->name.c_str(), sizeof(name.sun_path));
unlink(name.sun_path); unlink(name.sun_path);
int size = SUN_LEN(&name); int size = SUN_LEN(&name);
bind(serverSocket, (struct sockaddr *)&name, size); bind(serverSocket, (struct sockaddr *)&name, size);
listen(serverSocket, 5); listen(serverSocket, 5);
//Change permissions to allow everyone //Change permissions to allow everyone
chmod(d->name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); chmod(d->name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
len = sizeof(struct sockaddr_un); len = sizeof(struct sockaddr_un);
fd_set infds; fd_set infds;
FD_ZERO(&infds); FD_ZERO(&infds);
FD_SET(serverSocket, &infds); FD_SET(serverSocket, &infds);
while(d->running) { while(d->running) {
tv.tv_sec = 5; tv.tv_sec = 5;
int response = select(serverSocket+1, &infds, NULL, NULL, &tv); int response = select(serverSocket+1, &infds, NULL, NULL, &tv);
if (response == 0) { if (response == 0) {
FD_SET(serverSocket, &infds); FD_SET(serverSocket, &infds);
continue; continue;
} else if (response < 0 ) { } else if (response < 0 ) {
continue; continue;
} }
//Make sure it is a new connection //Make sure it is a new connection
if (!FD_ISSET(serverSocket, &infds)) { if (!FD_ISSET(serverSocket, &infds)) {
continue; continue;
} }
SOCKET_T clientSocket = accept(serverSocket, NULL, NULL); SOCKET_T clientSocket = accept(serverSocket, NULL, NULL);
ConnectionListenerEventData *data = new ConnectionListenerEventData(); ConnectionListenerEventData *data = new ConnectionListenerEventData();
data->socket = new TelldusCore::Socket(clientSocket); data->socket = new TelldusCore::Socket(clientSocket);
d->waitEvent->signal(data); d->waitEvent->signal(data);
} }
close(serverSocket); close(serverSocket);
} }

View file

@ -1,149 +1,149 @@
#include "ConnectionListener.h" #include "ConnectionListener.h"
#include "Event.h" #include "Event.h"
#include "Socket.h" #include "Socket.h"
#include <windows.h> #include <windows.h>
#include <AccCtrl.h> #include <AccCtrl.h>
#include <Aclapi.h> #include <Aclapi.h>
#define BUFSIZE 512 #define BUFSIZE 512
class ConnectionListener::PrivateData { class ConnectionListener::PrivateData {
public: public:
std::wstring pipename; std::wstring pipename;
SECURITY_ATTRIBUTES sa; SECURITY_ATTRIBUTES sa;
HANDLE hEvent; HANDLE hEvent;
bool running; bool running;
TelldusCore::EventRef waitEvent; TelldusCore::EventRef waitEvent;
}; };
ConnectionListener::ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent) ConnectionListener::ConnectionListener(const std::wstring &name, TelldusCore::EventRef waitEvent)
{ {
d = new PrivateData; d = new PrivateData;
d->hEvent = 0; d->hEvent = 0;
d->running = true; d->running = true;
d->waitEvent = waitEvent; d->waitEvent = waitEvent;
d->pipename = L"\\\\.\\pipe\\" + name; d->pipename = L"\\\\.\\pipe\\" + name;
PSECURITY_DESCRIPTOR pSD = NULL; PSECURITY_DESCRIPTOR pSD = NULL;
PACL pACL = NULL; PACL pACL = NULL;
EXPLICIT_ACCESS ea; EXPLICIT_ACCESS ea;
PSID pEveryoneSID = NULL; PSID pEveryoneSID = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (pSD == NULL) { if (pSD == NULL) {
return; return;
} }
if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
LocalFree(pSD); LocalFree(pSD);
return; return;
} }
if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID)) { if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID)) {
LocalFree(pSD); LocalFree(pSD);
} }
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS)); ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
ea.grfAccessPermissions = STANDARD_RIGHTS_ALL; ea.grfAccessPermissions = STANDARD_RIGHTS_ALL;
ea.grfAccessMode = SET_ACCESS; ea.grfAccessMode = SET_ACCESS;
ea.grfInheritance= NO_INHERITANCE; ea.grfInheritance= NO_INHERITANCE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID; ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea.Trustee.ptstrName = (LPTSTR) pEveryoneSID; ea.Trustee.ptstrName = (LPTSTR) pEveryoneSID;
// Add the ACL to the security descriptor. // Add the ACL to the security descriptor.
if (!SetSecurityDescriptorDacl(pSD, if (!SetSecurityDescriptorDacl(pSD,
TRUE, // bDaclPresent flag TRUE, // bDaclPresent flag
pACL, pACL,
FALSE)) // not a default DACL FALSE)) // not a default DACL
{ {
LocalFree(pSD); LocalFree(pSD);
FreeSid(pEveryoneSID); FreeSid(pEveryoneSID);
} }
d->sa.nLength = sizeof(SECURITY_ATTRIBUTES); d->sa.nLength = sizeof(SECURITY_ATTRIBUTES);
d->sa.lpSecurityDescriptor = pSD; d->sa.lpSecurityDescriptor = pSD;
d->sa.bInheritHandle = false; d->sa.bInheritHandle = false;
start(); start();
} }
ConnectionListener::~ConnectionListener(void) { ConnectionListener::~ConnectionListener(void) {
d->running = false; d->running = false;
if (d->hEvent) { if (d->hEvent) {
SetEvent(d->hEvent); SetEvent(d->hEvent);
} }
wait(); wait();
delete d; delete d;
} }
void ConnectionListener::run() { void ConnectionListener::run() {
HANDLE hPipe; HANDLE hPipe;
OVERLAPPED oOverlap; OVERLAPPED oOverlap;
DWORD cbBytesRead; DWORD cbBytesRead;
memset(&oOverlap, 0, sizeof(OVERLAPPED)); memset(&oOverlap, 0, sizeof(OVERLAPPED));
d->hEvent = CreateEvent(NULL, true, false, NULL); d->hEvent = CreateEvent(NULL, true, false, NULL);
oOverlap.hEvent = d->hEvent; oOverlap.hEvent = d->hEvent;
bool recreate = true; bool recreate = true;
while (1) { while (1) {
BOOL alreadyConnected = false; BOOL alreadyConnected = false;
if (recreate) { if (recreate) {
hPipe = CreateNamedPipe( hPipe = CreateNamedPipe(
(const wchar_t *)d->pipename.c_str(), // pipe name (const wchar_t *)d->pipename.c_str(), // pipe name
PIPE_ACCESS_DUPLEX | // read/write access PIPE_ACCESS_DUPLEX | // read/write access
FILE_FLAG_OVERLAPPED, //Overlapped mode FILE_FLAG_OVERLAPPED, //Overlapped mode
PIPE_TYPE_MESSAGE | // message type pipe PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size BUFSIZE, // output buffer size
BUFSIZE, // input buffer size BUFSIZE, // input buffer size
0, // client time-out 0, // client time-out
&d->sa); // default security attribute &d->sa); // default security attribute
if (hPipe == INVALID_HANDLE_VALUE) { if (hPipe == INVALID_HANDLE_VALUE) {
return; return;
} }
ConnectNamedPipe(hPipe, &oOverlap); ConnectNamedPipe(hPipe, &oOverlap);
alreadyConnected = GetLastError() == ERROR_PIPE_CONNECTED; alreadyConnected = GetLastError() == ERROR_PIPE_CONNECTED;
recreate = false; recreate = false;
} }
if(!alreadyConnected){ if(!alreadyConnected){
DWORD result = WaitForSingleObject(oOverlap.hEvent, 1000); DWORD result = WaitForSingleObject(oOverlap.hEvent, 1000);
if (!d->running) { if (!d->running) {
CancelIo(hPipe); CancelIo(hPipe);
WaitForSingleObject(oOverlap.hEvent, INFINITE); WaitForSingleObject(oOverlap.hEvent, INFINITE);
break; break;
} }
if(result == WAIT_TIMEOUT){ if(result == WAIT_TIMEOUT){
//CloseHandle(hPipe); //CloseHandle(hPipe);
continue; continue;
} }
BOOL connected = GetOverlappedResult(hPipe, &oOverlap, &cbBytesRead, false); BOOL connected = GetOverlappedResult(hPipe, &oOverlap, &cbBytesRead, false);
if (!connected) { if (!connected) {
CloseHandle(hPipe); CloseHandle(hPipe);
return; return;
} }
} }
ConnectionListenerEventData *data = new ConnectionListenerEventData(); ConnectionListenerEventData *data = new ConnectionListenerEventData();
ResetEvent(oOverlap.hEvent); ResetEvent(oOverlap.hEvent);
data->socket = new TelldusCore::Socket(hPipe); data->socket = new TelldusCore::Socket(hPipe);
d->waitEvent->signal(data); d->waitEvent->signal(data);
recreate = true; recreate = true;
} }
CloseHandle(d->hEvent); CloseHandle(d->hEvent);
CloseHandle(hPipe); CloseHandle(hPipe);
} }

View file

@ -1,53 +1,53 @@
#include "Controller.h" #include "Controller.h"
#include "Protocol.h" #include "Protocol.h"
#include "EventUpdateManager.h" #include "EventUpdateManager.h"
#include "Strings.h" #include "Strings.h"
class Controller::PrivateData { class Controller::PrivateData {
public: public:
TelldusCore::EventRef event, updateEvent; TelldusCore::EventRef event, updateEvent;
int id, firmwareVersion; int id, firmwareVersion;
}; };
Controller::Controller(int id, TelldusCore::EventRef event, TelldusCore::EventRef updateEvent){ Controller::Controller(int id, TelldusCore::EventRef event, TelldusCore::EventRef updateEvent){
d = new PrivateData; d = new PrivateData;
d->event = event; d->event = event;
d->updateEvent = updateEvent; d->updateEvent = updateEvent;
d->id = id; d->id = id;
d->firmwareVersion = 0; d->firmwareVersion = 0;
} }
Controller::~Controller(){ Controller::~Controller(){
delete d; delete d;
} }
void Controller::publishData(const std::string &msg) const { void Controller::publishData(const std::string &msg) const {
ControllerEventData *data = new ControllerEventData; ControllerEventData *data = new ControllerEventData;
data->msg = msg; data->msg = msg;
data->controllerId = d->id; data->controllerId = d->id;
d->event->signal(data); d->event->signal(data);
} }
void Controller::decodePublishData(const std::string &data) const { void Controller::decodePublishData(const std::string &data) const {
std::list<std::string> msgList = Protocol::decodeData(data); std::list<std::string> msgList = Protocol::decodeData(data);
for (std::list<std::string>::iterator msgIt = msgList.begin(); msgIt != msgList.end(); ++msgIt){ for (std::list<std::string>::iterator msgIt = msgList.begin(); msgIt != msgList.end(); ++msgIt){
this->publishData(*msgIt); this->publishData(*msgIt);
} }
} }
int Controller::firmwareVersion() const { int Controller::firmwareVersion() const {
return d->firmwareVersion; return d->firmwareVersion;
} }
void Controller::setFirmwareVersion(int version) { void Controller::setFirmwareVersion(int version) {
d->firmwareVersion = version; d->firmwareVersion = version;
EventUpdateData *eventData = new EventUpdateData(); EventUpdateData *eventData = new EventUpdateData();
eventData->messageType = L"TDControllerEvent"; eventData->messageType = L"TDControllerEvent";
eventData->controllerId = d->id; eventData->controllerId = d->id;
eventData->eventState = TELLSTICK_DEVICE_CHANGED; eventData->eventState = TELLSTICK_DEVICE_CHANGED;
eventData->eventChangeType = TELLSTICK_CHANGE_FIRMWARE; eventData->eventChangeType = TELLSTICK_CHANGE_FIRMWARE;
eventData->eventValue = TelldusCore::intToWstring(version); eventData->eventValue = TelldusCore::intToWstring(version);
d->updateEvent->signal(eventData); d->updateEvent->signal(eventData);
} }

View file

@ -1,32 +1,32 @@
#ifndef CONTROLLER_H #ifndef CONTROLLER_H
#define CONTROLLER_H #define CONTROLLER_H
#include "Event.h" #include "Event.h"
#include <string> #include <string>
class ControllerEventData : public TelldusCore::EventDataBase { class ControllerEventData : public TelldusCore::EventDataBase {
public: public:
std::string msg; std::string msg;
int controllerId; int controllerId;
}; };
class Controller { class Controller {
public: public:
virtual ~Controller(); virtual ~Controller();
virtual int firmwareVersion() const; virtual int firmwareVersion() const;
virtual int send( const std::string &message ) = 0; virtual int send( const std::string &message ) = 0;
virtual int reset() = 0; virtual int reset() = 0;
protected: protected:
Controller(int id, TelldusCore::EventRef event, TelldusCore::EventRef updateEvent); Controller(int id, TelldusCore::EventRef event, TelldusCore::EventRef updateEvent);
void publishData(const std::string &data) const; void publishData(const std::string &data) const;
void decodePublishData(const std::string &data) const; void decodePublishData(const std::string &data) const;
void setFirmwareVersion(int version); void setFirmwareVersion(int version);
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
#endif //CONTROLLER_H #endif //CONTROLLER_H

View file

@ -1,337 +1,337 @@
#include "ControllerManager.h" #include "ControllerManager.h"
#include "Controller.h" #include "Controller.h"
#include "Mutex.h" #include "Mutex.h"
#include "TellStick.h" #include "TellStick.h"
#include "Log.h" #include "Log.h"
#include "Message.h" #include "Message.h"
#include "Strings.h" #include "Strings.h"
#include "Settings.h" #include "Settings.h"
#include "EventUpdateManager.h" #include "EventUpdateManager.h"
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
#include <map> #include <map>
#include <stdio.h> #include <stdio.h>
class ControllerDescriptor { class ControllerDescriptor {
public: public:
std::wstring name, serial; std::wstring name, serial;
int type; int type;
Controller *controller; Controller *controller;
}; };
typedef std::map<int, ControllerDescriptor> ControllerMap; typedef std::map<int, ControllerDescriptor> ControllerMap;
class ControllerManager::PrivateData { class ControllerManager::PrivateData {
public: public:
int lastControllerId; int lastControllerId;
Settings settings; Settings settings;
ControllerMap controllers; ControllerMap controllers;
TelldusCore::EventRef event, updateEvent; TelldusCore::EventRef event, updateEvent;
TelldusCore::Mutex mutex; TelldusCore::Mutex mutex;
}; };
ControllerManager::ControllerManager(TelldusCore::EventRef event, TelldusCore::EventRef updateEvent){ ControllerManager::ControllerManager(TelldusCore::EventRef event, TelldusCore::EventRef updateEvent){
d = new PrivateData; d = new PrivateData;
d->lastControllerId = 0; d->lastControllerId = 0;
d->event = event; d->event = event;
d->updateEvent = updateEvent; d->updateEvent = updateEvent;
this->loadStoredControllers(); this->loadStoredControllers();
this->loadControllers(); this->loadControllers();
} }
ControllerManager::~ControllerManager() { ControllerManager::~ControllerManager() {
for (ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) { for (ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) {
if (it->second.controller) { if (it->second.controller) {
delete( it->second.controller ); delete( it->second.controller );
} }
} }
delete d; delete d;
} }
void ControllerManager::deviceInsertedOrRemoved(int vid, int pid, const std::string &serial, bool inserted) { void ControllerManager::deviceInsertedOrRemoved(int vid, int pid, const std::string &serial, bool inserted) {
if (vid == 0x0 && pid == 0x0) { //All if (vid == 0x0 && pid == 0x0) { //All
if (inserted) { if (inserted) {
loadControllers(); loadControllers();
} else { } else {
//Disconnect all //Disconnect all
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
while(d->controllers.size()) { while(d->controllers.size()) {
ControllerMap::iterator it = d->controllers.begin(); ControllerMap::iterator it = d->controllers.begin();
delete it->second.controller; delete it->second.controller;
it->second.controller = 0; it->second.controller = 0;
signalControllerEvent(it->first, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"0"); signalControllerEvent(it->first, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"0");
} }
} }
return; return;
} }
if (vid != 0x1781) { if (vid != 0x1781) {
return; return;
} }
if (pid != 0x0C30 && pid != 0x0C31) { if (pid != 0x0C30 && pid != 0x0C31) {
return; return;
} }
if (inserted) { if (inserted) {
loadControllers(); loadControllers();
} else { } else {
//Autodetect which has been disconnected //Autodetect which has been disconnected
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) { for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) {
if (!it->second.controller) { if (!it->second.controller) {
continue; continue;
} }
TellStick *tellstick = reinterpret_cast<TellStick*>(it->second.controller); TellStick *tellstick = reinterpret_cast<TellStick*>(it->second.controller);
if (!tellstick) { if (!tellstick) {
continue; continue;
} }
if (serial.compare("") != 0) { if (serial.compare("") != 0) {
TellStickDescriptor tsd; TellStickDescriptor tsd;
tsd.vid = vid; tsd.vid = vid;
tsd.pid = pid; tsd.pid = pid;
tsd.serial = serial; tsd.serial = serial;
if (!tellstick->isSameAsDescriptor(tsd)) { if (!tellstick->isSameAsDescriptor(tsd)) {
continue; continue;
} }
} else if (tellstick->stillConnected()) { } else if (tellstick->stillConnected()) {
continue; continue;
} }
it->second.controller = 0; it->second.controller = 0;
delete tellstick; delete tellstick;
signalControllerEvent(it->first, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"0"); signalControllerEvent(it->first, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"0");
} }
} }
} }
Controller *ControllerManager::getBestControllerById(int id) { Controller *ControllerManager::getBestControllerById(int id) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
if (!d->controllers.size()) { if (!d->controllers.size()) {
return 0; return 0;
} }
ControllerMap::const_iterator it = d->controllers.find(id); ControllerMap::const_iterator it = d->controllers.find(id);
if (it != d->controllers.end() && it->second.controller) { if (it != d->controllers.end() && it->second.controller) {
return it->second.controller; return it->second.controller;
} }
//Find first available controller //Find first available controller
for(it = d->controllers.begin(); it != d->controllers.end(); ++it) { for(it = d->controllers.begin(); it != d->controllers.end(); ++it) {
if (it->second.controller) { if (it->second.controller) {
return it->second.controller; return it->second.controller;
} }
} }
return 0; return 0;
} }
void ControllerManager::loadControllers() { void ControllerManager::loadControllers() {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
std::list<TellStickDescriptor> list = TellStick::findAll(); std::list<TellStickDescriptor> list = TellStick::findAll();
std::list<TellStickDescriptor>::iterator it = list.begin(); std::list<TellStickDescriptor>::iterator it = list.begin();
for(; it != list.end(); ++it) { for(; it != list.end(); ++it) {
//Most backend only report non-opened devices. //Most backend only report non-opened devices.
//If they don't make sure we don't open them twice //If they don't make sure we don't open them twice
bool found = false; bool found = false;
ControllerMap::const_iterator cit = d->controllers.begin(); ControllerMap::const_iterator cit = d->controllers.begin();
for(; cit != d->controllers.end(); ++cit) { for(; cit != d->controllers.end(); ++cit) {
if (!cit->second.controller) { if (!cit->second.controller) {
continue; continue;
} }
TellStick *tellstick = reinterpret_cast<TellStick*>(cit->second.controller); TellStick *tellstick = reinterpret_cast<TellStick*>(cit->second.controller);
if (!tellstick) { if (!tellstick) {
continue; continue;
} }
if (tellstick->isSameAsDescriptor(*it)) { if (tellstick->isSameAsDescriptor(*it)) {
found = true; found = true;
break; break;
} }
} }
if (found) { if (found) {
continue; continue;
} }
int type = TELLSTICK_CONTROLLER_TELLSTICK; int type = TELLSTICK_CONTROLLER_TELLSTICK;
if ((*it).pid == 0x0c31) { if ((*it).pid == 0x0c31) {
type = TELLSTICK_CONTROLLER_TELLSTICK_DUO; type = TELLSTICK_CONTROLLER_TELLSTICK_DUO;
} }
int controllerId = 0; int controllerId = 0;
//See if the controller matches one of the loaded, non available controllers //See if the controller matches one of the loaded, non available controllers
std::wstring serial = TelldusCore::charToWstring((*it).serial.c_str()); std::wstring serial = TelldusCore::charToWstring((*it).serial.c_str());
for(cit = d->controllers.begin(); cit != d->controllers.end(); ++cit) { for(cit = d->controllers.begin(); cit != d->controllers.end(); ++cit) {
if (cit->second.type == type && cit->second.serial.compare(serial) == 0) { if (cit->second.type == type && cit->second.serial.compare(serial) == 0) {
controllerId = cit->first; controllerId = cit->first;
break; break;
} }
} }
bool isNew = false; bool isNew = false;
if (!controllerId) { if (!controllerId) {
controllerId = d->settings.addNode(Settings::Controller); controllerId = d->settings.addNode(Settings::Controller);
if(controllerId < 0){ if(controllerId < 0){
//TODO: How to handle this? //TODO: How to handle this?
continue; continue;
} }
isNew = true; isNew = true;
d->controllers[controllerId].type = type; d->controllers[controllerId].type = type;
d->settings.setControllerType(controllerId, type); d->settings.setControllerType(controllerId, type);
d->controllers[controllerId].serial = TelldusCore::charToWstring((*it).serial.c_str()); d->controllers[controllerId].serial = TelldusCore::charToWstring((*it).serial.c_str());
d->settings.setControllerSerial(controllerId, d->controllers[controllerId].serial); d->settings.setControllerSerial(controllerId, d->controllers[controllerId].serial);
} }
//int controllerId = d->lastControllerId+1; //int controllerId = d->lastControllerId+1;
TellStick *controller = new TellStick(controllerId, d->event, d->updateEvent, *it); TellStick *controller = new TellStick(controllerId, d->event, d->updateEvent, *it);
if (!controller->isOpen()) { if (!controller->isOpen()) {
delete controller; delete controller;
continue; continue;
} }
d->controllers[controllerId].controller = controller; d->controllers[controllerId].controller = controller;
if (isNew) { if (isNew) {
signalControllerEvent(controllerId, TELLSTICK_DEVICE_ADDED, type, L""); signalControllerEvent(controllerId, TELLSTICK_DEVICE_ADDED, type, L"");
} else { } else {
signalControllerEvent(controllerId, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"1"); signalControllerEvent(controllerId, TELLSTICK_DEVICE_STATE_CHANGED, TELLSTICK_CHANGE_AVAILABLE, L"1");
} }
} }
} }
void ControllerManager::loadStoredControllers() { void ControllerManager::loadStoredControllers() {
int numberOfControllers = d->settings.getNumberOfNodes(Settings::Controller); int numberOfControllers = d->settings.getNumberOfNodes(Settings::Controller);
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
for (int i = 0; i < numberOfControllers; ++i) { for (int i = 0; i < numberOfControllers; ++i) {
int id = d->settings.getNodeId(Settings::Controller, i); int id = d->settings.getNodeId(Settings::Controller, i);
d->controllers[id].controller = NULL; d->controllers[id].controller = NULL;
d->controllers[id].name = d->settings.getName(Settings::Controller, id); d->controllers[id].name = d->settings.getName(Settings::Controller, id);
d->controllers[id].type = d->settings.getControllerType(id); d->controllers[id].type = d->settings.getControllerType(id);
d->controllers[id].serial = d->settings.getControllerSerial(id); d->controllers[id].serial = d->settings.getControllerSerial(id);
signalControllerEvent(id, TELLSTICK_DEVICE_ADDED, 0, L""); signalControllerEvent(id, TELLSTICK_DEVICE_ADDED, 0, L"");
} }
} }
void ControllerManager::queryControllerStatus(){ void ControllerManager::queryControllerStatus(){
std::list<TellStick *> tellStickControllers; std::list<TellStick *> tellStickControllers;
{ {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) { for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) {
if (!it->second.controller) { if (!it->second.controller) {
continue; continue;
} }
TellStick *tellstick = reinterpret_cast<TellStick*>(it->second.controller); TellStick *tellstick = reinterpret_cast<TellStick*>(it->second.controller);
if (tellstick) { if (tellstick) {
tellStickControllers.push_back(tellstick); tellStickControllers.push_back(tellstick);
} }
} }
} }
bool reloadControllers = false; bool reloadControllers = false;
std::string noop = "N+"; std::string noop = "N+";
for(std::list<TellStick *>::iterator it = tellStickControllers.begin(); it != tellStickControllers.end(); ++it) { for(std::list<TellStick *>::iterator it = tellStickControllers.begin(); it != tellStickControllers.end(); ++it) {
int success = (*it)->send(noop); int success = (*it)->send(noop);
if(success == TELLSTICK_ERROR_BROKEN_PIPE){ if(success == TELLSTICK_ERROR_BROKEN_PIPE){
Log::warning("TellStick query: Error in communication with TellStick, resetting USB"); Log::warning("TellStick query: Error in communication with TellStick, resetting USB");
resetController(*it); resetController(*it);
} }
if(success == TELLSTICK_ERROR_BROKEN_PIPE || success == TELLSTICK_ERROR_NOT_FOUND){ if(success == TELLSTICK_ERROR_BROKEN_PIPE || success == TELLSTICK_ERROR_NOT_FOUND){
reloadControllers = true; reloadControllers = true;
} }
} }
if(!tellStickControllers.size() || reloadControllers){ if(!tellStickControllers.size() || reloadControllers){
//no tellstick at all found, or controller was reset //no tellstick at all found, or controller was reset
Log::debug("TellStick query: Rescanning USB ports"); //only log as debug, since this will happen all the time if no TellStick is connected Log::debug("TellStick query: Rescanning USB ports"); //only log as debug, since this will happen all the time if no TellStick is connected
loadControllers(); loadControllers();
} }
} }
int ControllerManager::resetController(Controller *controller) { int ControllerManager::resetController(Controller *controller) {
TellStick *tellstick = reinterpret_cast<TellStick*>(controller); TellStick *tellstick = reinterpret_cast<TellStick*>(controller);
if (!tellstick) { if (!tellstick) {
return true; //not tellstick, nothing to reset at the moment, just return true return true; //not tellstick, nothing to reset at the moment, just return true
} }
int success = tellstick->reset(); int success = tellstick->reset();
deviceInsertedOrRemoved(tellstick->vid(), tellstick->pid(), tellstick->serial(), false); //remove from list and delete deviceInsertedOrRemoved(tellstick->vid(), tellstick->pid(), tellstick->serial(), false); //remove from list and delete
return success; return success;
} }
std::wstring ControllerManager::getControllers() const { std::wstring ControllerManager::getControllers() const {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
TelldusCore::Message msg; TelldusCore::Message msg;
msg.addArgument((int)d->controllers.size()); msg.addArgument((int)d->controllers.size());
for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) { for(ControllerMap::iterator it = d->controllers.begin(); it != d->controllers.end(); ++it) {
msg.addArgument(it->first); msg.addArgument(it->first);
msg.addArgument(it->second.type); msg.addArgument(it->second.type);
msg.addArgument(it->second.name.c_str()); msg.addArgument(it->second.name.c_str());
msg.addArgument(it->second.controller ? 1 : 0); msg.addArgument(it->second.controller ? 1 : 0);
} }
return msg; return msg;
} }
std::wstring ControllerManager::getControllerValue(int id, const std::wstring &name) { std::wstring ControllerManager::getControllerValue(int id, const std::wstring &name) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
ControllerMap::iterator it = d->controllers.find(id); ControllerMap::iterator it = d->controllers.find(id);
if (it == d->controllers.end()) { if (it == d->controllers.end()) {
return L""; return L"";
} }
if (name == L"serial") { if (name == L"serial") {
return it->second.serial; return it->second.serial;
} else if (name == L"firmware") { } else if (name == L"firmware") {
if (!it->second.controller) { if (!it->second.controller) {
return L"-1"; return L"-1";
} }
return TelldusCore::intToWstring(it->second.controller->firmwareVersion()); return TelldusCore::intToWstring(it->second.controller->firmwareVersion());
} }
return L""; return L"";
} }
int ControllerManager::removeController(int id) { int ControllerManager::removeController(int id) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
ControllerMap::iterator it = d->controllers.find(id); ControllerMap::iterator it = d->controllers.find(id);
if (it == d->controllers.end()) { if (it == d->controllers.end()) {
return TELLSTICK_ERROR_NOT_FOUND; return TELLSTICK_ERROR_NOT_FOUND;
} }
if (it->second.controller) { if (it->second.controller) {
//Still connected //Still connected
return TELLSTICK_ERROR_PERMISSION_DENIED; return TELLSTICK_ERROR_PERMISSION_DENIED;
} }
int ret = d->settings.removeNode(Settings::Controller, id); int ret = d->settings.removeNode(Settings::Controller, id);
if (ret != TELLSTICK_SUCCESS) { if (ret != TELLSTICK_SUCCESS) {
return ret; return ret;
} }
d->controllers.erase(it); d->controllers.erase(it);
signalControllerEvent(id, TELLSTICK_DEVICE_REMOVED, 0, L""); signalControllerEvent(id, TELLSTICK_DEVICE_REMOVED, 0, L"");
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
int ControllerManager::setControllerValue(int id, const std::wstring &name, const std::wstring &value) { int ControllerManager::setControllerValue(int id, const std::wstring &name, const std::wstring &value) {
TelldusCore::MutexLocker locker(&d->mutex); TelldusCore::MutexLocker locker(&d->mutex);
ControllerMap::iterator it = d->controllers.find(id); ControllerMap::iterator it = d->controllers.find(id);
if (it == d->controllers.end()) { if (it == d->controllers.end()) {
return TELLSTICK_ERROR_NOT_FOUND; return TELLSTICK_ERROR_NOT_FOUND;
} }
if (name == L"name") { if (name == L"name") {
it->second.name = value; it->second.name = value;
d->settings.setName(Settings::Controller, id, value); d->settings.setName(Settings::Controller, id, value);
signalControllerEvent(id, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_NAME, value); signalControllerEvent(id, TELLSTICK_DEVICE_CHANGED, TELLSTICK_CHANGE_NAME, value);
} else { } else {
return TELLSTICK_ERROR_SYNTAX; //TODO: Is this the best error? return TELLSTICK_ERROR_SYNTAX; //TODO: Is this the best error?
} }
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
void ControllerManager::signalControllerEvent(int controllerId, int changeEvent, int changeType, const std::wstring &newValue) { void ControllerManager::signalControllerEvent(int controllerId, int changeEvent, int changeType, const std::wstring &newValue) {
EventUpdateData *eventData = new EventUpdateData(); EventUpdateData *eventData = new EventUpdateData();
eventData->messageType = L"TDControllerEvent"; eventData->messageType = L"TDControllerEvent";
eventData->controllerId = controllerId; eventData->controllerId = controllerId;
eventData->eventState = changeEvent; eventData->eventState = changeEvent;
eventData->eventChangeType = changeType; eventData->eventChangeType = changeType;
eventData->eventValue = newValue; eventData->eventValue = newValue;
d->updateEvent->signal(eventData); d->updateEvent->signal(eventData);
} }

View file

@ -1,89 +1,89 @@
#include "ControllerMessage.h" #include "ControllerMessage.h"
#include "Device.h" #include "Device.h"
#include "Strings.h" #include "Strings.h"
#include "common.h" #include "common.h"
#include <map> #include <map>
class ControllerMessage::PrivateData { class ControllerMessage::PrivateData {
public: public:
std::map<std::string, std::string> parameters; std::map<std::string, std::string> parameters;
std::string protocol, model, msgClass; std::string protocol, model, msgClass;
int method; int method;
}; };
ControllerMessage::ControllerMessage(const std::string &message) { ControllerMessage::ControllerMessage(const std::string &message) {
d = new PrivateData; d = new PrivateData;
//Process our message into bits //Process our message into bits
size_t prevPos = 0; size_t prevPos = 0;
size_t pos = message.find(";"); size_t pos = message.find(";");
while(pos != std::string::npos) { while(pos != std::string::npos) {
std::string param = message.substr(prevPos, pos-prevPos); std::string param = message.substr(prevPos, pos-prevPos);
prevPos = pos+1; prevPos = pos+1;
size_t delim = param.find(":"); size_t delim = param.find(":");
if (delim == std::string::npos) { if (delim == std::string::npos) {
break; break;
} }
if (param.substr(0, delim).compare("class") == 0) { if (param.substr(0, delim).compare("class") == 0) {
d->msgClass = param.substr(delim+1, param.length()-delim); d->msgClass = param.substr(delim+1, param.length()-delim);
} else if (param.substr(0, delim).compare("protocol") == 0) { } else if (param.substr(0, delim).compare("protocol") == 0) {
d->protocol = param.substr(delim+1, param.length()-delim); d->protocol = param.substr(delim+1, param.length()-delim);
} else if (param.substr(0, delim).compare("model") == 0) { } else if (param.substr(0, delim).compare("model") == 0) {
d->model = param.substr(delim+1, param.length()-delim); d->model = param.substr(delim+1, param.length()-delim);
} else if (param.substr(0, delim).compare("method") == 0) { } else if (param.substr(0, delim).compare("method") == 0) {
d->method = Device::methodId(param.substr(delim+1, param.length()-delim)); d->method = Device::methodId(param.substr(delim+1, param.length()-delim));
} else { } else {
d->parameters[param.substr(0, delim)] = param.substr(delim+1, param.length()-delim); d->parameters[param.substr(0, delim)] = param.substr(delim+1, param.length()-delim);
} }
pos = message.find(";", pos+1); pos = message.find(";", pos+1);
} }
} }
ControllerMessage::~ControllerMessage(){ ControllerMessage::~ControllerMessage(){
delete d; delete d;
} }
std::string ControllerMessage::msgClass() const { std::string ControllerMessage::msgClass() const {
return d->msgClass; return d->msgClass;
} }
int ControllerMessage::method() const { int ControllerMessage::method() const {
return d->method; return d->method;
} }
std::wstring ControllerMessage::protocol() const { std::wstring ControllerMessage::protocol() const {
return TelldusCore::charToWstring(d->protocol.c_str()); return TelldusCore::charToWstring(d->protocol.c_str());
} }
std::wstring ControllerMessage::model() const { std::wstring ControllerMessage::model() const {
return TelldusCore::charToWstring(d->model.c_str()); return TelldusCore::charToWstring(d->model.c_str());
} }
int ControllerMessage::getIntParameter(const std::string &key) const { int ControllerMessage::getIntParameter(const std::string &key) const {
std::string strValue = getParameter(key); std::string strValue = getParameter(key);
if (strValue.compare("") == 0) { if (strValue.compare("") == 0) {
return -1; return -1;
} }
if (strValue.substr(0,2).compare("0x") == 0) { if (strValue.substr(0,2).compare("0x") == 0) {
return strtol(strValue.c_str(), NULL, 16); return strtol(strValue.c_str(), NULL, 16);
} }
return strtol(strValue.c_str(), NULL, 10); return strtol(strValue.c_str(), NULL, 10);
} }
std::string ControllerMessage::getParameter(const std::string &key) const { std::string ControllerMessage::getParameter(const std::string &key) const {
std::map<std::string, std::string>::iterator it = d->parameters.find(key); std::map<std::string, std::string>::iterator it = d->parameters.find(key);
if (it == d->parameters.end()) { if (it == d->parameters.end()) {
return ""; return "";
} }
return d->parameters[key]; return d->parameters[key];
} }
bool ControllerMessage::hasParameter(const std::string &key) const { bool ControllerMessage::hasParameter(const std::string &key) const {
std::map<std::string, std::string>::iterator it = d->parameters.find(key); std::map<std::string, std::string>::iterator it = d->parameters.find(key);
if (it == d->parameters.end()) { if (it == d->parameters.end()) {
return false; return false;
} }
return true; return true;
} }

View file

@ -1,253 +1,253 @@
#include "Device.h" #include "Device.h"
#include "Settings.h" #include "Settings.h"
#include "TellStick.h" #include "TellStick.h"
class Device::PrivateData { class Device::PrivateData {
public: public:
std::wstring model; std::wstring model;
std::wstring name; std::wstring name;
ParameterMap parameterList; ParameterMap parameterList;
Protocol *protocol; Protocol *protocol;
std::wstring protocolName; std::wstring protocolName;
int preferredControllerId; int preferredControllerId;
int state; int state;
std::wstring stateValue; std::wstring stateValue;
}; };
Device::Device(int id) Device::Device(int id)
:Mutex() :Mutex()
{ {
d = new PrivateData; d = new PrivateData;
d->protocol = 0; d->protocol = 0;
d->preferredControllerId = 0; d->preferredControllerId = 0;
d->state = 0; d->state = 0;
} }
Device::~Device(void) { Device::~Device(void) {
delete d->protocol; delete d->protocol;
delete d; delete d;
} }
/** /**
* Get-/Set-methods * Get-/Set-methods
*/ */
int Device::getLastSentCommand(int methodsSupported){ int Device::getLastSentCommand(int methodsSupported){
int lastSentCommand = Device::maskUnsupportedMethods(d->state, methodsSupported); int lastSentCommand = Device::maskUnsupportedMethods(d->state, methodsSupported);
if (lastSentCommand == TELLSTICK_BELL) { if (lastSentCommand == TELLSTICK_BELL) {
//Bell is not a state //Bell is not a state
lastSentCommand = TELLSTICK_TURNOFF; lastSentCommand = TELLSTICK_TURNOFF;
} }
if (lastSentCommand == 0) { if (lastSentCommand == 0) {
lastSentCommand = TELLSTICK_TURNOFF; lastSentCommand = TELLSTICK_TURNOFF;
} }
return lastSentCommand; return lastSentCommand;
} }
int Device::getMethods() const { int Device::getMethods() const {
Protocol *p = this->retrieveProtocol(); Protocol *p = this->retrieveProtocol();
if (p) { if (p) {
return p->methods(); return p->methods();
} }
return 0; return 0;
} }
void Device::setLastSentCommand(int command, std::wstring value){ void Device::setLastSentCommand(int command, std::wstring value){
d->state = command; d->state = command;
d->stateValue = value; d->stateValue = value;
} }
std::wstring Device::getModel(){ std::wstring Device::getModel(){
return d->model; return d->model;
} }
void Device::setModel(const std::wstring &model){ void Device::setModel(const std::wstring &model){
if(d->protocol){ if(d->protocol){
delete(d->protocol); delete(d->protocol);
d->protocol = 0; d->protocol = 0;
} }
d->model = model; d->model = model;
} }
std::wstring Device::getName(){ std::wstring Device::getName(){
return d->name; return d->name;
} }
void Device::setName(const std::wstring &name){ void Device::setName(const std::wstring &name){
d->name = name; d->name = name;
} }
std::wstring Device::getParameter(const std::wstring &key){ std::wstring Device::getParameter(const std::wstring &key){
ParameterMap::iterator it = d->parameterList.find(key); ParameterMap::iterator it = d->parameterList.find(key);
if (it == d->parameterList.end()) { if (it == d->parameterList.end()) {
return L""; return L"";
} }
return d->parameterList[key]; return d->parameterList[key];
} }
std::list<std::string> Device::getParametersForProtocol() const { std::list<std::string> Device::getParametersForProtocol() const {
return Protocol::getParametersForProtocol(getProtocolName()); return Protocol::getParametersForProtocol(getProtocolName());
} }
void Device::setParameter(const std::wstring &key, const std::wstring &value){ void Device::setParameter(const std::wstring &key, const std::wstring &value){
d->parameterList[key] = value; d->parameterList[key] = value;
if(d->protocol){ if(d->protocol){
d->protocol->setParameters(d->parameterList); d->protocol->setParameters(d->parameterList);
} }
} }
int Device::getPreferredControllerId(){ int Device::getPreferredControllerId(){
return d->preferredControllerId; return d->preferredControllerId;
} }
void Device::setPreferredControllerId(int controllerId){ void Device::setPreferredControllerId(int controllerId){
d->preferredControllerId = controllerId; d->preferredControllerId = controllerId;
} }
std::wstring Device::getProtocolName() const { std::wstring Device::getProtocolName() const {
return d->protocolName; return d->protocolName;
} }
void Device::setProtocolName(const std::wstring &protocolName){ void Device::setProtocolName(const std::wstring &protocolName){
if(d->protocol){ if(d->protocol){
delete(d->protocol); delete(d->protocol);
d->protocol = 0; d->protocol = 0;
} }
d->protocolName = protocolName; d->protocolName = protocolName;
} }
std::wstring Device::getStateValue(){ std::wstring Device::getStateValue(){
return d->stateValue; return d->stateValue;
} }
int Device::getType(){ int Device::getType(){
if(d->protocolName == L"group"){ if(d->protocolName == L"group"){
return TELLSTICK_TYPE_GROUP; return TELLSTICK_TYPE_GROUP;
} }
else if(d->protocolName == L"scene"){ else if(d->protocolName == L"scene"){
return TELLSTICK_TYPE_SCENE; return TELLSTICK_TYPE_SCENE;
} }
return TELLSTICK_TYPE_DEVICE; return TELLSTICK_TYPE_DEVICE;
} }
/** /**
* End Get-/Set * End Get-/Set
*/ */
int Device::doAction(int action, unsigned char data, Controller *controller) { int Device::doAction(int action, unsigned char data, Controller *controller) {
Protocol *p = this->retrieveProtocol(); Protocol *p = this->retrieveProtocol();
if(p){ if(p){
//Try to determine if we need to call another method due to masking //Try to determine if we need to call another method due to masking
int methods = p->methods(); int methods = p->methods();
if ((action & methods) == 0) { if ((action & methods) == 0) {
//Loop all methods an see if any method masks to this one //Loop all methods an see if any method masks to this one
for(int i = 1; i <= methods; i<<=1) { for(int i = 1; i <= methods; i<<=1) {
if ((i & methods) == 0) { if ((i & methods) == 0) {
continue; continue;
} }
if (this->maskUnsupportedMethods(i, action)) { if (this->maskUnsupportedMethods(i, action)) {
action = i; action = i;
break; break;
} }
} }
} }
if ((action & methods) == 0) { if ((action & methods) == 0) {
return TELLSTICK_ERROR_METHOD_NOT_SUPPORTED; return TELLSTICK_ERROR_METHOD_NOT_SUPPORTED;
} }
std::string code = p->getStringForMethod(action, data, controller); std::string code = p->getStringForMethod(action, data, controller);
if (code == "") { if (code == "") {
return TELLSTICK_ERROR_METHOD_NOT_SUPPORTED; return TELLSTICK_ERROR_METHOD_NOT_SUPPORTED;
} }
if (code[0] != 'S' && code[0] != 'T' && code[0] != 'P' && code[0] != 'R') { if (code[0] != 'S' && code[0] != 'T' && code[0] != 'P' && code[0] != 'R') {
//Try autodetect sendtype //Try autodetect sendtype
TellStick *tellstick = reinterpret_cast<TellStick *>(controller); TellStick *tellstick = reinterpret_cast<TellStick *>(controller);
if (!tellstick) { if (!tellstick) {
return TELLSTICK_ERROR_UNKNOWN; return TELLSTICK_ERROR_UNKNOWN;
} }
unsigned int maxlength = 80; unsigned int maxlength = 80;
if (tellstick->pid() == 0x0c31) { if (tellstick->pid() == 0x0c31) {
maxlength = 512; maxlength = 512;
} }
if (code.length() <= maxlength) { if (code.length() <= maxlength) {
//S is enough //S is enough
code.insert(0, 1, 'S'); code.insert(0, 1, 'S');
code.append(1, '+'); code.append(1, '+');
} else { } else {
code = TellStick::createTPacket(code); code = TellStick::createTPacket(code);
} }
} }
return controller->send(code); return controller->send(code);
} }
return TELLSTICK_ERROR_UNKNOWN; return TELLSTICK_ERROR_UNKNOWN;
} }
Protocol* Device::retrieveProtocol() const { Protocol* Device::retrieveProtocol() const {
if (d->protocol) { if (d->protocol) {
return d->protocol; return d->protocol;
} }
d->protocol = Protocol::getProtocolInstance(d->protocolName); d->protocol = Protocol::getProtocolInstance(d->protocolName);
if(d->protocol){ if(d->protocol){
d->protocol->setModel(d->model); d->protocol->setModel(d->model);
d->protocol->setParameters(d->parameterList); d->protocol->setParameters(d->parameterList);
return d->protocol; return d->protocol;
} }
return 0; return 0;
} }
int Device::maskUnsupportedMethods(int methods, int supportedMethods) { int Device::maskUnsupportedMethods(int methods, int supportedMethods) {
// Bell -> On // Bell -> On
if ((methods & TELLSTICK_BELL) && !(supportedMethods & TELLSTICK_BELL)) { if ((methods & TELLSTICK_BELL) && !(supportedMethods & TELLSTICK_BELL)) {
methods |= TELLSTICK_TURNON; methods |= TELLSTICK_TURNON;
} }
// Execute -> On // Execute -> On
if ((methods & TELLSTICK_EXECUTE) && !(supportedMethods & TELLSTICK_EXECUTE)) { if ((methods & TELLSTICK_EXECUTE) && !(supportedMethods & TELLSTICK_EXECUTE)) {
methods |= TELLSTICK_TURNON; methods |= TELLSTICK_TURNON;
} }
// Up -> Off // Up -> Off
if ((methods & TELLSTICK_UP) && !(supportedMethods & TELLSTICK_UP)) { if ((methods & TELLSTICK_UP) && !(supportedMethods & TELLSTICK_UP)) {
methods |= TELLSTICK_TURNOFF; methods |= TELLSTICK_TURNOFF;
} }
// Down -> On // Down -> On
if ((methods & TELLSTICK_DOWN) && !(supportedMethods & TELLSTICK_DOWN)) { if ((methods & TELLSTICK_DOWN) && !(supportedMethods & TELLSTICK_DOWN)) {
methods |= TELLSTICK_TURNON; methods |= TELLSTICK_TURNON;
} }
//Cut of the rest of the unsupported methods we don't have a fallback for //Cut of the rest of the unsupported methods we don't have a fallback for
return methods & supportedMethods; return methods & supportedMethods;
} }
int Device::methodId( const std::string &methodName ) { int Device::methodId( const std::string &methodName ) {
if (methodName.compare("turnon") == 0) { if (methodName.compare("turnon") == 0) {
return TELLSTICK_TURNON; return TELLSTICK_TURNON;
} }
if (methodName.compare("turnoff") == 0) { if (methodName.compare("turnoff") == 0) {
return TELLSTICK_TURNOFF; return TELLSTICK_TURNOFF;
} }
if (methodName.compare("bell") == 0) { if (methodName.compare("bell") == 0) {
return TELLSTICK_BELL; return TELLSTICK_BELL;
} }
if (methodName.compare("dim") == 0) { if (methodName.compare("dim") == 0) {
return TELLSTICK_DIM; return TELLSTICK_DIM;
} }
if (methodName.compare("execute") == 0) { if (methodName.compare("execute") == 0) {
return TELLSTICK_EXECUTE; return TELLSTICK_EXECUTE;
} }
if (methodName.compare("up") == 0) { if (methodName.compare("up") == 0) {
return TELLSTICK_UP; return TELLSTICK_UP;
} }
if (methodName.compare("down") == 0) { if (methodName.compare("down") == 0) {
return TELLSTICK_DOWN; return TELLSTICK_DOWN;
} }
if (methodName.compare("stop") == 0) { if (methodName.compare("stop") == 0) {
return TELLSTICK_STOP; return TELLSTICK_STOP;
} }
return 0; return 0;
} }

View file

@ -1,45 +1,45 @@
#ifndef DEVICE_H #ifndef DEVICE_H
#define DEVICE_H #define DEVICE_H
#include "Controller.h" #include "Controller.h"
#include "Mutex.h" #include "Mutex.h"
#include "Protocol.h" #include "Protocol.h"
#include <string> #include <string>
#include <list> #include <list>
class Device : public TelldusCore::Mutex class Device : public TelldusCore::Mutex
{ {
public: public:
Device(int id); Device(int id);
~Device(void); ~Device(void);
int doAction(int action, unsigned char data, Controller *controller); int doAction(int action, unsigned char data, Controller *controller);
std::wstring getStateValue(); std::wstring getStateValue();
int getLastSentCommand(int methodsSupported); int getLastSentCommand(int methodsSupported);
int getMethods() const; int getMethods() const;
std::wstring getModel(); std::wstring getModel();
void setModel(const std::wstring &model); void setModel(const std::wstring &model);
std::wstring getName(); std::wstring getName();
void setName(const std::wstring &name); void setName(const std::wstring &name);
std::wstring getParameter(const std::wstring &key); std::wstring getParameter(const std::wstring &key);
std::list<std::string> getParametersForProtocol() const; std::list<std::string> getParametersForProtocol() const;
void setParameter(const std::wstring &key, const std::wstring &value); void setParameter(const std::wstring &key, const std::wstring &value);
int getPreferredControllerId(); int getPreferredControllerId();
void setPreferredControllerId(int controllerId); void setPreferredControllerId(int controllerId);
std::wstring getProtocolName() const; std::wstring getProtocolName() const;
void setProtocolName(const std::wstring &name); void setProtocolName(const std::wstring &name);
void setStateValue(int stateValue); void setStateValue(int stateValue);
void setLastSentCommand(int command, std::wstring value); void setLastSentCommand(int command, std::wstring value);
int getType(); int getType();
static int maskUnsupportedMethods(int methods, int supportedMethods); static int maskUnsupportedMethods(int methods, int supportedMethods);
static int methodId( const std::string &methodName ); static int methodId( const std::string &methodName );
private: private:
Protocol *retrieveProtocol() const; Protocol *retrieveProtocol() const;
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
#endif //DEVICE_H #endif //DEVICE_H

File diff suppressed because it is too large Load diff

View file

@ -1,126 +1,126 @@
#include "EventUpdateManager.h" #include "EventUpdateManager.h"
#include "ConnectionListener.h" #include "ConnectionListener.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "Message.h" #include "Message.h"
#include "Socket.h" #include "Socket.h"
#include <list> #include <list>
#include <memory> #include <memory>
typedef std::list<TelldusCore::Socket *> SocketList; typedef std::list<TelldusCore::Socket *> SocketList;
class EventUpdateManager::PrivateData { class EventUpdateManager::PrivateData {
public: public:
TelldusCore::EventHandler eventHandler; TelldusCore::EventHandler eventHandler;
TelldusCore::EventRef stopEvent, updateEvent, clientConnectEvent; TelldusCore::EventRef stopEvent, updateEvent, clientConnectEvent;
SocketList clients; SocketList clients;
ConnectionListener *eventUpdateClientListener; ConnectionListener *eventUpdateClientListener;
}; };
EventUpdateManager::EventUpdateManager() EventUpdateManager::EventUpdateManager()
:Thread() :Thread()
{ {
d = new PrivateData; d = new PrivateData;
d->stopEvent = d->eventHandler.addEvent(); d->stopEvent = d->eventHandler.addEvent();
d->updateEvent = d->eventHandler.addEvent(); d->updateEvent = d->eventHandler.addEvent();
d->clientConnectEvent = d->eventHandler.addEvent(); d->clientConnectEvent = d->eventHandler.addEvent();
d->eventUpdateClientListener = new ConnectionListener(L"TelldusEvents", d->clientConnectEvent); d->eventUpdateClientListener = new ConnectionListener(L"TelldusEvents", d->clientConnectEvent);
} }
EventUpdateManager::~EventUpdateManager(void) { EventUpdateManager::~EventUpdateManager(void) {
d->stopEvent->signal(); d->stopEvent->signal();
wait(); wait();
delete d->eventUpdateClientListener; delete d->eventUpdateClientListener;
for (SocketList::iterator it = d->clients.begin(); it != d->clients.end(); ++it) { for (SocketList::iterator it = d->clients.begin(); it != d->clients.end(); ++it) {
delete(*it); delete(*it);
} }
delete d; delete d;
} }
TelldusCore::EventRef EventUpdateManager::retrieveUpdateEvent(){ TelldusCore::EventRef EventUpdateManager::retrieveUpdateEvent(){
return d->updateEvent; return d->updateEvent;
} }
void EventUpdateManager::run(){ void EventUpdateManager::run(){
while(!d->stopEvent->isSignaled()){ while(!d->stopEvent->isSignaled()){
if (!d->eventHandler.waitForAny()) { if (!d->eventHandler.waitForAny()) {
continue; continue;
} }
if(d->clientConnectEvent->isSignaled()){ if(d->clientConnectEvent->isSignaled()){
//new client added //new client added
TelldusCore::EventDataRef eventData = d->clientConnectEvent->takeSignal(); TelldusCore::EventDataRef eventData = d->clientConnectEvent->takeSignal();
ConnectionListenerEventData *data = reinterpret_cast<ConnectionListenerEventData*>(eventData.get()); ConnectionListenerEventData *data = reinterpret_cast<ConnectionListenerEventData*>(eventData.get());
if(data){ if(data){
d->clients.push_back(data->socket); d->clients.push_back(data->socket);
} }
} }
else if(d->updateEvent->isSignaled()){ else if(d->updateEvent->isSignaled()){
//device event, signal all clients //device event, signal all clients
TelldusCore::EventDataRef eventData = d->updateEvent->takeSignal(); TelldusCore::EventDataRef eventData = d->updateEvent->takeSignal();
EventUpdateData *data = reinterpret_cast<EventUpdateData*>(eventData.get()); EventUpdateData *data = reinterpret_cast<EventUpdateData*>(eventData.get());
if(data){ if(data){
sendMessageToClients(data); sendMessageToClients(data);
} }
} }
} }
} }
void EventUpdateManager::sendMessageToClients(EventUpdateData *data){ void EventUpdateManager::sendMessageToClients(EventUpdateData *data){
int connected = 0; int connected = 0;
for(SocketList::iterator it = d->clients.begin(); it != d->clients.end();){ for(SocketList::iterator it = d->clients.begin(); it != d->clients.end();){
if((*it)->isConnected()){ if((*it)->isConnected()){
connected++; connected++;
TelldusCore::Message msg; TelldusCore::Message msg;
if(data->messageType == L"TDDeviceEvent"){ if(data->messageType == L"TDDeviceEvent"){
msg.addArgument("TDDeviceEvent"); msg.addArgument("TDDeviceEvent");
msg.addArgument(data->deviceId); msg.addArgument(data->deviceId);
msg.addArgument(data->eventState); msg.addArgument(data->eventState);
msg.addArgument(data->eventValue); //string msg.addArgument(data->eventValue); //string
} }
else if(data->messageType == L"TDDeviceChangeEvent"){ else if(data->messageType == L"TDDeviceChangeEvent"){
msg.addArgument("TDDeviceChangeEvent"); msg.addArgument("TDDeviceChangeEvent");
msg.addArgument(data->deviceId); msg.addArgument(data->deviceId);
msg.addArgument(data->eventDeviceChanges); msg.addArgument(data->eventDeviceChanges);
msg.addArgument(data->eventChangeType); msg.addArgument(data->eventChangeType);
} }
else if(data->messageType == L"TDRawDeviceEvent"){ else if(data->messageType == L"TDRawDeviceEvent"){
msg.addArgument("TDRawDeviceEvent"); msg.addArgument("TDRawDeviceEvent");
msg.addArgument(data->eventValue); //string msg.addArgument(data->eventValue); //string
msg.addArgument(data->controllerId); msg.addArgument(data->controllerId);
} }
else if(data->messageType == L"TDSensorEvent"){ else if(data->messageType == L"TDSensorEvent"){
msg.addArgument("TDSensorEvent"); msg.addArgument("TDSensorEvent");
msg.addArgument(data->protocol); msg.addArgument(data->protocol);
msg.addArgument(data->model); msg.addArgument(data->model);
msg.addArgument(data->sensorId); msg.addArgument(data->sensorId);
msg.addArgument(data->dataType); msg.addArgument(data->dataType);
msg.addArgument(data->value); msg.addArgument(data->value);
msg.addArgument(data->timestamp); msg.addArgument(data->timestamp);
} }
else if(data->messageType == L"TDControllerEvent") { else if(data->messageType == L"TDControllerEvent") {
msg.addArgument("TDControllerEvent"); msg.addArgument("TDControllerEvent");
msg.addArgument(data->controllerId); msg.addArgument(data->controllerId);
msg.addArgument(data->eventState); msg.addArgument(data->eventState);
msg.addArgument(data->eventChangeType); msg.addArgument(data->eventChangeType);
msg.addArgument(data->eventValue); msg.addArgument(data->eventValue);
} }
(*it)->write(msg); (*it)->write(msg);
it++; it++;
} }
else{ else{
//connection is dead, remove it //connection is dead, remove it
delete *it; delete *it;
it = d->clients.erase(it); it = d->clients.erase(it);
} }
} }
} }

View file

@ -1,181 +1,181 @@
#include "Log.h" #include "Log.h"
#include <stdarg.h> #include <stdarg.h>
#if defined(_LINUX) #if defined(_LINUX)
#include <syslog.h> #include <syslog.h>
#elif defined(_WINDOWS) #elif defined(_WINDOWS)
#include <windows.h> #include <windows.h>
#include "Strings.h" #include "Strings.h"
#include "Messages.h" #include "Messages.h"
#endif #endif
class Log::PrivateData { class Log::PrivateData {
public: public:
PrivateData() : logOutput(Log::System), debug(false) {} PrivateData() : logOutput(Log::System), debug(false) {}
Log::LogOutput logOutput; Log::LogOutput logOutput;
bool debug; bool debug;
static Log *instance; static Log *instance;
#ifdef _WINDOWS #ifdef _WINDOWS
HANDLE eventSource; HANDLE eventSource;
#endif #endif
}; };
Log *Log::PrivateData::instance = 0; Log *Log::PrivateData::instance = 0;
Log::Log() Log::Log()
:d(new PrivateData) :d(new PrivateData)
{ {
#if defined(_LINUX) #if defined(_LINUX)
setlogmask(LOG_UPTO(LOG_INFO)); setlogmask(LOG_UPTO(LOG_INFO));
openlog("telldusd", LOG_CONS, LOG_USER); openlog("telldusd", LOG_CONS, LOG_USER);
#elif defined(_MACOSX) #elif defined(_MACOSX)
d->logOutput = Log::StdOut; d->logOutput = Log::StdOut;
#elif defined(_WINDOWS) #elif defined(_WINDOWS)
//Add ourselves to the registy //Add ourselves to the registy
HKEY hRegKey = NULL; HKEY hRegKey = NULL;
DWORD dwError = 0; DWORD dwError = 0;
TCHAR filePath[MAX_PATH]; TCHAR filePath[MAX_PATH];
std::wstring path(L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\TelldusService"); std::wstring path(L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\TelldusService");
dwError = RegCreateKey( HKEY_LOCAL_MACHINE, path.c_str(), &hRegKey ); dwError = RegCreateKey( HKEY_LOCAL_MACHINE, path.c_str(), &hRegKey );
GetModuleFileName( NULL, filePath, MAX_PATH ); GetModuleFileName( NULL, filePath, MAX_PATH );
dwError = RegSetValueEx( hRegKey, L"EventMessageFile", 0, dwError = RegSetValueEx( hRegKey, L"EventMessageFile", 0,
REG_EXPAND_SZ, (PBYTE) filePath, REG_EXPAND_SZ, (PBYTE) filePath,
(DWORD)(wcslen(filePath) + 1) * sizeof TCHAR ); (DWORD)(wcslen(filePath) + 1) * sizeof TCHAR );
DWORD dwTypes = LOG_DEBUG | LOG_NOTICE | LOG_WARNING | LOG_ERR; DWORD dwTypes = LOG_DEBUG | LOG_NOTICE | LOG_WARNING | LOG_ERR;
dwError = RegSetValueEx( hRegKey, L"TypesSupported", dwError = RegSetValueEx( hRegKey, L"TypesSupported",
0, REG_DWORD, (LPBYTE) &dwTypes, sizeof dwTypes ); 0, REG_DWORD, (LPBYTE) &dwTypes, sizeof dwTypes );
RegCloseKey(hRegKey); RegCloseKey(hRegKey);
d->eventSource = RegisterEventSource(NULL, L"TelldusService"); d->eventSource = RegisterEventSource(NULL, L"TelldusService");
#endif #endif
} }
Log::~Log() { Log::~Log() {
#if defined(_LINUX) #if defined(_LINUX)
closelog(); closelog();
#elif defined(_WINDOWS) #elif defined(_WINDOWS)
if (d->eventSource != NULL) { if (d->eventSource != NULL) {
DeregisterEventSource(d->eventSource); DeregisterEventSource(d->eventSource);
} }
#endif #endif
delete d; delete d;
} }
void Log::destroy() { void Log::destroy() {
if (PrivateData::instance == 0) { if (PrivateData::instance == 0) {
return; return;
} }
delete PrivateData::instance; delete PrivateData::instance;
PrivateData::instance = 0; PrivateData::instance = 0;
} }
void Log::debug(const char *fmt, ...) { void Log::debug(const char *fmt, ...) {
Log *log = Log::instance(); Log *log = Log::instance();
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
log->message(Debug, fmt, ap); log->message(Debug, fmt, ap);
va_end(ap); va_end(ap);
} }
void Log::notice(const char *fmt, ...) { void Log::notice(const char *fmt, ...) {
Log *log = Log::instance(); Log *log = Log::instance();
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
log->message(Notice, fmt, ap); log->message(Notice, fmt, ap);
va_end(ap); va_end(ap);
} }
void Log::warning(const char *fmt, ...) { void Log::warning(const char *fmt, ...) {
Log *log = Log::instance(); Log *log = Log::instance();
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
log->message(Warning, fmt, ap); log->message(Warning, fmt, ap);
va_end(ap); va_end(ap);
} }
void Log::error(const char *fmt, ...) { void Log::error(const char *fmt, ...) {
Log *log = Log::instance(); Log *log = Log::instance();
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
log->message(Error, fmt, ap); log->message(Error, fmt, ap);
va_end(ap); va_end(ap);
} }
void Log::setDebug() { void Log::setDebug() {
Log *log = Log::instance(); Log *log = Log::instance();
log->d->debug = true; log->d->debug = true;
Log::debug("Debug message output enabled"); Log::debug("Debug message output enabled");
} }
void Log::setLogOutput(LogOutput logOutput) { void Log::setLogOutput(LogOutput logOutput) {
#ifdef _MACOSX #ifdef _MACOSX
//Always stdout //Always stdout
return; return;
#endif #endif
Log *log = Log::instance(); Log *log = Log::instance();
log->d->logOutput = logOutput; log->d->logOutput = logOutput;
} }
void Log::message(Log::LogLevel logLevel, const char *format, va_list ap) const { void Log::message(Log::LogLevel logLevel, const char *format, va_list ap) const {
if (logLevel == Debug && d->debug == false) { if (logLevel == Debug && d->debug == false) {
return; return;
} }
if (d->logOutput == StdOut) { if (d->logOutput == StdOut) {
FILE *stream = stdout; FILE *stream = stdout;
if (logLevel == Warning || logLevel == Error) { if (logLevel == Warning || logLevel == Error) {
stream = stderr; stream = stderr;
} }
vfprintf(stream, format, ap); vfprintf(stream, format, ap);
fprintf(stream, "\n"); fprintf(stream, "\n");
fflush(stream); fflush(stream);
} else { } else {
#if defined(_LINUX) #if defined(_LINUX)
switch (logLevel) { switch (logLevel) {
case Debug: case Debug:
vsyslog(LOG_DEBUG, format, ap); vsyslog(LOG_DEBUG, format, ap);
break; break;
case Notice: case Notice:
vsyslog(LOG_NOTICE, format, ap); vsyslog(LOG_NOTICE, format, ap);
break; break;
case Warning: case Warning:
vsyslog(LOG_WARNING, format, ap); vsyslog(LOG_WARNING, format, ap);
break; break;
case Error: case Error:
vsyslog(LOG_ERR, format, ap); vsyslog(LOG_ERR, format, ap);
break; break;
} }
#elif defined(_WINDOWS) #elif defined(_WINDOWS)
LPWSTR pInsertStrings[2] = {NULL, NULL}; LPWSTR pInsertStrings[2] = {NULL, NULL};
std::wstring str = TelldusCore::charToWstring(TelldusCore::sformatf(format, ap).c_str()); std::wstring str = TelldusCore::charToWstring(TelldusCore::sformatf(format, ap).c_str());
pInsertStrings[0] = (LPWSTR)str.c_str(); pInsertStrings[0] = (LPWSTR)str.c_str();
switch (logLevel) { switch (logLevel) {
case Debug: case Debug:
ReportEvent(d->eventSource, EVENTLOG_SUCCESS, NULL, LOG_DEBUG, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL); ReportEvent(d->eventSource, EVENTLOG_SUCCESS, NULL, LOG_DEBUG, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL);
break; break;
case Notice: case Notice:
ReportEvent(d->eventSource, EVENTLOG_INFORMATION_TYPE, NULL, LOG_NOTICE, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL); ReportEvent(d->eventSource, EVENTLOG_INFORMATION_TYPE, NULL, LOG_NOTICE, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL);
break; break;
case Warning: case Warning:
ReportEvent(d->eventSource, EVENTLOG_WARNING_TYPE, NULL, LOG_WARNING, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL); ReportEvent(d->eventSource, EVENTLOG_WARNING_TYPE, NULL, LOG_WARNING, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL);
break; break;
case Error: case Error:
ReportEvent(d->eventSource, EVENTLOG_ERROR_TYPE, NULL, LOG_ERR, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL); ReportEvent(d->eventSource, EVENTLOG_ERROR_TYPE, NULL, LOG_ERR, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL);
break; break;
} }
#endif #endif
} }
} }
Log *Log::instance() { Log *Log::instance() {
if (PrivateData::instance == 0) { if (PrivateData::instance == 0) {
PrivateData::instance = new Log(); PrivateData::instance = new Log();
} }
return PrivateData::instance; return PrivateData::instance;
} }

View file

@ -1,263 +1,263 @@
#include "Protocol.h" #include "Protocol.h"
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
#include "ControllerMessage.h" #include "ControllerMessage.h"
#include "ProtocolBrateck.h" #include "ProtocolBrateck.h"
#include "ProtocolComen.h" #include "ProtocolComen.h"
#include "ProtocolEverflourish.h" #include "ProtocolEverflourish.h"
#include "ProtocolFineoffset.h" #include "ProtocolFineoffset.h"
#include "ProtocolFuhaote.h" #include "ProtocolFuhaote.h"
#include "ProtocolGroup.h" #include "ProtocolGroup.h"
#include "ProtocolHasta.h" #include "ProtocolHasta.h"
#include "ProtocolIkea.h" #include "ProtocolIkea.h"
#include "ProtocolMandolyn.h" #include "ProtocolMandolyn.h"
#include "ProtocolNexa.h" #include "ProtocolNexa.h"
#include "ProtocolOregon.h" #include "ProtocolOregon.h"
#include "ProtocolRisingSun.h" #include "ProtocolRisingSun.h"
#include "ProtocolSartano.h" #include "ProtocolSartano.h"
#include "ProtocolScene.h" #include "ProtocolScene.h"
#include "ProtocolSilvanChip.h" #include "ProtocolSilvanChip.h"
#include "ProtocolUpm.h" #include "ProtocolUpm.h"
#include "ProtocolWaveman.h" #include "ProtocolWaveman.h"
#include "ProtocolX10.h" #include "ProtocolX10.h"
#include "ProtocolYidong.h" #include "ProtocolYidong.h"
#include "Strings.h" #include "Strings.h"
#include <sstream> #include <sstream>
class Protocol::PrivateData { class Protocol::PrivateData {
public: public:
ParameterMap parameterList; ParameterMap parameterList;
std::wstring model; std::wstring model;
}; };
Protocol::Protocol(){ Protocol::Protocol(){
d = new PrivateData; d = new PrivateData;
} }
Protocol::~Protocol(void) { Protocol::~Protocol(void) {
delete d; delete d;
} }
std::wstring Protocol::model() const { std::wstring Protocol::model() const {
std::wstring strModel = d->model; std::wstring strModel = d->model;
//Strip anything after : if it is found //Strip anything after : if it is found
size_t pos = strModel.find(L":"); size_t pos = strModel.find(L":");
if (pos != std::wstring::npos) { if (pos != std::wstring::npos) {
strModel = strModel.substr(0, pos); strModel = strModel.substr(0, pos);
} }
return strModel; return strModel;
} }
void Protocol::setModel(const std::wstring &model){ void Protocol::setModel(const std::wstring &model){
d->model = model; d->model = model;
} }
void Protocol::setParameters(ParameterMap &parameterList){ void Protocol::setParameters(ParameterMap &parameterList){
d->parameterList = parameterList; d->parameterList = parameterList;
} }
std::wstring Protocol::getStringParameter(const std::wstring &name, const std::wstring &defaultValue) const { std::wstring Protocol::getStringParameter(const std::wstring &name, const std::wstring &defaultValue) const {
ParameterMap::const_iterator it = d->parameterList.find(name); ParameterMap::const_iterator it = d->parameterList.find(name);
if (it == d->parameterList.end()) { if (it == d->parameterList.end()) {
return defaultValue; return defaultValue;
} }
return it->second; return it->second;
} }
int Protocol::getIntParameter(const std::wstring &name, int min, int max) const { int Protocol::getIntParameter(const std::wstring &name, int min, int max) const {
std::wstring value = getStringParameter(name, L""); std::wstring value = getStringParameter(name, L"");
if (value == L"") { if (value == L"") {
return min; return min;
} }
std::wstringstream st; std::wstringstream st;
st << value; st << value;
int intValue = 0; int intValue = 0;
st >> intValue; st >> intValue;
if (intValue < min) { if (intValue < min) {
return min; return min;
} }
if (intValue > max) { if (intValue > max) {
return max; return max;
} }
return intValue; return intValue;
} }
bool Protocol::checkBit(int data, int bitno) { bool Protocol::checkBit(int data, int bitno) {
return ((data>>bitno)&0x01); return ((data>>bitno)&0x01);
} }
Protocol *Protocol::getProtocolInstance(const std::wstring &protocolname){ Protocol *Protocol::getProtocolInstance(const std::wstring &protocolname){
if(TelldusCore::comparei(protocolname, L"arctech")){ if(TelldusCore::comparei(protocolname, L"arctech")){
return new ProtocolNexa(); return new ProtocolNexa();
} else if (TelldusCore::comparei(protocolname, L"brateck")) { } else if (TelldusCore::comparei(protocolname, L"brateck")) {
return new ProtocolBrateck(); return new ProtocolBrateck();
} else if (TelldusCore::comparei(protocolname, L"comen")) { } else if (TelldusCore::comparei(protocolname, L"comen")) {
return new ProtocolComen(); return new ProtocolComen();
} else if (TelldusCore::comparei(protocolname, L"everflourish")) { } else if (TelldusCore::comparei(protocolname, L"everflourish")) {
return new ProtocolEverflourish(); return new ProtocolEverflourish();
} else if (TelldusCore::comparei(protocolname, L"fuhaote")) { } else if (TelldusCore::comparei(protocolname, L"fuhaote")) {
return new ProtocolFuhaote(); return new ProtocolFuhaote();
} else if (TelldusCore::comparei(protocolname, L"hasta")) { } else if (TelldusCore::comparei(protocolname, L"hasta")) {
return new ProtocolHasta(); return new ProtocolHasta();
} else if (TelldusCore::comparei(protocolname, L"ikea")) { } else if (TelldusCore::comparei(protocolname, L"ikea")) {
return new ProtocolIkea(); return new ProtocolIkea();
} else if (TelldusCore::comparei(protocolname, L"risingsun")) { } else if (TelldusCore::comparei(protocolname, L"risingsun")) {
return new ProtocolRisingSun(); return new ProtocolRisingSun();
} else if (TelldusCore::comparei(protocolname, L"sartano")) { } else if (TelldusCore::comparei(protocolname, L"sartano")) {
return new ProtocolSartano(); return new ProtocolSartano();
} else if (TelldusCore::comparei(protocolname, L"silvanchip")) { } else if (TelldusCore::comparei(protocolname, L"silvanchip")) {
return new ProtocolSilvanChip(); return new ProtocolSilvanChip();
} else if (TelldusCore::comparei(protocolname, L"upm")) { } else if (TelldusCore::comparei(protocolname, L"upm")) {
return new ProtocolUpm(); return new ProtocolUpm();
} else if (TelldusCore::comparei(protocolname, L"waveman")) { } else if (TelldusCore::comparei(protocolname, L"waveman")) {
return new ProtocolWaveman(); return new ProtocolWaveman();
} else if (TelldusCore::comparei(protocolname, L"x10")) { } else if (TelldusCore::comparei(protocolname, L"x10")) {
return new ProtocolX10(); return new ProtocolX10();
} else if (TelldusCore::comparei(protocolname, L"yidong")) { } else if (TelldusCore::comparei(protocolname, L"yidong")) {
return new ProtocolYidong(); return new ProtocolYidong();
} else if (TelldusCore::comparei(protocolname, L"group")) { } else if (TelldusCore::comparei(protocolname, L"group")) {
return new ProtocolGroup(); return new ProtocolGroup();
} }
else if (TelldusCore::comparei(protocolname, L"scene")) { else if (TelldusCore::comparei(protocolname, L"scene")) {
return new ProtocolScene(); return new ProtocolScene();
} }
return 0; return 0;
} }
std::list<std::string> Protocol::getParametersForProtocol(const std::wstring &protocolName) { std::list<std::string> Protocol::getParametersForProtocol(const std::wstring &protocolName) {
std::list<std::string> parameters; std::list<std::string> parameters;
if(TelldusCore::comparei(protocolName, L"arctech")){ if(TelldusCore::comparei(protocolName, L"arctech")){
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"brateck")) { } else if (TelldusCore::comparei(protocolName, L"brateck")) {
parameters.push_back("house"); parameters.push_back("house");
} else if (TelldusCore::comparei(protocolName, L"comen")) { } else if (TelldusCore::comparei(protocolName, L"comen")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"everflourish")) { } else if (TelldusCore::comparei(protocolName, L"everflourish")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"fuhaote")) { } else if (TelldusCore::comparei(protocolName, L"fuhaote")) {
parameters.push_back("code"); parameters.push_back("code");
} else if (TelldusCore::comparei(protocolName, L"hasta")) { } else if (TelldusCore::comparei(protocolName, L"hasta")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"ikea")) { } else if (TelldusCore::comparei(protocolName, L"ikea")) {
parameters.push_back("system"); parameters.push_back("system");
parameters.push_back("units"); parameters.push_back("units");
//parameters.push_back("fade"); //parameters.push_back("fade");
} else if (TelldusCore::comparei(protocolName, L"risingsun")) { } else if (TelldusCore::comparei(protocolName, L"risingsun")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"sartano")) { } else if (TelldusCore::comparei(protocolName, L"sartano")) {
parameters.push_back("code"); parameters.push_back("code");
} else if (TelldusCore::comparei(protocolName, L"silvanchip")) { } else if (TelldusCore::comparei(protocolName, L"silvanchip")) {
parameters.push_back("house"); parameters.push_back("house");
} else if (TelldusCore::comparei(protocolName, L"upm")) { } else if (TelldusCore::comparei(protocolName, L"upm")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"waveman")) { } else if (TelldusCore::comparei(protocolName, L"waveman")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"x10")) { } else if (TelldusCore::comparei(protocolName, L"x10")) {
parameters.push_back("house"); parameters.push_back("house");
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"yidong")) { } else if (TelldusCore::comparei(protocolName, L"yidong")) {
parameters.push_back("unit"); parameters.push_back("unit");
} else if (TelldusCore::comparei(protocolName, L"group")) { } else if (TelldusCore::comparei(protocolName, L"group")) {
parameters.push_back("devices"); parameters.push_back("devices");
} else if (TelldusCore::comparei(protocolName, L"scene")) { } else if (TelldusCore::comparei(protocolName, L"scene")) {
parameters.push_back("devices"); parameters.push_back("devices");
} }
return parameters; return parameters;
} }
std::list<std::string> Protocol::decodeData(const std::string &fullData) { std::list<std::string> Protocol::decodeData(const std::string &fullData) {
std::list<std::string> retval; std::list<std::string> retval;
std::string decoded = ""; std::string decoded = "";
ControllerMessage dataMsg(fullData); ControllerMessage dataMsg(fullData);
if( TelldusCore::comparei(dataMsg.protocol(), L"arctech") ) { if( TelldusCore::comparei(dataMsg.protocol(), L"arctech") ) {
decoded = ProtocolNexa::decodeData(dataMsg); decoded = ProtocolNexa::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
decoded = ProtocolWaveman::decodeData(dataMsg); decoded = ProtocolWaveman::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
decoded = ProtocolSartano::decodeData(dataMsg); decoded = ProtocolSartano::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
else if(TelldusCore::comparei(dataMsg.protocol(), L"everflourish") ) { else if(TelldusCore::comparei(dataMsg.protocol(), L"everflourish") ) {
decoded = ProtocolEverflourish::decodeData(dataMsg); decoded = ProtocolEverflourish::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
else if(TelldusCore::comparei(dataMsg.protocol(), L"fineoffset") ) { else if(TelldusCore::comparei(dataMsg.protocol(), L"fineoffset") ) {
decoded = ProtocolFineoffset::decodeData(dataMsg); decoded = ProtocolFineoffset::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
else if(TelldusCore::comparei(dataMsg.protocol(), L"mandolyn") ) { else if(TelldusCore::comparei(dataMsg.protocol(), L"mandolyn") ) {
decoded = ProtocolMandolyn::decodeData(dataMsg); decoded = ProtocolMandolyn::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
else if(TelldusCore::comparei(dataMsg.protocol(), L"oregon") ) { else if(TelldusCore::comparei(dataMsg.protocol(), L"oregon") ) {
decoded = ProtocolOregon::decodeData(dataMsg); decoded = ProtocolOregon::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
else if(TelldusCore::comparei(dataMsg.protocol(), L"x10") ) { else if(TelldusCore::comparei(dataMsg.protocol(), L"x10") ) {
decoded = ProtocolX10::decodeData(dataMsg); decoded = ProtocolX10::decodeData(dataMsg);
if (decoded != "") { if (decoded != "") {
retval.push_back(decoded); retval.push_back(decoded);
} }
} }
return retval; return retval;
} }

View file

@ -1,41 +1,41 @@
#ifndef PROTOCOL_H #ifndef PROTOCOL_H
#define PROTOCOL_H #define PROTOCOL_H
#include <string> #include <string>
#include <list> #include <list>
#include <map> #include <map>
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
typedef std::map<std::wstring, std::wstring> ParameterMap; typedef std::map<std::wstring, std::wstring> ParameterMap;
class Controller; class Controller;
class Protocol class Protocol
{ {
public: public:
Protocol(); Protocol();
virtual ~Protocol(void); virtual ~Protocol(void);
static Protocol *getProtocolInstance(const std::wstring &protocolname); static Protocol *getProtocolInstance(const std::wstring &protocolname);
static std::list<std::string> getParametersForProtocol(const std::wstring &protocolName); static std::list<std::string> getParametersForProtocol(const std::wstring &protocolName);
static std::list<std::string> decodeData(const std::string &fullData); static std::list<std::string> decodeData(const std::string &fullData);
virtual int methods() const = 0; virtual int methods() const = 0;
std::wstring model() const; std::wstring model() const;
void setModel(const std::wstring &model); void setModel(const std::wstring &model);
void setParameters(ParameterMap &parameterList); void setParameters(ParameterMap &parameterList);
virtual std::string getStringForMethod(int method, unsigned char data, Controller *controller) = 0; virtual std::string getStringForMethod(int method, unsigned char data, Controller *controller) = 0;
protected: protected:
std::wstring getStringParameter(const std::wstring &name, const std::wstring &defaultValue = L"") const; std::wstring getStringParameter(const std::wstring &name, const std::wstring &defaultValue = L"") const;
int getIntParameter(const std::wstring &name, int min, int max) const; int getIntParameter(const std::wstring &name, int min, int max) const;
static bool checkBit(int data, int bit); static bool checkBit(int data, int bit);
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
#endif //PROTOCOL_H #endif //PROTOCOL_H

View file

@ -1,46 +1,46 @@
#include "ProtocolBrateck.h" #include "ProtocolBrateck.h"
int ProtocolBrateck::methods() const { int ProtocolBrateck::methods() const {
return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP; return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP;
} }
std::string ProtocolBrateck::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolBrateck::getStringForMethod(int method, unsigned char, Controller *) {
const char S = '!'; const char S = '!';
const char L = 'V'; const char L = 'V';
const char B1[] = {L,S,L,S,0}; const char B1[] = {L,S,L,S,0};
const char BX[] = {S,L,L,S,0}; const char BX[] = {S,L,L,S,0};
const char B0[] = {S,L,S,L,0}; const char B0[] = {S,L,S,L,0};
const char BUP[] = {L,S,L,S,S,L,S,L,S,L,S,L,S,L,S,L,S,0}; const char BUP[] = {L,S,L,S,S,L,S,L,S,L,S,L,S,L,S,L,S,0};
const char BSTOP[] = {S,L,S,L,L,S,L,S,S,L,S,L,S,L,S,L,S,0}; const char BSTOP[] = {S,L,S,L,L,S,L,S,S,L,S,L,S,L,S,L,S,0};
const char BDOWN[] = {S,L,S,L,S,L,S,L,S,L,S,L,L,S,L,S,S,0}; const char BDOWN[] = {S,L,S,L,S,L,S,L,S,L,S,L,L,S,L,S,S,0};
std::string strReturn; std::string strReturn;
std::wstring strHouse = this->getStringParameter(L"house", L""); std::wstring strHouse = this->getStringParameter(L"house", L"");
if (strHouse == L"") { if (strHouse == L"") {
return ""; return "";
} }
for( size_t i = 0; i < strHouse.length(); ++i ) { for( size_t i = 0; i < strHouse.length(); ++i ) {
if (strHouse[i] == '1') { if (strHouse[i] == '1') {
strReturn.insert(0, B1); strReturn.insert(0, B1);
} else if (strHouse[i] == '-') { } else if (strHouse[i] == '-') {
strReturn.insert(0, BX); strReturn.insert(0, BX);
} else if (strHouse[i] == '0') { } else if (strHouse[i] == '0') {
strReturn.insert(0, B0); strReturn.insert(0, B0);
} }
} }
strReturn.insert(0, "S"); strReturn.insert(0, "S");
if (method == TELLSTICK_UP) { if (method == TELLSTICK_UP) {
strReturn.append(BUP); strReturn.append(BUP);
} else if (method == TELLSTICK_DOWN) { } else if (method == TELLSTICK_DOWN) {
strReturn.append(BDOWN); strReturn.append(BDOWN);
} else if (method == TELLSTICK_STOP) { } else if (method == TELLSTICK_STOP) {
strReturn.append(BSTOP); strReturn.append(BSTOP);
} else { } else {
return ""; return "";
} }
strReturn.append("+"); strReturn.append("+");
return strReturn; return strReturn;
} }

View file

@ -1,12 +1,12 @@
#include "ProtocolComen.h" #include "ProtocolComen.h"
int ProtocolComen::methods() const { int ProtocolComen::methods() const {
return (TELLSTICK_TURNON | TELLSTICK_TURNOFF); return (TELLSTICK_TURNON | TELLSTICK_TURNOFF);
} }
std::string ProtocolComen::getStringForMethod(int method, unsigned char level, Controller *) { std::string ProtocolComen::getStringForMethod(int method, unsigned char level, Controller *) {
int intHouse = getIntParameter(L"house", 1, 33554431); int intHouse = getIntParameter(L"house", 1, 33554431);
intHouse <<= 1; //They seem to only accept even codes? intHouse <<= 1; //They seem to only accept even codes?
int intCode = getIntParameter(L"unit", 1, 16)-1; int intCode = getIntParameter(L"unit", 1, 16)-1;
return getStringSelflearningForCode(intHouse, intCode, method, level); return getStringSelflearningForCode(intHouse, intCode, method, level);
} }

View file

@ -1,131 +1,131 @@
#include "ProtocolEverflourish.h" #include "ProtocolEverflourish.h"
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
#include "ControllerMessage.h" #include "ControllerMessage.h"
int ProtocolEverflourish::methods() const { int ProtocolEverflourish::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN; return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN;
} }
std::string ProtocolEverflourish::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolEverflourish::getStringForMethod(int method, unsigned char, Controller *) {
unsigned int deviceCode = this->getIntParameter(L"house", 0, 16383); unsigned int deviceCode = this->getIntParameter(L"house", 0, 16383);
unsigned int intCode = this->getIntParameter(L"unit", 1, 4)-1; unsigned int intCode = this->getIntParameter(L"unit", 1, 4)-1;
unsigned char action; unsigned char action;
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
action = 15; action = 15;
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
action = 0; action = 0;
} else if (method == TELLSTICK_LEARN) { } else if (method == TELLSTICK_LEARN) {
action = 10; action = 10;
} else { } else {
return ""; return "";
} }
const char ssss = 85; const char ssss = 85;
const char sssl = 84; // 0 const char sssl = 84; // 0
const char slss = 69; // 1 const char slss = 69; // 1
const char bits[2] = {sssl,slss}; const char bits[2] = {sssl,slss};
int i, check; int i, check;
std::string strCode; std::string strCode;
deviceCode = (deviceCode << 2) | intCode; deviceCode = (deviceCode << 2) | intCode;
check = calculateChecksum(deviceCode); check = calculateChecksum(deviceCode);
char preamble[] = {'R', 5, 'T', 114,60,1,1,105,ssss,ssss,0}; char preamble[] = {'R', 5, 'T', 114,60,1,1,105,ssss,ssss,0};
strCode.append(preamble); strCode.append(preamble);
for(i=15;i>=0;i--) { for(i=15;i>=0;i--) {
strCode.append(1, bits[(deviceCode>>i)&0x01]); strCode.append(1, bits[(deviceCode>>i)&0x01]);
} }
for(i=3;i>=0;i--) { for(i=3;i>=0;i--) {
strCode.append(1, bits[(check>>i)&0x01]); strCode.append(1, bits[(check>>i)&0x01]);
} }
for(i=3;i>=0;i--) { for(i=3;i>=0;i--) {
strCode.append(1, bits[(action>>i)&0x01]); strCode.append(1, bits[(action>>i)&0x01]);
} }
strCode.append(1, ssss); strCode.append(1, ssss);
strCode.append(1, '+'); strCode.append(1, '+');
return strCode; return strCode;
} }
// The calculation used in this function is provided by Frank Stevenson // The calculation used in this function is provided by Frank Stevenson
unsigned int ProtocolEverflourish::calculateChecksum(unsigned int x) { unsigned int ProtocolEverflourish::calculateChecksum(unsigned int x) {
unsigned int bits[16] = { unsigned int bits[16] = {
0xf ,0xa ,0x7 ,0xe, 0xf ,0xa ,0x7 ,0xe,
0xf ,0xd ,0x9 ,0x1, 0xf ,0xd ,0x9 ,0x1,
0x1 ,0x2 ,0x4 ,0x8, 0x1 ,0x2 ,0x4 ,0x8,
0x3 ,0x6 ,0xc ,0xb 0x3 ,0x6 ,0xc ,0xb
}; };
unsigned int bit = 1; unsigned int bit = 1;
unsigned int res = 0x5; unsigned int res = 0x5;
int i; int i;
unsigned int lo,hi; unsigned int lo,hi;
if ((x&0x3)==3) { if ((x&0x3)==3) {
lo = x & 0x00ff; lo = x & 0x00ff;
hi = x & 0xff00; hi = x & 0xff00;
lo += 4; lo += 4;
if (lo>0x100) { if (lo>0x100) {
lo = 0x12; lo = 0x12;
} }
x = lo | hi; x = lo | hi;
} }
for(i=0;i<16;i++) { for(i=0;i<16;i++) {
if (x&bit) { if (x&bit) {
res = res ^ bits[i]; res = res ^ bits[i];
} }
bit = bit << 1; bit = bit << 1;
} }
return res; return res;
} }
std::string ProtocolEverflourish::decodeData(ControllerMessage &dataMsg) std::string ProtocolEverflourish::decodeData(ControllerMessage &dataMsg)
{ {
std::string data = dataMsg.getParameter("data"); std::string data = dataMsg.getParameter("data");
unsigned int allData; unsigned int allData;
unsigned int house = 0; unsigned int house = 0;
unsigned int unit = 0; unsigned int unit = 0;
unsigned int method = 0; unsigned int method = 0;
sscanf(data.c_str(), "%X", &allData); sscanf(data.c_str(), "%X", &allData);
house = allData & 0xFFFC00; house = allData & 0xFFFC00;
house >>= 10; house >>= 10;
unit = allData & 0x300; unit = allData & 0x300;
unit >>= 8; unit >>= 8;
unit++; //unit from 1 to 4 unit++; //unit from 1 to 4
method = allData & 0xF; method = allData & 0xF;
if(house < 0 || house > 16383 || unit < 1 || unit > 4){ if(house < 0 || house > 16383 || unit < 1 || unit > 4){
//not everflourish //not everflourish
return ""; return "";
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:everflourish;model:selflearning;house:" << house << ";unit:" << unit << ";method:"; retString << "class:command;protocol:everflourish;model:selflearning;house:" << house << ";unit:" << unit << ";method:";
if(method == 0){ if(method == 0){
retString << "turnoff;"; retString << "turnoff;";
} }
else if(method == 15){ else if(method == 15){
retString << "turnon;"; retString << "turnon;";
} }
else if(method == 10){ else if(method == 10){
retString << "learn;"; retString << "learn;";
} }
else { else {
//not everflourish //not everflourish
return ""; return "";
} }
return retString.str(); return retString.str();
} }

View file

@ -1,45 +1,45 @@
#include "ProtocolFineoffset.h" #include "ProtocolFineoffset.h"
#include "Strings.h" #include "Strings.h"
#include <stdlib.h> #include <stdlib.h>
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
std::string ProtocolFineoffset::decodeData(ControllerMessage &dataMsg) std::string ProtocolFineoffset::decodeData(ControllerMessage &dataMsg)
{ {
std::string data = dataMsg.getParameter("data"); std::string data = dataMsg.getParameter("data");
if (data.length() < 8) { if (data.length() < 8) {
return ""; return "";
} }
uint8_t checksum = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2)); uint8_t checksum = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2));
data = data.substr(0, data.length()-2); data = data.substr(0, data.length()-2);
uint8_t humidity = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2)); uint8_t humidity = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2));
data = data.substr(0, data.length()-2); data = data.substr(0, data.length()-2);
uint16_t value = (uint16_t)TelldusCore::hexTo64l(data.substr(data.length()-3)); uint16_t value = (uint16_t)TelldusCore::hexTo64l(data.substr(data.length()-3));
double temperature = (value & 0x7FF)/10.0; double temperature = (value & 0x7FF)/10.0;
value >>= 11; value >>= 11;
if (value & 1) { if (value & 1) {
temperature = -temperature; temperature = -temperature;
} }
data = data.substr(0, data.length()-3); data = data.substr(0, data.length()-3);
uint16_t id = (uint16_t)TelldusCore::hexTo64l(data) & 0xFF; uint16_t id = (uint16_t)TelldusCore::hexTo64l(data) & 0xFF;
std::stringstream retString; std::stringstream retString;
retString << "class:sensor;protocol:fineoffset;id:" << id << ";model:"; retString << "class:sensor;protocol:fineoffset;id:" << id << ";model:";
if (humidity <= 100) { if (humidity <= 100) {
retString << "temperaturehumidity;humidity:" << (int)humidity << ";"; retString << "temperaturehumidity;humidity:" << (int)humidity << ";";
} else if (humidity == 0xFF) { } else if (humidity == 0xFF) {
retString << "temperature;"; retString << "temperature;";
} else { } else {
return ""; return "";
} }
retString << "temp:" << std::fixed << std::setprecision(1) << temperature << ";"; retString << "temp:" << std::fixed << std::setprecision(1) << temperature << ";";
return retString.str(); return retString.str();
} }

View file

@ -1,54 +1,54 @@
#include "ProtocolFuhaote.h" #include "ProtocolFuhaote.h"
int ProtocolFuhaote::methods() const { int ProtocolFuhaote::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF; return TELLSTICK_TURNON | TELLSTICK_TURNOFF;
} }
std::string ProtocolFuhaote::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolFuhaote::getStringForMethod(int method, unsigned char, Controller *) {
const char S = 19; const char S = 19;
const char L = 58; const char L = 58;
const char B0[] = {S,L,L,S,0}; const char B0[] = {S,L,L,S,0};
const char B1[] = {L,S,L,S,0}; const char B1[] = {L,S,L,S,0};
const char OFF[] = {S,L,S,L,S,L,L,S,0}; const char OFF[] = {S,L,S,L,S,L,L,S,0};
const char ON[] = {S,L,L,S,S,L,S,L,0}; const char ON[] = {S,L,L,S,S,L,S,L,0};
std::string strReturn = "S"; std::string strReturn = "S";
std::wstring strCode = this->getStringParameter(L"code", L""); std::wstring strCode = this->getStringParameter(L"code", L"");
if (strCode == L"") { if (strCode == L"") {
return ""; return "";
} }
//House code //House code
for(size_t i = 0; i < 5; ++i) { for(size_t i = 0; i < 5; ++i) {
if (strCode[i] == '0') { if (strCode[i] == '0') {
strReturn.append(B0); strReturn.append(B0);
} else if (strCode[i] == '1') { } else if (strCode[i] == '1') {
strReturn.append(B1); strReturn.append(B1);
} }
} }
//Unit code //Unit code
for(size_t i = 5; i < 10; ++i) { for(size_t i = 5; i < 10; ++i) {
if (strCode[i] == '0') { if (strCode[i] == '0') {
strReturn.append(B0); strReturn.append(B0);
} else if (strCode[i] == '1') { } else if (strCode[i] == '1') {
strReturn.append(1, S); strReturn.append(1, S);
strReturn.append(1, L); strReturn.append(1, L);
strReturn.append(1, S); strReturn.append(1, S);
strReturn.append(1, L); strReturn.append(1, L);
} }
} }
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strReturn.append(ON); strReturn.append(ON);
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strReturn.append(OFF); strReturn.append(OFF);
} else { } else {
return ""; return "";
} }
strReturn.append(1, S); strReturn.append(1, S);
strReturn.append("+"); strReturn.append("+");
return strReturn; return strReturn;
} }

View file

@ -1,9 +1,9 @@
#include "ProtocolGroup.h" #include "ProtocolGroup.h"
int ProtocolGroup::methods() const { int ProtocolGroup::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM | TELLSTICK_BELL | TELLSTICK_LEARN | TELLSTICK_EXECUTE | TELLSTICK_TOGGLE | TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP; return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM | TELLSTICK_BELL | TELLSTICK_LEARN | TELLSTICK_EXECUTE | TELLSTICK_TOGGLE | TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP;
} }
std::string ProtocolGroup::getStringForMethod(int method, unsigned char data, Controller *) { std::string ProtocolGroup::getStringForMethod(int method, unsigned char data, Controller *) {
return ""; return "";
} }

View file

@ -10,7 +10,7 @@ public:
}; };
#endif //PROTOCOLGROUP_H #endif //PROTOCOLGROUP_H

View file

@ -1,66 +1,66 @@
#include "ProtocolHasta.h" #include "ProtocolHasta.h"
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
int ProtocolHasta::methods() const { int ProtocolHasta::methods() const {
return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP | TELLSTICK_LEARN; return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP | TELLSTICK_LEARN;
} }
std::string ProtocolHasta::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolHasta::getStringForMethod(int method, unsigned char, Controller *) {
int house = this->getIntParameter(L"house", 1, 65536); int house = this->getIntParameter(L"house", 1, 65536);
int unit = this->getIntParameter(L"unit", 1, 15); int unit = this->getIntParameter(L"unit", 1, 15);
std::string strReturn; std::string strReturn;
std::string preamble; std::string preamble;
strReturn.append(1, 190); strReturn.append(1, 190);
strReturn.append(1, 1); strReturn.append(1, 1);
strReturn.append(1, 190); strReturn.append(1, 190);
strReturn.append(1, 1); strReturn.append(1, 1);
strReturn.append(1, 190); strReturn.append(1, 190);
strReturn.append(1, 190); strReturn.append(1, 190);
strReturn.append(convertByte( (house&0xFF) )); strReturn.append(convertByte( (house&0xFF) ));
strReturn.append(convertByte( (house>>8)&0xFF )); strReturn.append(convertByte( (house>>8)&0xFF ));
int byte = unit&0x0F; int byte = unit&0x0F;
if (method == TELLSTICK_UP) { if (method == TELLSTICK_UP) {
byte |= 0x00; byte |= 0x00;
} else if (method == TELLSTICK_DOWN) { } else if (method == TELLSTICK_DOWN) {
byte |= 0x10; byte |= 0x10;
} else if (method == TELLSTICK_STOP) { } else if (method == TELLSTICK_STOP) {
byte |= 0x50; byte |= 0x50;
} else if (method == TELLSTICK_LEARN) { } else if (method == TELLSTICK_LEARN) {
byte |= 0x40; byte |= 0x40;
} else { } else {
return ""; return "";
} }
strReturn.append(convertByte(byte)); strReturn.append(convertByte(byte));
strReturn.append(convertByte(0x0)); strReturn.append(convertByte(0x0));
strReturn.append(convertByte(0x0)); strReturn.append(convertByte(0x0));
//Remove the last pulse //Remove the last pulse
strReturn.erase(strReturn.end()-1,strReturn.end()); strReturn.erase(strReturn.end()-1,strReturn.end());
return strReturn; return strReturn;
} }
std::string ProtocolHasta::convertByte(unsigned char byte) { std::string ProtocolHasta::convertByte(unsigned char byte) {
std::string retval; std::string retval;
for(int i = 0; i < 8; ++i) { for(int i = 0; i < 8; ++i) {
if (byte & 1) { if (byte & 1) {
retval.append(1, 33); retval.append(1, 33);
retval.append(1, 17); retval.append(1, 17);
} else { } else {
retval.append(1, 17); retval.append(1, 17);
retval.append(1, 33); retval.append(1, 33);
} }
byte >>= 1; byte >>= 1;
} }
return retval; return retval;
} }

View file

@ -1,127 +1,127 @@
#include "ProtocolIkea.h" #include "ProtocolIkea.h"
#include "Strings.h" #include "Strings.h"
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
int ProtocolIkea::methods() const { int ProtocolIkea::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM; return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM;
} }
std::string ProtocolIkea::getStringForMethod(int method, unsigned char level, Controller *) { std::string ProtocolIkea::getStringForMethod(int method, unsigned char level, Controller *) {
int intSystem = this->getIntParameter(L"system", 1, 16)-1; int intSystem = this->getIntParameter(L"system", 1, 16)-1;
int intFadeStyle = TelldusCore::comparei(this->getStringParameter(L"fade", L"true"), L"true"); int intFadeStyle = TelldusCore::comparei(this->getStringParameter(L"fade", L"true"), L"true");
std::wstring wstrUnits = this->getStringParameter(L"units", L""); std::wstring wstrUnits = this->getStringParameter(L"units", L"");
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
level = 255; level = 255;
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
level = 0; level = 0;
} else if (method == TELLSTICK_DIM) { } else if (method == TELLSTICK_DIM) {
} else { } else {
return ""; return "";
} }
if (wstrUnits == L"") { if (wstrUnits == L"") {
return ""; return "";
} }
std::string strUnits(TelldusCore::wideToString(wstrUnits)); std::string strUnits(TelldusCore::wideToString(wstrUnits));
int intUnits = 0; //Start without any units int intUnits = 0; //Start without any units
char *tempUnits = new char[strUnits.size()+1]; char *tempUnits = new char[strUnits.size()+1];
#ifdef _WINDOWS #ifdef _WINDOWS
strcpy_s(tempUnits, strUnits.size()+1, strUnits.c_str()); strcpy_s(tempUnits, strUnits.size()+1, strUnits.c_str());
#else #else
strcpy(tempUnits, strUnits.c_str()); strcpy(tempUnits, strUnits.c_str());
#endif #endif
char *strToken = strtok(tempUnits, ","); char *strToken = strtok(tempUnits, ",");
do { do {
int intUnit = atoi(strToken); int intUnit = atoi(strToken);
if (intUnit == 10) { if (intUnit == 10) {
intUnit = 0; intUnit = 0;
} }
intUnits = intUnits | ( 1<<(9-intUnit) ); intUnits = intUnits | ( 1<<(9-intUnit) );
} while ( (strToken = strtok(NULL, ",")) != NULL ); } while ( (strToken = strtok(NULL, ",")) != NULL );
delete[] tempUnits; delete[] tempUnits;
std::string strReturn = "STTTTTTª"; //Startcode, always like this; std::string strReturn = "STTTTTTª"; //Startcode, always like this;
std::string strChannels = ""; std::string strChannels = "";
int intCode = (intSystem << 10) | intUnits; int intCode = (intSystem << 10) | intUnits;
int checksum1 = 0; int checksum1 = 0;
int checksum2 = 0; int checksum2 = 0;
for (int i = 13; i >= 0; --i) { for (int i = 13; i >= 0; --i) {
if ((intCode>>i) & 1) { if ((intCode>>i) & 1) {
strChannels.append("TT"); strChannels.append("TT");
if (i % 2 == 0) if (i % 2 == 0)
checksum2++; checksum2++;
else else
checksum1++; checksum1++;
} else { } else {
strChannels.append("ª"); strChannels.append("ª");
} }
} }
strReturn.append(strChannels); //System + Units strReturn.append(strChannels); //System + Units
strReturn.append(checksum1 %2 == 0 ? "TT" : "ª"); //1st checksum strReturn.append(checksum1 %2 == 0 ? "TT" : "ª"); //1st checksum
strReturn.append(checksum2 %2 == 0 ? "TT" : "ª"); //2nd checksum strReturn.append(checksum2 %2 == 0 ? "TT" : "ª"); //2nd checksum
int intLevel = 0; int intLevel = 0;
if (level <= 12) { if (level <= 12) {
intLevel = 10; // Level 10 is actually off intLevel = 10; // Level 10 is actually off
} else if (level <= 37) { } else if (level <= 37) {
intLevel = 1; intLevel = 1;
} else if (level <= 62) { } else if (level <= 62) {
intLevel = 2; intLevel = 2;
} else if (level <= 87) { } else if (level <= 87) {
intLevel = 3; intLevel = 3;
} else if (level <= 112) { } else if (level <= 112) {
intLevel = 4; intLevel = 4;
} else if (level <= 137) { } else if (level <= 137) {
intLevel = 5; intLevel = 5;
} else if (level <= 162) { } else if (level <= 162) {
intLevel = 6; intLevel = 6;
} else if (level <= 187) { } else if (level <= 187) {
intLevel = 7; intLevel = 7;
} else if (level <= 212) { } else if (level <= 212) {
intLevel = 8; intLevel = 8;
} else if (level <= 237) { } else if (level <= 237) {
intLevel = 9; intLevel = 9;
} else { } else {
intLevel = 0; // Level 0 is actually full on intLevel = 0; // Level 0 is actually full on
} }
int intFade = 0; int intFade = 0;
if (intFadeStyle == 1) { if (intFadeStyle == 1) {
intFade = 11 << 4; //Smooth intFade = 11 << 4; //Smooth
} else { } else {
intFade = 1 << 4; //Instant intFade = 1 << 4; //Instant
} }
intCode = intLevel | intFade; //Concat level and fade intCode = intLevel | intFade; //Concat level and fade
checksum1 = 0; checksum1 = 0;
checksum2 = 0; checksum2 = 0;
for (int i = 0; i < 6; ++i) { for (int i = 0; i < 6; ++i) {
if ((intCode>>i) & 1) { if ((intCode>>i) & 1) {
strReturn.append("TT"); strReturn.append("TT");
if (i % 2 == 0) if (i % 2 == 0)
checksum1++; checksum1++;
else else
checksum2++; checksum2++;
} else { } else {
strReturn.append("ª"); strReturn.append("ª");
} }
} }
strReturn.append(checksum1 %2 == 0 ? "TT" : "ª"); //1st checksum strReturn.append(checksum1 %2 == 0 ? "TT" : "ª"); //1st checksum
strReturn.append(checksum2 %2 == 0 ? "TT" : "ª"); //2nd checksum strReturn.append(checksum2 %2 == 0 ? "TT" : "ª"); //2nd checksum
strReturn.append("+"); strReturn.append("+");
return strReturn; return strReturn;
} }

View file

@ -1,38 +1,38 @@
#include "ProtocolMandolyn.h" #include "ProtocolMandolyn.h"
#include "Strings.h" #include "Strings.h"
#include <stdlib.h> #include <stdlib.h>
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
std::string ProtocolMandolyn::decodeData(ControllerMessage &dataMsg) std::string ProtocolMandolyn::decodeData(ControllerMessage &dataMsg)
{ {
std::string data = dataMsg.getParameter("data"); std::string data = dataMsg.getParameter("data");
uint32_t value = (uint32_t)TelldusCore::hexTo64l(data); uint32_t value = (uint32_t)TelldusCore::hexTo64l(data);
bool parity = value & 0x1; bool parity = value & 0x1;
value >>= 1; value >>= 1;
double temp = (double)(value & 0x7FFF) - (double)6400; double temp = (double)(value & 0x7FFF) - (double)6400;
temp = temp/128.0; temp = temp/128.0;
value >>= 15; value >>= 15;
uint8_t humidity = (value & 0x7F); uint8_t humidity = (value & 0x7F);
value >>= 7; value >>= 7;
bool battOk = value & 0x1; bool battOk = value & 0x1;
value >>= 3; value >>= 3;
uint8_t channel = (value & 0x3)+1; uint8_t channel = (value & 0x3)+1;
value >>= 2; value >>= 2;
uint8_t house = value & 0xF; uint8_t house = value & 0xF;
std::stringstream retString; std::stringstream retString;
retString << "class:sensor;protocol:mandolyn;id:" retString << "class:sensor;protocol:mandolyn;id:"
<< house*10+channel << house*10+channel
<< ";model:temperaturehumidity;" << ";model:temperaturehumidity;"
<< "temp:" << std::fixed << std::setprecision(1) << temp << "temp:" << std::fixed << std::setprecision(1) << temp
<< ";humidity:" << (int)humidity << ";"; << ";humidity:" << (int)humidity << ";";
return retString.str(); return retString.str();
} }

View file

@ -1,282 +1,282 @@
#include "ProtocolNexa.h" #include "ProtocolNexa.h"
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
#include "TellStick.h" #include "TellStick.h"
#include "Strings.h" #include "Strings.h"
int ProtocolNexa::lastArctecCodeSwitchWasTurnOff=0; //TODO, always removing first turnon now, make more flexible (waveman too) int ProtocolNexa::lastArctecCodeSwitchWasTurnOff=0; //TODO, always removing first turnon now, make more flexible (waveman too)
int ProtocolNexa::methods() const { int ProtocolNexa::methods() const {
if (TelldusCore::comparei(model(), L"codeswitch")) { if (TelldusCore::comparei(model(), L"codeswitch")) {
return (TELLSTICK_TURNON | TELLSTICK_TURNOFF); return (TELLSTICK_TURNON | TELLSTICK_TURNOFF);
} else if (TelldusCore::comparei(model(), L"selflearning-switch")) { } else if (TelldusCore::comparei(model(), L"selflearning-switch")) {
return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN); return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN);
} else if (TelldusCore::comparei(model(), L"selflearning-dimmer")) { } else if (TelldusCore::comparei(model(), L"selflearning-dimmer")) {
return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM | TELLSTICK_LEARN); return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_DIM | TELLSTICK_LEARN);
} else if (TelldusCore::comparei(model(), L"bell")) { } else if (TelldusCore::comparei(model(), L"bell")) {
return TELLSTICK_BELL; return TELLSTICK_BELL;
} }
return 0; return 0;
} }
std::string ProtocolNexa::getStringForMethod(int method, unsigned char data, Controller *controller) { std::string ProtocolNexa::getStringForMethod(int method, unsigned char data, Controller *controller) {
if (TelldusCore::comparei(model(), L"codeswitch")) { if (TelldusCore::comparei(model(), L"codeswitch")) {
return getStringCodeSwitch(method); return getStringCodeSwitch(method);
} else if (TelldusCore::comparei(model(), L"bell")) { } else if (TelldusCore::comparei(model(), L"bell")) {
return getStringBell(); return getStringBell();
} }
if ((method == TELLSTICK_TURNON) && TelldusCore::comparei(model(), L"selflearning-dimmer")) { if ((method == TELLSTICK_TURNON) && TelldusCore::comparei(model(), L"selflearning-dimmer")) {
//Workaround for not letting a dimmer do into "dimming mode" //Workaround for not letting a dimmer do into "dimming mode"
return getStringSelflearning(TELLSTICK_DIM, 255); return getStringSelflearning(TELLSTICK_DIM, 255);
} }
if (method == TELLSTICK_LEARN) { if (method == TELLSTICK_LEARN) {
std::string str = getStringSelflearning(TELLSTICK_TURNON, data); std::string str = getStringSelflearning(TELLSTICK_TURNON, data);
//Check to see if we are an old TellStick (fw <= 2, batch <= 8) //Check to see if we are an old TellStick (fw <= 2, batch <= 8)
TellStick *ts = reinterpret_cast<TellStick *>(controller); TellStick *ts = reinterpret_cast<TellStick *>(controller);
if (!ts) { if (!ts) {
return str; return str;
} }
if (ts->pid() == 0x0c30 && ts->firmwareVersion() <= 2) { if (ts->pid() == 0x0c30 && ts->firmwareVersion() <= 2) {
//Workaround for the bug in early firmwares //Workaround for the bug in early firmwares
//The TellStick have a fixed pause (max) between two packets. //The TellStick have a fixed pause (max) between two packets.
//It is only correct between the first and second packet. //It is only correct between the first and second packet.
//It seems faster to send two packes at a time and some //It seems faster to send two packes at a time and some
//receivers seems picky about this when learning. //receivers seems picky about this when learning.
//We also return the last packet so Device::doAction() doesn't //We also return the last packet so Device::doAction() doesn't
//report TELLSTICK_ERROR_METHOD_NOT_SUPPORTED //report TELLSTICK_ERROR_METHOD_NOT_SUPPORTED
str.insert(0, 1, 2); //Repeat two times str.insert(0, 1, 2); //Repeat two times
str.insert(0, 1, 'R'); str.insert(0, 1, 'R');
for (int i = 0; i < 5; ++i) { for (int i = 0; i < 5; ++i) {
controller->send(str); controller->send(str);
} }
} }
return str; return str;
} }
return getStringSelflearning(method, data); return getStringSelflearning(method, data);
} }
std::string ProtocolNexa::getStringCodeSwitch(int method) { std::string ProtocolNexa::getStringCodeSwitch(int method) {
std::string strReturn = "S"; std::string strReturn = "S";
std::wstring house = getStringParameter(L"house", L"A"); std::wstring house = getStringParameter(L"house", L"A");
int intHouse = house[0] - L'A'; int intHouse = house[0] - L'A';
strReturn.append(getCodeSwitchTuple(intHouse)); strReturn.append(getCodeSwitchTuple(intHouse));
strReturn.append(getCodeSwitchTuple(getIntParameter(L"unit", 1, 16)-1)); strReturn.append(getCodeSwitchTuple(getIntParameter(L"unit", 1, 16)-1));
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strReturn.append("$k$k$kk$$kk$$kk$$k+"); strReturn.append("$k$k$kk$$kk$$kk$$k+");
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strReturn.append(this->getOffCode()); strReturn.append(this->getOffCode());
} else { } else {
return ""; return "";
} }
return strReturn; return strReturn;
} }
std::string ProtocolNexa::getStringBell() { std::string ProtocolNexa::getStringBell() {
std::string strReturn = "S"; std::string strReturn = "S";
std::wstring house = getStringParameter(L"house", L"A"); std::wstring house = getStringParameter(L"house", L"A");
int intHouse = house[0] - L'A'; int intHouse = house[0] - L'A';
strReturn.append(getCodeSwitchTuple(intHouse)); strReturn.append(getCodeSwitchTuple(intHouse));
strReturn.append("$kk$$kk$$kk$$k$k"); //Unit 7 strReturn.append("$kk$$kk$$kk$$k$k"); //Unit 7
strReturn.append("$kk$$kk$$kk$$kk$$k+"); //Bell strReturn.append("$kk$$kk$$kk$$kk$$k+"); //Bell
return strReturn; return strReturn;
} }
std::string ProtocolNexa::getStringSelflearning(int method, unsigned char level) { std::string ProtocolNexa::getStringSelflearning(int method, unsigned char level) {
int intHouse = getIntParameter(L"house", 1, 67108863); int intHouse = getIntParameter(L"house", 1, 67108863);
int intCode = getIntParameter(L"unit", 1, 16)-1; int intCode = getIntParameter(L"unit", 1, 16)-1;
return getStringSelflearningForCode(intHouse, intCode, method, level); return getStringSelflearningForCode(intHouse, intCode, method, level);
} }
std::string ProtocolNexa::getStringSelflearningForCode(int intHouse, int intCode, int method, unsigned char level) { std::string ProtocolNexa::getStringSelflearningForCode(int intHouse, int intCode, int method, unsigned char level) {
const unsigned char START[] = {'T',127,255,24,1,0}; const unsigned char START[] = {'T',127,255,24,1,0};
// const char START[] = {'T',130,255,26,24,0}; // const char START[] = {'T',130,255,26,24,0};
std::string strMessage(reinterpret_cast<const char*>(START)); std::string strMessage(reinterpret_cast<const char*>(START));
strMessage.append(1,(method == TELLSTICK_DIM ? 147 : 132)); //Number of pulses strMessage.append(1,(method == TELLSTICK_DIM ? 147 : 132)); //Number of pulses
std::string m; std::string m;
for (int i = 25; i >= 0; --i) { for (int i = 25; i >= 0; --i) {
m.append( intHouse & 1 << i ? "10" : "01" ); m.append( intHouse & 1 << i ? "10" : "01" );
} }
m.append("01"); //Group m.append("01"); //Group
//On/off //On/off
if (method == TELLSTICK_DIM) { if (method == TELLSTICK_DIM) {
m.append("00"); m.append("00");
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
m.append("01"); m.append("01");
} else if (method == TELLSTICK_TURNON) { } else if (method == TELLSTICK_TURNON) {
m.append("10"); m.append("10");
} else { } else {
return ""; return "";
} }
for (int i = 3; i >= 0; --i) { for (int i = 3; i >= 0; --i) {
m.append( intCode & 1 << i ? "10" : "01" ); m.append( intCode & 1 << i ? "10" : "01" );
} }
if (method == TELLSTICK_DIM) { if (method == TELLSTICK_DIM) {
unsigned char newLevel = level/16; unsigned char newLevel = level/16;
for (int i = 3; i >= 0; --i) { for (int i = 3; i >= 0; --i) {
m.append(newLevel & 1 << i ? "10" : "01"); m.append(newLevel & 1 << i ? "10" : "01");
} }
} }
//The number of data is odd. //The number of data is odd.
//Add this to make it even, otherwise the following loop will not work //Add this to make it even, otherwise the following loop will not work
m.append("0"); m.append("0");
unsigned char code = 9; //b1001, startcode unsigned char code = 9; //b1001, startcode
for (unsigned int i = 0; i < m.length(); ++i) { for (unsigned int i = 0; i < m.length(); ++i) {
code <<= 4; code <<= 4;
if (m[i] == '1') { if (m[i] == '1') {
code |= 8; //b1000 code |= 8; //b1000
} else { } else {
code |= 10; //b1010 code |= 10; //b1010
// code |= 11; //b1011 // code |= 11; //b1011
} }
if (i % 2 == 0) { if (i % 2 == 0) {
strMessage.append(1,code); strMessage.append(1,code);
code = 0; code = 0;
} }
} }
strMessage.append("+"); strMessage.append("+");
// for( int i = 0; i < strMessage.length(); ++i ) { // for( int i = 0; i < strMessage.length(); ++i ) {
// printf("%i,", (unsigned char)strMessage[i]); // printf("%i,", (unsigned char)strMessage[i]);
// } // }
// printf("\n"); // printf("\n");
return strMessage; return strMessage;
} }
std::string ProtocolNexa::decodeData(ControllerMessage& dataMsg) std::string ProtocolNexa::decodeData(ControllerMessage& dataMsg)
{ {
unsigned long allData = 0; unsigned long allData = 0;
sscanf(dataMsg.getParameter("data").c_str(), "%lx", &allData); sscanf(dataMsg.getParameter("data").c_str(), "%lx", &allData);
if(TelldusCore::comparei(dataMsg.model(), L"selflearning")){ if(TelldusCore::comparei(dataMsg.model(), L"selflearning")){
//selflearning //selflearning
return decodeDataSelfLearning(allData); return decodeDataSelfLearning(allData);
} }
else{ else{
//codeswitch //codeswitch
return decodeDataCodeSwitch(allData); return decodeDataCodeSwitch(allData);
} }
} }
std::string ProtocolNexa::decodeDataSelfLearning(long allData){ std::string ProtocolNexa::decodeDataSelfLearning(long allData){
unsigned int house = 0; unsigned int house = 0;
unsigned int unit = 0; unsigned int unit = 0;
unsigned int group = 0; unsigned int group = 0;
unsigned int method = 0; unsigned int method = 0;
house = allData & 0xFFFFFFC0; house = allData & 0xFFFFFFC0;
house >>= 6; house >>= 6;
group = allData & 0x20; group = allData & 0x20;
group >>= 5; group >>= 5;
method = allData & 0x10; method = allData & 0x10;
method >>= 4; method >>= 4;
unit = allData & 0xF; unit = allData & 0xF;
unit++; unit++;
if(house < 1 || house > 67108863 || unit < 1 || unit > 16){ if(house < 1 || house > 67108863 || unit < 1 || unit > 16){
//not arctech selflearning //not arctech selflearning
return ""; return "";
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:arctech;model:selflearning;house:" << house << ";unit:" << unit << ";group:" << group << ";method:"; retString << "class:command;protocol:arctech;model:selflearning;house:" << house << ";unit:" << unit << ";group:" << group << ";method:";
if(method == 1){ if(method == 1){
retString << "turnon;"; retString << "turnon;";
} }
else if(method == 0){ else if(method == 0){
retString << "turnoff;"; retString << "turnoff;";
} }
else { else {
//not arctech selflearning //not arctech selflearning
return ""; return "";
} }
return retString.str(); return retString.str();
} }
std::string ProtocolNexa::decodeDataCodeSwitch(long allData){ std::string ProtocolNexa::decodeDataCodeSwitch(long allData){
unsigned int house = 0; unsigned int house = 0;
unsigned int unit = 0; unsigned int unit = 0;
unsigned int method = 0; unsigned int method = 0;
method = allData & 0xF00; method = allData & 0xF00;
method >>= 8; method >>= 8;
unit = allData & 0xF0; unit = allData & 0xF0;
unit >>= 4; unit >>= 4;
unit++; unit++;
house = allData & 0xF; house = allData & 0xF;
if(house < 0 || house > 16 || unit < 1 || unit > 16){ if(house < 0 || house > 16 || unit < 1 || unit > 16){
//not arctech codeswitch //not arctech codeswitch
return ""; return "";
} }
house = house + 'A'; //house from A to P house = house + 'A'; //house from A to P
if(method != 6 && lastArctecCodeSwitchWasTurnOff == 1){ if(method != 6 && lastArctecCodeSwitchWasTurnOff == 1){
lastArctecCodeSwitchWasTurnOff = 0; lastArctecCodeSwitchWasTurnOff = 0;
return ""; //probably a stray turnon or bell (perhaps: only certain time interval since last, check that it's the same house/unit... Will lose return ""; //probably a stray turnon or bell (perhaps: only certain time interval since last, check that it's the same house/unit... Will lose
//one turnon/bell, but it's better than the alternative... //one turnon/bell, but it's better than the alternative...
} }
if(method == 6){ if(method == 6){
lastArctecCodeSwitchWasTurnOff = 1; lastArctecCodeSwitchWasTurnOff = 1;
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:arctech;model:codeswitch;house:" << char(house); retString << "class:command;protocol:arctech;model:codeswitch;house:" << char(house);
if(method == 6){ if(method == 6){
retString << ";unit:" << unit << ";method:turnoff;"; retString << ";unit:" << unit << ";method:turnoff;";
} }
else if(method == 14){ else if(method == 14){
retString << ";unit:" << unit << ";method:turnon;"; retString << ";unit:" << unit << ";method:turnon;";
} }
else if(method == 15){ else if(method == 15){
retString << ";method:bell;"; retString << ";method:bell;";
} }
else { else {
//not arctech codeswitch //not arctech codeswitch
return ""; return "";
} }
return retString.str(); return retString.str();
} }
std::string ProtocolNexa::getCodeSwitchTuple(int intCode) { std::string ProtocolNexa::getCodeSwitchTuple(int intCode) {
std::string strReturn = ""; std::string strReturn = "";
for( int i = 0; i < 4; ++i ) { for( int i = 0; i < 4; ++i ) {
if (intCode & 1) { //Convert 1 if (intCode & 1) { //Convert 1
strReturn.append("$kk$"); strReturn.append("$kk$");
} else { //Convert 0 } else { //Convert 0
strReturn.append("$k$k"); strReturn.append("$k$k");
} }
intCode >>= 1; intCode >>= 1;
} }
return strReturn; return strReturn;
} }
std::string ProtocolNexa::getOffCode() const { std::string ProtocolNexa::getOffCode() const {
return "$k$k$kk$$kk$$k$k$k+"; return "$k$k$kk$$kk$$k$k$k+";
} }

View file

@ -1,115 +1,115 @@
#include "ProtocolOregon.h" #include "ProtocolOregon.h"
#include "Strings.h" #include "Strings.h"
#include <stdlib.h> #include <stdlib.h>
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
std::string ProtocolOregon::decodeData(ControllerMessage &dataMsg) std::string ProtocolOregon::decodeData(ControllerMessage &dataMsg)
{ {
std::string data = dataMsg.getParameter("data"); std::string data = dataMsg.getParameter("data");
std::wstring model = dataMsg.model(); std::wstring model = dataMsg.model();
if (model.compare(L"0xEA4C") == 0) { if (model.compare(L"0xEA4C") == 0) {
return decodeEA4C(data); return decodeEA4C(data);
} else if (model.compare(L"0x1A2D") == 0) { } else if (model.compare(L"0x1A2D") == 0) {
return decode1A2D(data); return decode1A2D(data);
} }
return ""; return "";
} }
std::string ProtocolOregon::decodeEA4C(const std::string &data) { std::string ProtocolOregon::decodeEA4C(const std::string &data) {
uint64_t value = TelldusCore::hexTo64l(data); uint64_t value = TelldusCore::hexTo64l(data);
uint8_t checksum = 0xE + 0xA + 0x4 + 0xC; uint8_t checksum = 0xE + 0xA + 0x4 + 0xC;
checksum -= (value & 0xF) * 0x10; checksum -= (value & 0xF) * 0x10;
checksum -= 0xA; checksum -= 0xA;
value >>= 8; value >>= 8;
uint8_t checksumw = (value >> 4) & 0xF; uint8_t checksumw = (value >> 4) & 0xF;
bool neg = value & (1 << 3); bool neg = value & (1 << 3);
checksum += (value & 0xF); checksum += (value & 0xF);
value >>= 8; value >>= 8;
uint8_t temp2 = value & 0xF; uint8_t temp2 = value & 0xF;
uint8_t temp1 = (value >> 4) & 0xF; uint8_t temp1 = (value >> 4) & 0xF;
checksum += temp2 + temp1; checksum += temp2 + temp1;
value >>= 8; value >>= 8;
uint8_t temp3 = (value >> 4) & 0xF; uint8_t temp3 = (value >> 4) & 0xF;
checksum += (value & 0xF) + temp3; checksum += (value & 0xF) + temp3;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t address = value & 0xFF; uint8_t address = value & 0xFF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t channel = (value >> 4) & 0x7; uint8_t channel = (value >> 4) & 0x7;
if (checksum != checksumw) { if (checksum != checksumw) {
return ""; return "";
} }
double temperature = ((temp1 * 100) + (temp2 * 10) + temp3)/10.0; double temperature = ((temp1 * 100) + (temp2 * 10) + temp3)/10.0;
if (neg) { if (neg) {
temperature = -temperature; temperature = -temperature;
} }
std::stringstream retString; std::stringstream retString;
retString << "class:sensor;protocol:oregon;model:EA4C;id:" << (int)address retString << "class:sensor;protocol:oregon;model:EA4C;id:" << (int)address
<< ";temp:" << std::fixed << std::setprecision(1) << temperature << ";"; << ";temp:" << std::fixed << std::setprecision(1) << temperature << ";";
return retString.str(); return retString.str();
} }
std::string ProtocolOregon::decode1A2D(const std::string &data) { std::string ProtocolOregon::decode1A2D(const std::string &data) {
uint64_t value = TelldusCore::hexTo64l(data); uint64_t value = TelldusCore::hexTo64l(data);
uint8_t checksum2 = value & 0xFF; uint8_t checksum2 = value & 0xFF;
value >>= 8; value >>= 8;
uint8_t checksum1 = value & 0xFF; uint8_t checksum1 = value & 0xFF;
value >>= 8; value >>= 8;
uint8_t checksum = ((value >> 4) & 0xF) + (value & 0xF); uint8_t checksum = ((value >> 4) & 0xF) + (value & 0xF);
uint8_t hum1 = value & 0xF; uint8_t hum1 = value & 0xF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t neg = value & (1 << 3); uint8_t neg = value & (1 << 3);
uint8_t hum2 = (value >> 4) & 0xF; uint8_t hum2 = (value >> 4) & 0xF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t temp2 = value & 0xF; uint8_t temp2 = value & 0xF;
uint8_t temp1 = (value >> 4) & 0xF; uint8_t temp1 = (value >> 4) & 0xF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t temp3 = (value >> 4) & 0xF; uint8_t temp3 = (value >> 4) & 0xF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t address = value & 0xFF; uint8_t address = value & 0xFF;
value >>= 8; value >>= 8;
checksum += ((value >> 4) & 0xF) + (value & 0xF); checksum += ((value >> 4) & 0xF) + (value & 0xF);
uint8_t channel = (value >> 4) & 0x7; uint8_t channel = (value >> 4) & 0x7;
checksum += 0x1 + 0xA + 0x2 + 0xD - 0xA; checksum += 0x1 + 0xA + 0x2 + 0xD - 0xA;
//TODO: Find out how checksum2 works //TODO: Find out how checksum2 works
if (checksum != checksum1) { if (checksum != checksum1) {
return ""; return "";
} }
double temperature = ((temp1 * 100) + (temp2 * 10) + temp3)/10.0; double temperature = ((temp1 * 100) + (temp2 * 10) + temp3)/10.0;
if (neg) { if (neg) {
temperature = -temperature; temperature = -temperature;
} }
std::stringstream retString; std::stringstream retString;
retString << "class:sensor;protocol:oregon;model:1A2D;id:" << (int)address retString << "class:sensor;protocol:oregon;model:1A2D;id:" << (int)address
<< ";temp:" << std::fixed << std::setprecision(1) << temperature << ";"; << ";temp:" << std::fixed << std::setprecision(1) << temperature << ";";
return retString.str(); return retString.str();
} }

View file

@ -1,111 +1,111 @@
#include "ProtocolRisingSun.h" #include "ProtocolRisingSun.h"
#include "Strings.h" #include "Strings.h"
int ProtocolRisingSun::methods() const { int ProtocolRisingSun::methods() const {
if (TelldusCore::comparei(model(), L"selflearning")) { if (TelldusCore::comparei(model(), L"selflearning")) {
return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN); return (TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN);
} }
return TELLSTICK_TURNON | TELLSTICK_TURNOFF; return TELLSTICK_TURNON | TELLSTICK_TURNOFF;
} }
std::string ProtocolRisingSun::getStringForMethod(int method, unsigned char data, Controller *controller) { std::string ProtocolRisingSun::getStringForMethod(int method, unsigned char data, Controller *controller) {
if (TelldusCore::comparei(model(), L"selflearning")) { if (TelldusCore::comparei(model(), L"selflearning")) {
return getStringSelflearning(method); return getStringSelflearning(method);
} }
return getStringCodeSwitch(method); return getStringCodeSwitch(method);
} }
std::string ProtocolRisingSun::getStringSelflearning(int method) { std::string ProtocolRisingSun::getStringSelflearning(int method) {
int intHouse = this->getIntParameter(L"house", 1, 33554432)-1; int intHouse = this->getIntParameter(L"house", 1, 33554432)-1;
int intCode = this->getIntParameter(L"code", 1, 16)-1; int intCode = this->getIntParameter(L"code", 1, 16)-1;
const char code_on[][7] = { const char code_on[][7] = {
"110110", "001110", "100110", "010110", "110110", "001110", "100110", "010110",
"111001", "000101", "101001", "011001", "111001", "000101", "101001", "011001",
"110000", "001000", "100000", "010000", "110000", "001000", "100000", "010000",
"111100", "000010", "101100", "011100" "111100", "000010", "101100", "011100"
}; };
const char code_off[][7] = { const char code_off[][7] = {
"111110", "000001", "101110", "011110", "111110", "000001", "101110", "011110",
"110101", "001101", "100101", "010101", "110101", "001101", "100101", "010101",
"111000", "000100", "101000", "011000", "111000", "000100", "101000", "011000",
"110010", "001010", "100010", "010010" "110010", "001010", "100010", "010010"
}; };
const char l = 120; const char l = 120;
const char s = 51; const char s = 51;
std::string strCode = "10"; std::string strCode = "10";
int code = intCode; int code = intCode;
code = (code < 0 ? 0 : code); code = (code < 0 ? 0 : code);
code = (code > 15 ? 15 : code); code = (code > 15 ? 15 : code);
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strCode.append(code_on[code]); strCode.append(code_on[code]);
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strCode.append(code_off[code]); strCode.append(code_off[code]);
} else if (method == TELLSTICK_LEARN) { } else if (method == TELLSTICK_LEARN) {
strCode.append(code_on[code]); strCode.append(code_on[code]);
} else { } else {
return ""; return "";
} }
int house = intHouse; int house = intHouse;
for(int i = 0; i < 25; ++i) { for(int i = 0; i < 25; ++i) {
if (house & 1) { if (house & 1) {
strCode.append(1, '1'); strCode.append(1, '1');
} else { } else {
strCode.append(1, '0'); strCode.append(1, '0');
} }
house >>= 1; house >>= 1;
} }
std::string strReturn; std::string strReturn;
for(unsigned int i = 0; i < strCode.length(); ++i) { for(unsigned int i = 0; i < strCode.length(); ++i) {
if (strCode[i] == '1') { if (strCode[i] == '1') {
strReturn.append(1, l); strReturn.append(1, l);
strReturn.append(1, s); strReturn.append(1, s);
} else { } else {
strReturn.append(1, s); strReturn.append(1, s);
strReturn.append(1, l); strReturn.append(1, l);
} }
} }
std::string prefix = "P"; std::string prefix = "P";
prefix.append(1, 5); prefix.append(1, 5);
if (method == TELLSTICK_LEARN) { if (method == TELLSTICK_LEARN) {
prefix.append("R"); prefix.append("R");
prefix.append( 1, 50 ); prefix.append( 1, 50 );
} }
prefix.append("S"); prefix.append("S");
strReturn.insert(0, prefix); strReturn.insert(0, prefix);
strReturn.append(1, '+'); strReturn.append(1, '+');
return strReturn; return strReturn;
} }
std::string ProtocolRisingSun::getStringCodeSwitch(int method) { std::string ProtocolRisingSun::getStringCodeSwitch(int method) {
std::string strReturn = "S.e"; std::string strReturn = "S.e";
strReturn.append(getCodeSwitchTuple(this->getIntParameter(L"house", 1, 4)-1)); strReturn.append(getCodeSwitchTuple(this->getIntParameter(L"house", 1, 4)-1));
strReturn.append(getCodeSwitchTuple(this->getIntParameter(L"unit", 1, 4)-1)); strReturn.append(getCodeSwitchTuple(this->getIntParameter(L"unit", 1, 4)-1));
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strReturn.append("e..ee..ee..ee..e+"); strReturn.append("e..ee..ee..ee..e+");
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strReturn.append("e..ee..ee..e.e.e+"); strReturn.append("e..ee..ee..e.e.e+");
} else { } else {
return ""; return "";
} }
return strReturn; return strReturn;
} }
std::string ProtocolRisingSun::getCodeSwitchTuple(int intToConvert) { std::string ProtocolRisingSun::getCodeSwitchTuple(int intToConvert) {
std::string strReturn = ""; std::string strReturn = "";
for(int i = 0; i < 4; ++i) { for(int i = 0; i < 4; ++i) {
if (i == intToConvert) { if (i == intToConvert) {
strReturn.append( ".e.e" ); strReturn.append( ".e.e" );
} else { } else {
strReturn.append( "e..e" ); strReturn.append( "e..e" );
} }
} }
return strReturn; return strReturn;
} }

View file

@ -1,104 +1,104 @@
#include "ProtocolSartano.h" #include "ProtocolSartano.h"
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
int ProtocolSartano::methods() const { int ProtocolSartano::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF; return TELLSTICK_TURNON | TELLSTICK_TURNOFF;
} }
std::string ProtocolSartano::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolSartano::getStringForMethod(int method, unsigned char, Controller *) {
std::wstring strCode = this->getStringParameter(L"code", L""); std::wstring strCode = this->getStringParameter(L"code", L"");
return getStringForCode(strCode, method); return getStringForCode(strCode, method);
} }
std::string ProtocolSartano::getStringForCode(const std::wstring &strCode, int method) { std::string ProtocolSartano::getStringForCode(const std::wstring &strCode, int method) {
std::string strReturn("S"); std::string strReturn("S");
for (size_t i = 0; i < strCode.length(); ++i) { for (size_t i = 0; i < strCode.length(); ++i) {
if (strCode[i] == L'1') { if (strCode[i] == L'1') {
strReturn.append("$k$k"); strReturn.append("$k$k");
} else { } else {
strReturn.append("$kk$"); strReturn.append("$kk$");
} }
} }
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strReturn.append("$k$k$kk$$k+"); strReturn.append("$k$k$kk$$k+");
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strReturn.append("$kk$$k$k$k+"); strReturn.append("$kk$$k$k$k+");
} else { } else {
return ""; return "";
} }
return strReturn; return strReturn;
} }
std::string ProtocolSartano::decodeData(ControllerMessage &dataMsg) std::string ProtocolSartano::decodeData(ControllerMessage &dataMsg)
{ {
std::string data = dataMsg.getParameter("data"); std::string data = dataMsg.getParameter("data");
signed int allDataIn; signed int allDataIn;
signed int allData = 0; signed int allData = 0;
unsigned int code = 0; unsigned int code = 0;
unsigned int method1 = 0; unsigned int method1 = 0;
unsigned int method2 = 0; unsigned int method2 = 0;
unsigned int method = 0; unsigned int method = 0;
sscanf(data.c_str(), "%X", &allDataIn); sscanf(data.c_str(), "%X", &allDataIn);
unsigned long mask = (1<<11); unsigned long mask = (1<<11);
for(int i=0;i<12;++i){ for(int i=0;i<12;++i){
allData >>= 1; allData >>= 1;
if((allDataIn & mask) == 0){ if((allDataIn & mask) == 0){
allData |= (1<<11); allData |= (1<<11);
} }
mask >>= 1; mask >>= 1;
} }
code = allData & 0xFFC; code = allData & 0xFFC;
code >>= 2; code >>= 2;
method1 = allData & 0x2; method1 = allData & 0x2;
method1 >>= 1; method1 >>= 1;
method2 = allData & 0x1; method2 = allData & 0x1;
if(method1 == 0 && method2 == 1){ if(method1 == 0 && method2 == 1){
method = 0; //off method = 0; //off
} }
else if(method1 == 1 && method2 == 0){ else if(method1 == 1 && method2 == 0){
method = 1; //on method = 1; //on
} }
else{ else{
return ""; return "";
} }
if(code < 0 || code > 1023){ if(code < 0 || code > 1023){
//not sartano //not sartano
return ""; return "";
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:sartano;model:codeswitch;code:"; retString << "class:command;protocol:sartano;model:codeswitch;code:";
mask = (1<<9); mask = (1<<9);
for(int i=0;i<10;i++){ for(int i=0;i<10;i++){
if((code & mask) != 0){ if((code & mask) != 0){
retString << 1; retString << 1;
} }
else{ else{
retString << 0; retString << 0;
} }
mask >>= 1; mask >>= 1;
} }
retString << ";method:"; retString << ";method:";
if(method == 0){ if(method == 0){
retString << "turnoff;"; retString << "turnoff;";
} }
else{ else{
retString << "turnon;"; retString << "turnon;";
} }
return retString.str(); return retString.str();
} }

View file

@ -1,9 +1,9 @@
#include "ProtocolScene.h" #include "ProtocolScene.h"
int ProtocolScene::methods() const { int ProtocolScene::methods() const {
return TELLSTICK_EXECUTE; return TELLSTICK_EXECUTE;
} }
std::string ProtocolScene::getStringForMethod(int method, unsigned char data, Controller *) { std::string ProtocolScene::getStringForMethod(int method, unsigned char data, Controller *) {
return ""; return "";
} }

View file

@ -10,7 +10,7 @@ public:
}; };
#endif //PROTOCOLSCENE_H #endif //PROTOCOLSCENE_H

View file

@ -1,140 +1,140 @@
#include "ProtocolSilvanChip.h" #include "ProtocolSilvanChip.h"
#include "Strings.h" #include "Strings.h"
int ProtocolSilvanChip::methods() const { int ProtocolSilvanChip::methods() const {
if (TelldusCore::comparei(model(), L"kp100")) { if (TelldusCore::comparei(model(), L"kp100")) {
return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP | TELLSTICK_LEARN; return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP | TELLSTICK_LEARN;
} else if (TelldusCore::comparei(model(), L"ecosavers")) { } else if (TelldusCore::comparei(model(), L"ecosavers")) {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN; return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN;
} else if (TelldusCore::comparei(model(), L"displaymatic")) { } else if (TelldusCore::comparei(model(), L"displaymatic")) {
return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP; return TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP;
} }
return 0; return 0;
} }
std::string ProtocolSilvanChip::getStringForMethod(int method, unsigned char data, Controller *controller) { std::string ProtocolSilvanChip::getStringForMethod(int method, unsigned char data, Controller *controller) {
if (TelldusCore::comparei(model(), L"kp100")) { if (TelldusCore::comparei(model(), L"kp100")) {
std::string preamble; std::string preamble;
preamble.append(1, 100); preamble.append(1, 100);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 100); preamble.append(1, 100);
const std::string one = "\xFF\x1\x2E\x2E"; const std::string one = "\xFF\x1\x2E\x2E";
const std::string zero = "\x2E\xFF\x1\x2E"; const std::string zero = "\x2E\xFF\x1\x2E";
int button = 0; int button = 0;
if (method == TELLSTICK_UP) { if (method == TELLSTICK_UP) {
button = 2; button = 2;
} else if (method == TELLSTICK_DOWN) { } else if (method == TELLSTICK_DOWN) {
button = 8; button = 8;
} else if (method == TELLSTICK_STOP) { } else if (method == TELLSTICK_STOP) {
button = 4; button = 4;
} else if (method == TELLSTICK_LEARN) { } else if (method == TELLSTICK_LEARN) {
button = 1; button = 1;
} else { } else {
return ""; return "";
} }
return this->getString(preamble, one, zero, button); return this->getString(preamble, one, zero, button);
} else if (TelldusCore::comparei(model(), L"displaymatic")) { } else if (TelldusCore::comparei(model(), L"displaymatic")) {
std::string preamble; std::string preamble;
preamble.append(1, 0x25); preamble.append(1, 0x25);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 0x25); preamble.append(1, 0x25);
const std::string one = "\x69\25"; const std::string one = "\x69\25";
const std::string zero = "\x25\x69"; const std::string zero = "\x25\x69";
int button = 0; int button = 0;
if (method == TELLSTICK_UP) { if (method == TELLSTICK_UP) {
button = 1; button = 1;
} else if (method == TELLSTICK_DOWN) { } else if (method == TELLSTICK_DOWN) {
button = 4; button = 4;
} else if (method == TELLSTICK_STOP) { } else if (method == TELLSTICK_STOP) {
button = 2; button = 2;
} }
return this->getString(preamble, one, zero, button); return this->getString(preamble, one, zero, button);
} else if (TelldusCore::comparei(model(), L"ecosavers")) { } else if (TelldusCore::comparei(model(), L"ecosavers")) {
std::string preamble; std::string preamble;
preamble.append(1, 0x25); preamble.append(1, 0x25);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 255); preamble.append(1, 255);
preamble.append(1, 1); preamble.append(1, 1);
preamble.append(1, 0x25); preamble.append(1, 0x25);
const std::string one = "\x69\25"; const std::string one = "\x69\25";
const std::string zero = "\x25\x69"; const std::string zero = "\x25\x69";
int intUnit = this->getIntParameter(L"unit", 1, 4); int intUnit = this->getIntParameter(L"unit", 1, 4);
int button = 0; int button = 0;
if (intUnit == 1) { if (intUnit == 1) {
button = 7; button = 7;
} else if (intUnit == 2) { } else if (intUnit == 2) {
button = 3; button = 3;
} else if (intUnit == 3) { } else if (intUnit == 3) {
button = 5; button = 5;
} else if (intUnit == 4) { } else if (intUnit == 4) {
button = 6; button = 6;
} }
if (method == TELLSTICK_TURNON || method == TELLSTICK_LEARN) { if (method == TELLSTICK_TURNON || method == TELLSTICK_LEARN) {
button |= 8; button |= 8;
} }
return this->getString(preamble, one, zero, button); return this->getString(preamble, one, zero, button);
} }
return ""; return "";
} }
std::string ProtocolSilvanChip::getString(const std::string &preamble, const std::string &one, const std::string &zero, int button) { std::string ProtocolSilvanChip::getString(const std::string &preamble, const std::string &one, const std::string &zero, int button) {
int intHouse = this->getIntParameter(L"house", 1, 1048575); int intHouse = this->getIntParameter(L"house", 1, 1048575);
std::string strReturn = preamble; std::string strReturn = preamble;
for( int i = 19; i >= 0; --i ) { for( int i = 19; i >= 0; --i ) {
if (intHouse & (1 << i)) { if (intHouse & (1 << i)) {
strReturn.append(one); strReturn.append(one);
} else { } else {
strReturn.append(zero); strReturn.append(zero);
} }
} }
for( int i = 3; i >= 0; --i) { for( int i = 3; i >= 0; --i) {
if (button & (1 << i)) { if (button & (1 << i)) {
strReturn.append(one); strReturn.append(one);
} else { } else {
strReturn.append(zero); strReturn.append(zero);
} }
} }
strReturn.append(zero); strReturn.append(zero);
return strReturn; return strReturn;
} }

View file

@ -1,71 +1,71 @@
#include "ProtocolUpm.h" #include "ProtocolUpm.h"
int ProtocolUpm::methods() const { int ProtocolUpm::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN; return TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_LEARN;
} }
std::string ProtocolUpm::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolUpm::getStringForMethod(int method, unsigned char, Controller *) {
const char S = ';'; const char S = ';';
const char L = '~'; const char L = '~';
const char START[] = {S,0}; const char START[] = {S,0};
const char B1[] = {L,S,0}; const char B1[] = {L,S,0};
const char B0[] = {S,L,0}; const char B0[] = {S,L,0};
//const char BON[] = {S,L,L,S,0}; //const char BON[] = {S,L,L,S,0};
//const char BOFF[] = {S,L,S,L,0}; //const char BOFF[] = {S,L,S,L,0};
int intUnit = this->getIntParameter(L"unit", 1, 4)-1; int intUnit = this->getIntParameter(L"unit", 1, 4)-1;
std::string strReturn; std::string strReturn;
int code = this->getIntParameter(L"house", 0, 4095); int code = this->getIntParameter(L"house", 0, 4095);
for( size_t i = 0; i < 12; ++i ) { for( size_t i = 0; i < 12; ++i ) {
if (code & 1) { if (code & 1) {
strReturn.insert(0, B1); strReturn.insert(0, B1);
} else { } else {
strReturn.insert(0, B0); strReturn.insert(0, B0);
} }
code >>= 1; code >>= 1;
} }
strReturn.insert(0, START); //Startcode, first strReturn.insert(0, START); //Startcode, first
code = 0; code = 0;
if (method == TELLSTICK_TURNON || method == TELLSTICK_LEARN) { if (method == TELLSTICK_TURNON || method == TELLSTICK_LEARN) {
code += 2; code += 2;
} else if (method != TELLSTICK_TURNOFF) { } else if (method != TELLSTICK_TURNOFF) {
return ""; return "";
} }
code <<= 2; code <<= 2;
code += intUnit; code += intUnit;
int check1 = 0, check2 = 0; int check1 = 0, check2 = 0;
for( size_t i = 0; i < 6; ++i ) { for( size_t i = 0; i < 6; ++i ) {
if (code & 1) { if (code & 1) {
if (i % 2 == 0) { if (i % 2 == 0) {
check1++; check1++;
} else { } else {
check2++; check2++;
} }
} }
if (code & 1) { if (code & 1) {
strReturn.append(B1); strReturn.append(B1);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
} }
code >>= 1; code >>= 1;
} }
if (check1 % 2 == 0) { if (check1 % 2 == 0) {
strReturn.append(B0); strReturn.append(B0);
} else { } else {
strReturn.append(B1); strReturn.append(B1);
} }
if (check2 % 2 == 0) { if (check2 % 2 == 0) {
strReturn.append(B0); strReturn.append(B0);
} else { } else {
strReturn.append(B1); strReturn.append(B1);
} }
strReturn.insert(0, "S"); strReturn.insert(0, "S");
strReturn.append("+"); strReturn.append("+");
return strReturn; return strReturn;
} }

View file

@ -1,69 +1,69 @@
#include "ProtocolWaveman.h" #include "ProtocolWaveman.h"
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
int ProtocolWaveman::lastArctecCodeSwitchWasTurnOff=0; int ProtocolWaveman::lastArctecCodeSwitchWasTurnOff=0;
int ProtocolWaveman::methods() const { int ProtocolWaveman::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF; return TELLSTICK_TURNON | TELLSTICK_TURNOFF;
} }
std::string ProtocolWaveman::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolWaveman::getStringForMethod(int method, unsigned char, Controller *) {
return getStringCodeSwitch(method); return getStringCodeSwitch(method);
} }
std::string ProtocolWaveman::getOffCode() const { std::string ProtocolWaveman::getOffCode() const {
return "$k$k$k$k$k$k$k$k$k+"; return "$k$k$k$k$k$k$k$k$k+";
} }
std::string ProtocolWaveman::decodeData(ControllerMessage& dataMsg) std::string ProtocolWaveman::decodeData(ControllerMessage& dataMsg)
{ {
unsigned long allData = 0; unsigned long allData = 0;
unsigned int house = 0; unsigned int house = 0;
unsigned int unit = 0; unsigned int unit = 0;
unsigned int method = 0; unsigned int method = 0;
sscanf(dataMsg.getParameter("data").c_str(), "%lx", &allData); sscanf(dataMsg.getParameter("data").c_str(), "%lx", &allData);
method = allData & 0xF00; method = allData & 0xF00;
method >>= 8; method >>= 8;
unit = allData & 0xF0; unit = allData & 0xF0;
unit >>= 4; unit >>= 4;
unit++; unit++;
house = allData & 0xF; house = allData & 0xF;
if(house < 0 || house > 16 || unit < 1 || unit > 16){ if(house < 0 || house > 16 || unit < 1 || unit > 16){
//not waveman //not waveman
return ""; return "";
} }
house = house + 'A'; //house from A to P house = house + 'A'; //house from A to P
if(method != 6 && lastArctecCodeSwitchWasTurnOff == 1){ if(method != 6 && lastArctecCodeSwitchWasTurnOff == 1){
lastArctecCodeSwitchWasTurnOff = 0; lastArctecCodeSwitchWasTurnOff = 0;
return ""; //probably a stray turnon or bell (perhaps: only certain time interval since last, check that it's the same house/unit... Will lose return ""; //probably a stray turnon or bell (perhaps: only certain time interval since last, check that it's the same house/unit... Will lose
//one turnon/bell, but it's better than the alternative... //one turnon/bell, but it's better than the alternative...
} }
if(method == 6){ if(method == 6){
lastArctecCodeSwitchWasTurnOff = 1; lastArctecCodeSwitchWasTurnOff = 1;
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:waveman;model:codeswitch;house:" << char(house); retString << "class:command;protocol:waveman;model:codeswitch;house:" << char(house);
if(method == 0){ if(method == 0){
retString << ";unit:" << unit << ";method:turnoff;"; retString << ";unit:" << unit << ";method:turnoff;";
} }
else if(method == 14){ else if(method == 14){
retString << ";unit:" << unit << ";method:turnon;"; retString << ";unit:" << unit << ";method:turnon;";
} }
else { else {
//not waveman //not waveman
return ""; return "";
} }
return retString.str(); return retString.str();
} }

View file

@ -1,174 +1,174 @@
#include "ProtocolX10.h" #include "ProtocolX10.h"
#include <stdio.h> #include <stdio.h>
#include <sstream> #include <sstream>
const unsigned char HOUSES[] = {6,0xE,2,0xA,1,9,5,0xD,7,0xF,3,0xB,0,8,4,0xC}; const unsigned char HOUSES[] = {6,0xE,2,0xA,1,9,5,0xD,7,0xF,3,0xB,0,8,4,0xC};
int ProtocolX10::methods() const { int ProtocolX10::methods() const {
return TELLSTICK_TURNON | TELLSTICK_TURNOFF; return TELLSTICK_TURNON | TELLSTICK_TURNOFF;
} }
std::string ProtocolX10::getStringForMethod(int method, unsigned char data, Controller *controller) { std::string ProtocolX10::getStringForMethod(int method, unsigned char data, Controller *controller) {
const unsigned char S = 59, L = 169; const unsigned char S = 59, L = 169;
const char B0[] = {S,S,0}; const char B0[] = {S,S,0};
const char B1[] = {S,L,0}; const char B1[] = {S,L,0};
const unsigned char START_CODE[] = {'S',255,1,255,1,255,1,100,255,1,180,0}; const unsigned char START_CODE[] = {'S',255,1,255,1,255,1,100,255,1,180,0};
const unsigned char STOP_CODE[] = {S,0}; const unsigned char STOP_CODE[] = {S,0};
std::string strReturn = reinterpret_cast<const char*>(START_CODE); std::string strReturn = reinterpret_cast<const char*>(START_CODE);
std::string strComplement = ""; std::string strComplement = "";
std::wstring strHouse = getStringParameter(L"house", L"A"); std::wstring strHouse = getStringParameter(L"house", L"A");
int intHouse = strHouse[0] - L'A'; int intHouse = strHouse[0] - L'A';
if (intHouse < 0) { if (intHouse < 0) {
intHouse = 0; intHouse = 0;
} else if (intHouse > 15) { } else if (intHouse > 15) {
intHouse = 15; intHouse = 15;
} }
//Translate it //Translate it
intHouse = HOUSES[intHouse]; intHouse = HOUSES[intHouse];
int intCode = getIntParameter(L"unit", 1, 16)-1; int intCode = getIntParameter(L"unit", 1, 16)-1;
for( int i = 0; i < 4; ++i ) { for( int i = 0; i < 4; ++i ) {
if (intHouse & 1) { if (intHouse & 1) {
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} }
intHouse >>= 1; intHouse >>= 1;
} }
strReturn.append( B0 ); strReturn.append( B0 );
strComplement.append( B1 ); strComplement.append( B1 );
if (intCode >= 8) { if (intCode >= 8) {
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} }
strReturn.append( B0 ); strReturn.append( B0 );
strComplement.append( B1 ); strComplement.append( B1 );
strReturn.append( B0 ); strReturn.append( B0 );
strComplement.append( B1 ); strComplement.append( B1 );
strReturn.append( strComplement ); strReturn.append( strComplement );
strComplement = ""; strComplement = "";
strReturn.append( B0 ); strReturn.append( B0 );
strComplement.append( B1 ); strComplement.append( B1 );
if (intCode >> 2 & 1) { //Bit 2 of intCode if (intCode >> 2 & 1) { //Bit 2 of intCode
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} }
if (method == TELLSTICK_TURNON) { if (method == TELLSTICK_TURNON) {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} else if (method == TELLSTICK_TURNOFF) { } else if (method == TELLSTICK_TURNOFF) {
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
return ""; return "";
} }
if (intCode & 1) { //Bit 0 of intCode if (intCode & 1) { //Bit 0 of intCode
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} }
if (intCode >> 1 & 1) { //Bit 1 of intCode if (intCode >> 1 & 1) { //Bit 1 of intCode
strReturn.append(B1); strReturn.append(B1);
strComplement.append(B0); strComplement.append(B0);
} else { } else {
strReturn.append(B0); strReturn.append(B0);
strComplement.append(B1); strComplement.append(B1);
} }
for( int i = 0; i < 3; ++i ) { for( int i = 0; i < 3; ++i ) {
strReturn.append( B0 ); strReturn.append( B0 );
strComplement.append( B1 ); strComplement.append( B1 );
} }
strReturn.append( strComplement ); strReturn.append( strComplement );
strReturn.append( reinterpret_cast<const char*>(STOP_CODE) ); strReturn.append( reinterpret_cast<const char*>(STOP_CODE) );
strReturn.append("+"); strReturn.append("+");
return strReturn; return strReturn;
} }
std::string ProtocolX10::decodeData(ControllerMessage& dataMsg) { std::string ProtocolX10::decodeData(ControllerMessage& dataMsg) {
int intData = 0, currentBit = 31; int intData = 0, currentBit = 31;
bool method=0; bool method=0;
sscanf(dataMsg.getParameter("data").c_str(), "%X", &intData); sscanf(dataMsg.getParameter("data").c_str(), "%X", &intData);
int unit = 0; int unit = 0;
int rawHouse = 0; int rawHouse = 0;
for(int i = 0; i < 4; ++i) { for(int i = 0; i < 4; ++i) {
rawHouse >>= 1; rawHouse >>= 1;
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
rawHouse |= 0x8; rawHouse |= 0x8;
} }
} }
if (checkBit(intData, currentBit--) != 0) { if (checkBit(intData, currentBit--) != 0) {
return ""; return "";
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
unit |= (1<<3); unit |= (1<<3);
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
return ""; return "";
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
return ""; return "";
} }
currentBit = 14; currentBit = 14;
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
unit |= (1<<2); unit |= (1<<2);
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
method = 1; method = 1;
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
unit |= (1<<0); unit |= (1<<0);
} }
if (checkBit(intData, currentBit--)) { if (checkBit(intData, currentBit--)) {
unit |= (1<<1); unit |= (1<<1);
} }
int intHouse = 0; int intHouse = 0;
for(int i = 0; i < 16; ++i) { for(int i = 0; i < 16; ++i) {
if (HOUSES[i] == rawHouse) { if (HOUSES[i] == rawHouse) {
intHouse = i; intHouse = i;
break; break;
} }
} }
std::stringstream retString; std::stringstream retString;
retString << "class:command;protocol:x10;model:codeswitch;"; retString << "class:command;protocol:x10;model:codeswitch;";
retString << "house:" << (char)('A' + intHouse); retString << "house:" << (char)('A' + intHouse);
retString << ";unit:" << unit+1; retString << ";unit:" << unit+1;
retString << ";method:"; retString << ";method:";
if(method == 0){ if(method == 0){
retString << "turnon;"; retString << "turnon;";
} else { } else {
retString << "turnoff;"; retString << "turnoff;";
} }
return retString.str(); return retString.str();
} }

View file

@ -1,24 +1,24 @@
#include "ProtocolYidong.h" #include "ProtocolYidong.h"
std::string ProtocolYidong::getStringForMethod(int method, unsigned char, Controller *) { std::string ProtocolYidong::getStringForMethod(int method, unsigned char, Controller *) {
int intCode = this->getIntParameter(L"unit", 1, 4); int intCode = this->getIntParameter(L"unit", 1, 4);
std::wstring strCode = L"111"; std::wstring strCode = L"111";
switch(intCode) { switch(intCode) {
case 1: case 1:
strCode.append(L"0010"); strCode.append(L"0010");
break; break;
case 2: case 2:
strCode.append(L"0001"); strCode.append(L"0001");
break; break;
case 3: case 3:
strCode.append(L"0100"); strCode.append(L"0100");
break; break;
case 4: case 4:
strCode.append(L"1000"); strCode.append(L"1000");
break; break;
} }
strCode.append(L"110"); strCode.append(L"110");
return getStringForCode(strCode, method); return getStringForCode(strCode, method);
} }

View file

@ -1,272 +1,272 @@
#include "Settings.h" #include "Settings.h"
#include "Strings.h" #include "Strings.h"
#include <Windows.h> #include <Windows.h>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <vector> #include <vector>
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include "common.h" #include "common.h"
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
const int intMaxRegValueLength = 1000; const int intMaxRegValueLength = 1000;
class Settings::PrivateData { class Settings::PrivateData {
public: public:
HKEY rootKey; HKEY rootKey;
std::wstring strRegPath; std::wstring strRegPath;
std::wstring getNodePath(Settings::Node type); std::wstring getNodePath(Settings::Node type);
}; };
std::wstring Settings::PrivateData::getNodePath(Settings::Node type) { std::wstring Settings::PrivateData::getNodePath(Settings::Node type) {
if (type == Settings::Device) { if (type == Settings::Device) {
return L"SOFTWARE\\Telldus\\Devices\\"; return L"SOFTWARE\\Telldus\\Devices\\";
} else if (type == Settings::Controller) { } else if (type == Settings::Controller) {
return L"SOFTWARE\\Telldus\\Controllers\\"; return L"SOFTWARE\\Telldus\\Controllers\\";
} }
return L""; return L"";
} }
/* /*
* Constructor * Constructor
*/ */
Settings::Settings(void) { Settings::Settings(void) {
d = new PrivateData(); d = new PrivateData();
d->strRegPath = L"SOFTWARE\\Telldus\\"; d->strRegPath = L"SOFTWARE\\Telldus\\";
d->rootKey = HKEY_LOCAL_MACHINE; d->rootKey = HKEY_LOCAL_MACHINE;
} }
/* /*
* Destructor * Destructor
*/ */
Settings::~Settings(void) { Settings::~Settings(void) {
delete d; delete d;
} }
/* /*
* Return the number of stored devices * Return the number of stored devices
*/ */
int Settings::getNumberOfNodes(Node type) const { int Settings::getNumberOfNodes(Node type) const {
TelldusCore::MutexLocker locker(&mutex); TelldusCore::MutexLocker locker(&mutex);
int intNumberOfNodes = 0; int intNumberOfNodes = 0;
HKEY hk; HKEY hk;
long lnExists = RegOpenKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, KEY_QUERY_VALUE, &hk); long lnExists = RegOpenKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, KEY_QUERY_VALUE, &hk);
if(lnExists == ERROR_SUCCESS){ if(lnExists == ERROR_SUCCESS){
std::wstring strNumSubKeys; std::wstring strNumSubKeys;
DWORD dNumSubKeys; DWORD dNumSubKeys;
RegQueryInfoKey(hk, NULL, NULL, NULL, &dNumSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL); RegQueryInfoKey(hk, NULL, NULL, NULL, &dNumSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
intNumberOfNodes = (int)dNumSubKeys; intNumberOfNodes = (int)dNumSubKeys;
RegCloseKey(hk); RegCloseKey(hk);
} }
return intNumberOfNodes; return intNumberOfNodes;
} }
int Settings::getNodeId(Node type, int intNodeIndex) const { int Settings::getNodeId(Node type, int intNodeIndex) const {
TelldusCore::MutexLocker locker(&mutex); TelldusCore::MutexLocker locker(&mutex);
int intReturn = -1; int intReturn = -1;
HKEY hk; HKEY hk;
long lnExists = RegOpenKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, KEY_READ, &hk); long lnExists = RegOpenKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, KEY_READ, &hk);
if(lnExists == ERROR_SUCCESS){ if(lnExists == ERROR_SUCCESS){
wchar_t* Buff = new wchar_t[intMaxRegValueLength]; wchar_t* Buff = new wchar_t[intMaxRegValueLength];
DWORD size = intMaxRegValueLength; DWORD size = intMaxRegValueLength;
if (RegEnumKeyEx(hk, intNodeIndex, (LPWSTR)Buff, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { if (RegEnumKeyEx(hk, intNodeIndex, (LPWSTR)Buff, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) {
intReturn = _wtoi(Buff); intReturn = _wtoi(Buff);
} }
delete[] Buff; delete[] Buff;
RegCloseKey(hk); RegCloseKey(hk);
} }
return intReturn; return intReturn;
} }
/* /*
* Add a new node * Add a new node
*/ */
int Settings::addNode(Node type) { int Settings::addNode(Node type) {
TelldusCore::MutexLocker locker(&mutex); TelldusCore::MutexLocker locker(&mutex);
int intNodeId = -1; int intNodeId = -1;
HKEY hk; HKEY hk;
DWORD dwDisp; DWORD dwDisp;
intNodeId = getNextNodeId(type); intNodeId = getNextNodeId(type);
std::wstring strCompleteRegPath = d->getNodePath(type); std::wstring strCompleteRegPath = d->getNodePath(type);
strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId)); strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId));
if (RegCreateKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, &dwDisp)) { if (RegCreateKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, &dwDisp)) {
//fail //fail
intNodeId = -1; intNodeId = -1;
} }
RegCloseKey(hk); RegCloseKey(hk);
return intNodeId; return intNodeId;
} }
/* /*
* Get next available device id * Get next available device id
*/ */
int Settings::getNextNodeId(Node type) const { int Settings::getNextNodeId(Node type) const {
//Private, no locks needed //Private, no locks needed
int intReturn = -1; int intReturn = -1;
HKEY hk; HKEY hk;
DWORD dwDisp; DWORD dwDisp;
long lnExists = RegCreateKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, &dwDisp); //create or open if already created long lnExists = RegCreateKeyEx(d->rootKey, d->getNodePath(type).c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hk, &dwDisp); //create or open if already created
if(lnExists == ERROR_SUCCESS){ if(lnExists == ERROR_SUCCESS){
DWORD dwLength = sizeof(DWORD); DWORD dwLength = sizeof(DWORD);
DWORD nResult(0); DWORD nResult(0);
long lngStatus = RegQueryValueEx(hk, L"LastUsedId", NULL, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwLength); long lngStatus = RegQueryValueEx(hk, L"LastUsedId", NULL, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwLength);
if(lngStatus == ERROR_SUCCESS){ if(lngStatus == ERROR_SUCCESS){
intReturn = nResult + 1; intReturn = nResult + 1;
} else { } else {
intReturn = 1; intReturn = 1;
} }
DWORD dwVal = intReturn; DWORD dwVal = intReturn;
RegSetValueEx (hk, L"LastUsedId", 0L, REG_DWORD, (CONST BYTE*) &dwVal, sizeof(DWORD)); RegSetValueEx (hk, L"LastUsedId", 0L, REG_DWORD, (CONST BYTE*) &dwVal, sizeof(DWORD));
} }
RegCloseKey(hk); RegCloseKey(hk);
return intReturn; return intReturn;
} }
/* /*
* Remove a device * Remove a device
*/ */
int Settings::removeNode(Node type, int intNodeId) { int Settings::removeNode(Node type, int intNodeId) {
TelldusCore::MutexLocker locker(&mutex); TelldusCore::MutexLocker locker(&mutex);
std::wstring strCompleteRegPath = d->getNodePath(type); std::wstring strCompleteRegPath = d->getNodePath(type);
strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId)); strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId));
long lngSuccess = RegDeleteKey(d->rootKey, strCompleteRegPath.c_str()); long lngSuccess = RegDeleteKey(d->rootKey, strCompleteRegPath.c_str());
if(lngSuccess == ERROR_SUCCESS){ if(lngSuccess == ERROR_SUCCESS){
//one of the deletions succeeded //one of the deletions succeeded
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
return TELLSTICK_ERROR_UNKNOWN; return TELLSTICK_ERROR_UNKNOWN;
} }
std::wstring Settings::getSetting(const std::wstring &strName) const{ std::wstring Settings::getSetting(const std::wstring &strName) const{
std::wstring strReturn; std::wstring strReturn;
HKEY hk; HKEY hk;
std::wstring strCompleteRegPath = d->strRegPath; std::wstring strCompleteRegPath = d->strRegPath;
long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk); long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk);
if(lnExists == ERROR_SUCCESS){ if(lnExists == ERROR_SUCCESS){
wchar_t* Buff = new wchar_t[intMaxRegValueLength]; wchar_t* Buff = new wchar_t[intMaxRegValueLength];
DWORD dwLength = sizeof(wchar_t)*intMaxRegValueLength; DWORD dwLength = sizeof(wchar_t)*intMaxRegValueLength;
long lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); long lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength);
if(lngStatus == ERROR_MORE_DATA){ if(lngStatus == ERROR_MORE_DATA){
//The buffer is to small, recreate it //The buffer is to small, recreate it
delete[] Buff; delete[] Buff;
Buff = new wchar_t[dwLength]; Buff = new wchar_t[dwLength];
lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); lngStatus = RegQueryValueEx(hk, strName.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength);
} }
if (lngStatus == ERROR_SUCCESS) { if (lngStatus == ERROR_SUCCESS) {
strReturn = Buff; strReturn = Buff;
} }
delete[] Buff; delete[] Buff;
} }
RegCloseKey(hk); RegCloseKey(hk);
return strReturn; return strReturn;
} }
std::wstring Settings::getStringSetting(Node type, int intNodeId, const std::wstring &name, bool parameter) const { std::wstring Settings::getStringSetting(Node type, int intNodeId, const std::wstring &name, bool parameter) const {
std::wstring strReturn; std::wstring strReturn;
HKEY hk; HKEY hk;
std::wstring strCompleteRegPath = d->getNodePath(type); std::wstring strCompleteRegPath = d->getNodePath(type);
strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId)); strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId));
long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk); long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_QUERY_VALUE, &hk);
if(lnExists == ERROR_SUCCESS){ if(lnExists == ERROR_SUCCESS){
wchar_t* Buff = new wchar_t[intMaxRegValueLength]; wchar_t* Buff = new wchar_t[intMaxRegValueLength];
DWORD dwLength = sizeof(wchar_t)*intMaxRegValueLength; DWORD dwLength = sizeof(wchar_t)*intMaxRegValueLength;
long lngStatus = RegQueryValueEx(hk, name.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); long lngStatus = RegQueryValueEx(hk, name.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength);
if(lngStatus == ERROR_MORE_DATA){ if(lngStatus == ERROR_MORE_DATA){
//The buffer is to small, recreate it //The buffer is to small, recreate it
delete[] Buff; delete[] Buff;
Buff = new wchar_t[dwLength]; Buff = new wchar_t[dwLength];
lngStatus = RegQueryValueEx(hk, name.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength); lngStatus = RegQueryValueEx(hk, name.c_str(), NULL, NULL, (LPBYTE)Buff, &dwLength);
} }
if (lngStatus == ERROR_SUCCESS) { if (lngStatus == ERROR_SUCCESS) {
strReturn = Buff; strReturn = Buff;
} }
delete[] Buff; delete[] Buff;
} }
RegCloseKey(hk); RegCloseKey(hk);
return strReturn; return strReturn;
} }
int Settings::setStringSetting(Node type, int intNodeId, const std::wstring &name, const std::wstring &value, bool parameter) { int Settings::setStringSetting(Node type, int intNodeId, const std::wstring &name, const std::wstring &value, bool parameter) {
HKEY hk; HKEY hk;
int ret = TELLSTICK_SUCCESS; int ret = TELLSTICK_SUCCESS;
std::wstring strNodeId = TelldusCore::intToWstring(intNodeId); std::wstring strNodeId = TelldusCore::intToWstring(intNodeId);
std::wstring strCompleteRegPath = d->getNodePath(type); std::wstring strCompleteRegPath = d->getNodePath(type);
strCompleteRegPath.append(strNodeId); strCompleteRegPath.append(strNodeId);
long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk); long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk);
if (lnExists == ERROR_SUCCESS){ if (lnExists == ERROR_SUCCESS){
int length = (int)value.length() * sizeof(wchar_t); int length = (int)value.length() * sizeof(wchar_t);
RegSetValueEx(hk, name.c_str(), 0, REG_SZ, (LPBYTE)value.c_str(), length+1); RegSetValueEx(hk, name.c_str(), 0, REG_SZ, (LPBYTE)value.c_str(), length+1);
} else { } else {
ret = TELLSTICK_ERROR_UNKNOWN; ret = TELLSTICK_ERROR_UNKNOWN;
} }
RegCloseKey(hk); RegCloseKey(hk);
return ret; return ret;
} }
int Settings::getIntSetting(Node type, int intNodeId, const std::wstring &name, bool parameter) const { int Settings::getIntSetting(Node type, int intNodeId, const std::wstring &name, bool parameter) const {
int intReturn = 0; int intReturn = 0;
std::wstring strSetting = getStringSetting(type, intNodeId, name, parameter); std::wstring strSetting = getStringSetting(type, intNodeId, name, parameter);
if (strSetting.length()) { if (strSetting.length()) {
intReturn = (int)strSetting[0]; //TODO: do real conversion instead intReturn = (int)strSetting[0]; //TODO: do real conversion instead
} }
return intReturn; return intReturn;
} }
int Settings::setIntSetting(Node type, int intNodeId, const std::wstring &name, int value, bool parameter) { int Settings::setIntSetting(Node type, int intNodeId, const std::wstring &name, int value, bool parameter) {
int intReturn = TELLSTICK_ERROR_UNKNOWN; int intReturn = TELLSTICK_ERROR_UNKNOWN;
HKEY hk; HKEY hk;
std::wstring strCompleteRegPath = d->getNodePath(type); std::wstring strCompleteRegPath = d->getNodePath(type);
strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId)); strCompleteRegPath.append(TelldusCore::intToWstring(intNodeId));
long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk); long lnExists = RegOpenKeyEx(d->rootKey, strCompleteRegPath.c_str(), 0, KEY_WRITE, &hk);
if (lnExists == ERROR_SUCCESS) { if (lnExists == ERROR_SUCCESS) {
DWORD dwVal = value; DWORD dwVal = value;
lnExists = RegSetValueEx (hk, name.c_str(), 0L, REG_DWORD, (CONST BYTE*) &dwVal, sizeof(DWORD)); lnExists = RegSetValueEx (hk, name.c_str(), 0L, REG_DWORD, (CONST BYTE*) &dwVal, sizeof(DWORD));
if (lnExists == ERROR_SUCCESS) { if (lnExists == ERROR_SUCCESS) {
intReturn = TELLSTICK_SUCCESS; intReturn = TELLSTICK_SUCCESS;
} }
} }
RegCloseKey(hk); RegCloseKey(hk);
return intReturn; return intReturn;
} }

View file

@ -55,8 +55,8 @@ TellStick::TellStick(int controllerId, TelldusCore::EventRef event, TelldusCore:
d->vid = td.vid; d->vid = td.vid;
d->pid = td.pid; d->pid = td.pid;
d->serial = td.serial; d->serial = td.serial;
Settings set; Settings set;
d->ignoreControllerConfirmation = set.getSetting(L"ignoreControllerConfirmation")==L"true"; d->ignoreControllerConfirmation = set.getSetting(L"ignoreControllerConfirmation")==L"true";
char *tempSerial = new char[td.serial.size()+1]; char *tempSerial = new char[td.serial.size()+1];
#ifdef _WINDOWS #ifdef _WINDOWS
@ -112,13 +112,13 @@ int TellStick::pid() const {
return d->pid; return d->pid;
} }
int TellStick::vid() const { int TellStick::vid() const {
return d->vid; return d->vid;
} }
std::string TellStick::serial() const { std::string TellStick::serial() const {
return d->serial; return d->serial;
} }
bool TellStick::isOpen() const { bool TellStick::isOpen() const {
return d->open; return d->open;
@ -146,8 +146,8 @@ void TellStick::processData( const std::string &data ) {
setFirmwareVersion(TelldusCore::charToInteger(d->message.substr(2).c_str())); setFirmwareVersion(TelldusCore::charToInteger(d->message.substr(2).c_str()));
} else if (d->message.substr(0,2).compare("+R") == 0) { } else if (d->message.substr(0,2).compare("+R") == 0) {
this->publishData(d->message.substr(2)); this->publishData(d->message.substr(2));
} else if(d->message.substr(0,2).compare("+W") == 0) { } else if(d->message.substr(0,2).compare("+W") == 0) {
this->decodePublishData(d->message.substr(2)); this->decodePublishData(d->message.substr(2));
} }
d->message.clear(); d->message.clear();
} else { // Append the character } else { // Append the character
@ -156,16 +156,16 @@ void TellStick::processData( const std::string &data ) {
} }
} }
int TellStick::reset(){ int TellStick::reset(){
#ifndef _WINDOWS #ifndef _WINDOWS
return TELLSTICK_SUCCESS; //nothing to be done on other platforms return TELLSTICK_SUCCESS; //nothing to be done on other platforms
#else #else
int success = FT_CyclePort( d->ftHandle ); int success = FT_CyclePort( d->ftHandle );
if(success == FT_OK){ if(success == FT_OK){
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
return TELLSTICK_ERROR_UNKNOWN; return TELLSTICK_ERROR_UNKNOWN;
#endif #endif
} }
void TellStick::run() { void TellStick::run() {
@ -228,20 +228,20 @@ int TellStick::send( const std::string &strMessage ) {
FT_STATUS ftStatus; FT_STATUS ftStatus;
ftStatus = FT_Write(d->ftHandle, tempMessage, (DWORD)strMessage.length(), &bytesWritten); ftStatus = FT_Write(d->ftHandle, tempMessage, (DWORD)strMessage.length(), &bytesWritten);
free(tempMessage); free(tempMessage);
if(ftStatus != FT_OK){ if(ftStatus != FT_OK){
Log::debug("Broken pipe on send"); Log::debug("Broken pipe on send");
return TELLSTICK_ERROR_BROKEN_PIPE; return TELLSTICK_ERROR_BROKEN_PIPE;
}
if(strMessage.compare("N+") == 0 && ((pid() == 0x0C31 && firmwareVersion() < 5) || (pid() == 0x0C30 && firmwareVersion() < 6))){
//these firmware versions doesn't implement ack to noop, just check that the noop can be sent correctly
return TELLSTICK_SUCCESS;
} }
if(d->ignoreControllerConfirmation){
//wait for TellStick to finish its air-sending if(strMessage.compare("N+") == 0 && ((pid() == 0x0C31 && firmwareVersion() < 5) || (pid() == 0x0C30 && firmwareVersion() < 6))){
msleep(1000); //these firmware versions doesn't implement ack to noop, just check that the noop can be sent correctly
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
}
if(d->ignoreControllerConfirmation){
//wait for TellStick to finish its air-sending
msleep(1000);
return TELLSTICK_SUCCESS;
} }
while(1) { while(1) {
@ -257,7 +257,7 @@ int TellStick::send( const std::string &strMessage ) {
return TELLSTICK_ERROR_COMMUNICATION; return TELLSTICK_ERROR_COMMUNICATION;
} }
} else { //Error } else { //Error
Log::debug("Broken pipe on read"); Log::debug("Broken pipe on read");
return TELLSTICK_ERROR_BROKEN_PIPE; return TELLSTICK_ERROR_BROKEN_PIPE;
} }
} }

View file

@ -1,142 +1,142 @@
#include "TelldusMain.h" #include "TelldusMain.h"
#include "ConnectionListener.h" #include "ConnectionListener.h"
#include "EventHandler.h" #include "EventHandler.h"
#include "ClientCommunicationHandler.h" #include "ClientCommunicationHandler.h"
#include "DeviceManager.h" #include "DeviceManager.h"
#include "ControllerManager.h" #include "ControllerManager.h"
#include "ControllerListener.h" #include "ControllerListener.h"
#include "EventUpdateManager.h" #include "EventUpdateManager.h"
#include "Timer.h" #include "Timer.h"
#include "Log.h" #include "Log.h"
#include <stdio.h> #include <stdio.h>
#include <list> #include <list>
#include <memory> #include <memory>
class TelldusMain::PrivateData { class TelldusMain::PrivateData {
public: public:
TelldusCore::EventHandler eventHandler; TelldusCore::EventHandler eventHandler;
TelldusCore::EventRef stopEvent, controllerChangeEvent; TelldusCore::EventRef stopEvent, controllerChangeEvent;
}; };
TelldusMain::TelldusMain(void) TelldusMain::TelldusMain(void)
{ {
d = new PrivateData; d = new PrivateData;
d->stopEvent = d->eventHandler.addEvent(); d->stopEvent = d->eventHandler.addEvent();
d->controllerChangeEvent = d->eventHandler.addEvent(); d->controllerChangeEvent = d->eventHandler.addEvent();
} }
TelldusMain::~TelldusMain(void) { TelldusMain::~TelldusMain(void) {
delete d; delete d;
} }
void TelldusMain::deviceInsertedOrRemoved(int vid, int pid, bool inserted) { void TelldusMain::deviceInsertedOrRemoved(int vid, int pid, bool inserted) {
ControllerChangeEventData *data = new ControllerChangeEventData; ControllerChangeEventData *data = new ControllerChangeEventData;
data->vid = vid; data->vid = vid;
data->pid = pid; data->pid = pid;
data->inserted = inserted; data->inserted = inserted;
d->controllerChangeEvent->signal(data); d->controllerChangeEvent->signal(data);
} }
void TelldusMain::resume() { void TelldusMain::resume() {
Log::notice("Came back from suspend"); Log::notice("Came back from suspend");
ControllerChangeEventData *data = new ControllerChangeEventData; ControllerChangeEventData *data = new ControllerChangeEventData;
data->vid = 0x0; data->vid = 0x0;
data->pid = 0x0; data->pid = 0x0;
data->inserted = true; data->inserted = true;
d->controllerChangeEvent->signal(data); d->controllerChangeEvent->signal(data);
} }
void TelldusMain::suspend() { void TelldusMain::suspend() {
Log::notice("Preparing for suspend"); Log::notice("Preparing for suspend");
ControllerChangeEventData *data = new ControllerChangeEventData; ControllerChangeEventData *data = new ControllerChangeEventData;
data->vid = 0x0; data->vid = 0x0;
data->pid = 0x0; data->pid = 0x0;
data->inserted = false; data->inserted = false;
d->controllerChangeEvent->signal(data); d->controllerChangeEvent->signal(data);
} }
void TelldusMain::start(void) { void TelldusMain::start(void) {
TelldusCore::EventRef clientEvent = d->eventHandler.addEvent(); TelldusCore::EventRef clientEvent = d->eventHandler.addEvent();
TelldusCore::EventRef dataEvent = d->eventHandler.addEvent(); TelldusCore::EventRef dataEvent = d->eventHandler.addEvent();
TelldusCore::EventRef janitor = d->eventHandler.addEvent(); //Used for regular cleanups TelldusCore::EventRef janitor = d->eventHandler.addEvent(); //Used for regular cleanups
Timer supervisor(janitor); //Tells the janitor to go back to work Timer supervisor(janitor); //Tells the janitor to go back to work
supervisor.setInterval(60); //Once every minute supervisor.setInterval(60); //Once every minute
supervisor.start(); supervisor.start();
EventUpdateManager eventUpdateManager; EventUpdateManager eventUpdateManager;
TelldusCore::EventRef deviceUpdateEvent = eventUpdateManager.retrieveUpdateEvent(); TelldusCore::EventRef deviceUpdateEvent = eventUpdateManager.retrieveUpdateEvent();
eventUpdateManager.start(); eventUpdateManager.start();
ControllerManager controllerManager(dataEvent, deviceUpdateEvent); ControllerManager controllerManager(dataEvent, deviceUpdateEvent);
DeviceManager deviceManager(&controllerManager, deviceUpdateEvent); DeviceManager deviceManager(&controllerManager, deviceUpdateEvent);
ConnectionListener clientListener(L"TelldusClient", clientEvent); ConnectionListener clientListener(L"TelldusClient", clientEvent);
std::list<ClientCommunicationHandler *> clientCommunicationHandlerList; std::list<ClientCommunicationHandler *> clientCommunicationHandlerList;
TelldusCore::EventRef handlerEvent = d->eventHandler.addEvent(); TelldusCore::EventRef handlerEvent = d->eventHandler.addEvent();
#ifdef _MACOSX #ifdef _MACOSX
//This is only needed on OS X //This is only needed on OS X
ControllerListener controllerListener(d->controllerChangeEvent); ControllerListener controllerListener(d->controllerChangeEvent);
#endif #endif
while(!d->stopEvent->isSignaled()) { while(!d->stopEvent->isSignaled()) {
if (!d->eventHandler.waitForAny()) { if (!d->eventHandler.waitForAny()) {
continue; continue;
} }
if (clientEvent->isSignaled()) { if (clientEvent->isSignaled()) {
//New client connection //New client connection
TelldusCore::EventDataRef eventDataRef = clientEvent->takeSignal(); TelldusCore::EventDataRef eventDataRef = clientEvent->takeSignal();
ConnectionListenerEventData *data = reinterpret_cast<ConnectionListenerEventData*>(eventDataRef.get()); ConnectionListenerEventData *data = reinterpret_cast<ConnectionListenerEventData*>(eventDataRef.get());
if (data) { if (data) {
ClientCommunicationHandler *clientCommunication = new ClientCommunicationHandler(data->socket, handlerEvent, &deviceManager, deviceUpdateEvent, &controllerManager); ClientCommunicationHandler *clientCommunication = new ClientCommunicationHandler(data->socket, handlerEvent, &deviceManager, deviceUpdateEvent, &controllerManager);
clientCommunication->start(); clientCommunication->start();
clientCommunicationHandlerList.push_back(clientCommunication); clientCommunicationHandlerList.push_back(clientCommunication);
} }
} }
if (d->controllerChangeEvent->isSignaled()) { if (d->controllerChangeEvent->isSignaled()) {
TelldusCore::EventDataRef eventDataRef = d->controllerChangeEvent->takeSignal(); TelldusCore::EventDataRef eventDataRef = d->controllerChangeEvent->takeSignal();
ControllerChangeEventData *data = reinterpret_cast<ControllerChangeEventData*>(eventDataRef.get()); ControllerChangeEventData *data = reinterpret_cast<ControllerChangeEventData*>(eventDataRef.get());
if (data) { if (data) {
controllerManager.deviceInsertedOrRemoved(data->vid, data->pid, "", data->inserted); controllerManager.deviceInsertedOrRemoved(data->vid, data->pid, "", data->inserted);
} }
} }
if (dataEvent->isSignaled()) { if (dataEvent->isSignaled()) {
TelldusCore::EventDataRef eventData = dataEvent->takeSignal(); TelldusCore::EventDataRef eventData = dataEvent->takeSignal();
ControllerEventData *data = reinterpret_cast<ControllerEventData*>(eventData.get()); ControllerEventData *data = reinterpret_cast<ControllerEventData*>(eventData.get());
if (data) { if (data) {
deviceManager.handleControllerMessage(*data); deviceManager.handleControllerMessage(*data);
} }
} }
if (handlerEvent->isSignaled()) { if (handlerEvent->isSignaled()) {
handlerEvent->popSignal(); handlerEvent->popSignal();
for ( std::list<ClientCommunicationHandler *>::iterator it = clientCommunicationHandlerList.begin(); it != clientCommunicationHandlerList.end(); ){ for ( std::list<ClientCommunicationHandler *>::iterator it = clientCommunicationHandlerList.begin(); it != clientCommunicationHandlerList.end(); ){
if ((*it)->isDone()){ if ((*it)->isDone()){
delete *it; delete *it;
it = clientCommunicationHandlerList.erase(it); it = clientCommunicationHandlerList.erase(it);
} else { } else {
++it; ++it;
} }
} }
} }
if (janitor->isSignaled()) { if (janitor->isSignaled()) {
//Clear all of them if there is more than one //Clear all of them if there is more than one
while(janitor->isSignaled()) { while(janitor->isSignaled()) {
janitor->popSignal(); janitor->popSignal();
} }
controllerManager.queryControllerStatus(); controllerManager.queryControllerStatus();
} }
} }
supervisor.stop(); supervisor.stop();
} }
void TelldusMain::stop(void){ void TelldusMain::stop(void){
d->stopEvent->signal(); d->stopEvent->signal();
} }

View file

@ -1,23 +1,23 @@
#ifndef TELLDUSMAIN_H #ifndef TELLDUSMAIN_H
#define TELLDUSMAIN_H #define TELLDUSMAIN_H
class TelldusMain class TelldusMain
{ {
public: public:
TelldusMain(void); TelldusMain(void);
~TelldusMain(void); ~TelldusMain(void);
void start(); void start();
void stop(); void stop();
//Thread safe! //Thread safe!
void deviceInsertedOrRemoved(int vid, int pid, bool inserted); void deviceInsertedOrRemoved(int vid, int pid, bool inserted);
void resume(); void resume();
void suspend(); void suspend();
private: private:
class PrivateData; class PrivateData;
PrivateData *d; PrivateData *d;
}; };
#endif //TELLDUSMAIN_H #endif //TELLDUSMAIN_H

View file

@ -1,177 +1,177 @@
#include "TelldusWinService_win.h" #include "TelldusWinService_win.h"
#include "TelldusMain.h" #include "TelldusMain.h"
#include "Log.h" #include "Log.h"
#include <Dbt.h> #include <Dbt.h>
#include <string> #include <string>
#include <algorithm> #include <algorithm>
int g_argc; int g_argc;
char **g_argv; char **g_argv;
static const GUID GUID_DEVINTERFACE_USBRAW = static const GUID GUID_DEVINTERFACE_USBRAW =
{ 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } }; { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
TelldusWinService::TelldusWinService() TelldusWinService::TelldusWinService()
:tm(0) :tm(0)
{ {
tm = new TelldusMain(); tm = new TelldusMain();
} }
TelldusWinService::~TelldusWinService() { TelldusWinService::~TelldusWinService() {
delete tm; delete tm;
} }
void TelldusWinService::stop() { void TelldusWinService::stop() {
tm->stop(); tm->stop();
} }
DWORD WINAPI TelldusWinService::serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ) { DWORD WINAPI TelldusWinService::serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ) {
switch ( controlCode ) { switch ( controlCode ) {
case SERVICE_CONTROL_INTERROGATE: case SERVICE_CONTROL_INTERROGATE:
SetServiceStatus( serviceStatusHandle, &serviceStatus ); SetServiceStatus( serviceStatusHandle, &serviceStatus );
return NO_ERROR; return NO_ERROR;
case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_STOP:
stop(); stop();
serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus( serviceStatusHandle, &serviceStatus ); SetServiceStatus( serviceStatusHandle, &serviceStatus );
return NO_ERROR; return NO_ERROR;
case SERVICE_CONTROL_POWEREVENT: case SERVICE_CONTROL_POWEREVENT:
if (dwEventType == PBT_APMSUSPEND) { if (dwEventType == PBT_APMSUSPEND) {
tm->suspend(); tm->suspend();
} else if (dwEventType == PBT_APMRESUMEAUTOMATIC) { } else if (dwEventType == PBT_APMRESUMEAUTOMATIC) {
tm->resume(); tm->resume();
} }
return NO_ERROR; return NO_ERROR;
} }
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
DWORD WINAPI TelldusWinService::deviceNotificationHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ) { DWORD WINAPI TelldusWinService::deviceNotificationHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ) {
if (controlCode != SERVICE_CONTROL_DEVICEEVENT) { if (controlCode != SERVICE_CONTROL_DEVICEEVENT) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
if (dwEventType != DBT_DEVICEARRIVAL && dwEventType != DBT_DEVICEREMOVECOMPLETE) { if (dwEventType != DBT_DEVICEARRIVAL && dwEventType != DBT_DEVICEREMOVECOMPLETE) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(lpEventData); PDEV_BROADCAST_DEVICEINTERFACE pDevInf = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE>(lpEventData);
if (!pDevInf) { if (!pDevInf) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
std::wstring name(pDevInf->dbcc_name); std::wstring name(pDevInf->dbcc_name);
transform(name.begin(), name.end(), name.begin(), toupper); transform(name.begin(), name.end(), name.begin(), toupper);
//Parse VID //Parse VID
size_t posStart = name.find(L"VID_"); size_t posStart = name.find(L"VID_");
if (posStart == std::wstring::npos) { if (posStart == std::wstring::npos) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
posStart += 4; posStart += 4;
size_t posEnd = name.find(L'&', posStart); size_t posEnd = name.find(L'&', posStart);
if (posEnd == std::wstring::npos) { if (posEnd == std::wstring::npos) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
std::wstring strVID = name.substr(posStart, posEnd-posStart); std::wstring strVID = name.substr(posStart, posEnd-posStart);
//Parse PID //Parse PID
posStart = name.find(L"PID_"); posStart = name.find(L"PID_");
if (posStart == std::wstring::npos) { if (posStart == std::wstring::npos) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
posStart += 4; posStart += 4;
posEnd = name.find(L'#', posStart); posEnd = name.find(L'#', posStart);
if (posEnd == std::wstring::npos) { if (posEnd == std::wstring::npos) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
std::wstring strPID = name.substr(posStart, posEnd-posStart); std::wstring strPID = name.substr(posStart, posEnd-posStart);
long int vid = strtol(std::string(strVID.begin(), strVID.end()).c_str(), NULL, 16); long int vid = strtol(std::string(strVID.begin(), strVID.end()).c_str(), NULL, 16);
long int pid = strtol(std::string(strPID.begin(), strPID.end()).c_str(), NULL, 16); long int pid = strtol(std::string(strPID.begin(), strPID.end()).c_str(), NULL, 16);
if (dwEventType == DBT_DEVICEARRIVAL) { if (dwEventType == DBT_DEVICEARRIVAL) {
tm->deviceInsertedOrRemoved(vid, pid, true); tm->deviceInsertedOrRemoved(vid, pid, true);
} else { } else {
tm->deviceInsertedOrRemoved(vid, pid, false); tm->deviceInsertedOrRemoved(vid, pid, false);
} }
return NO_ERROR; return NO_ERROR;
} }
DWORD WINAPI TelldusWinService::serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext ) { DWORD WINAPI TelldusWinService::serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext ) {
TelldusWinService *instance = reinterpret_cast<TelldusWinService *>(lpContext); TelldusWinService *instance = reinterpret_cast<TelldusWinService *>(lpContext);
if (!instance) { if (!instance) {
return ERROR_CALL_NOT_IMPLEMENTED; return ERROR_CALL_NOT_IMPLEMENTED;
} }
if (controlCode == SERVICE_CONTROL_DEVICEEVENT) { if (controlCode == SERVICE_CONTROL_DEVICEEVENT) {
return instance->deviceNotificationHandler(controlCode, dwEventType, lpEventData); return instance->deviceNotificationHandler(controlCode, dwEventType, lpEventData);
} }
return instance->serviceControlHandler(controlCode, dwEventType, lpEventData); return instance->serviceControlHandler(controlCode, dwEventType, lpEventData);
} }
void WINAPI TelldusWinService::serviceMain( DWORD argc, TCHAR* argv[] ) { void WINAPI TelldusWinService::serviceMain( DWORD argc, TCHAR* argv[] ) {
TelldusWinService instance; TelldusWinService instance;
//Enable debug if we hade this supplied //Enable debug if we hade this supplied
for(unsigned int i = 1; i < argc; ++i) { for(unsigned int i = 1; i < argc; ++i) {
if (wcscmp(argv[i], L"--debug") == 0) { if (wcscmp(argv[i], L"--debug") == 0) {
Log::setDebug(); Log::setDebug();
} }
} }
// initialise service status // initialise service status
instance.serviceStatus.dwServiceType = SERVICE_WIN32; instance.serviceStatus.dwServiceType = SERVICE_WIN32;
instance.serviceStatus.dwCurrentState = SERVICE_STOPPED; instance.serviceStatus.dwCurrentState = SERVICE_STOPPED;
instance.serviceStatus.dwControlsAccepted = 0; instance.serviceStatus.dwControlsAccepted = 0;
instance.serviceStatus.dwWin32ExitCode = NO_ERROR; instance.serviceStatus.dwWin32ExitCode = NO_ERROR;
instance.serviceStatus.dwServiceSpecificExitCode = NO_ERROR; instance.serviceStatus.dwServiceSpecificExitCode = NO_ERROR;
instance.serviceStatus.dwCheckPoint = 0; instance.serviceStatus.dwCheckPoint = 0;
instance.serviceStatus.dwWaitHint = 0; instance.serviceStatus.dwWaitHint = 0;
instance.serviceStatusHandle = RegisterServiceCtrlHandlerEx( serviceName, TelldusWinService::serviceControlHandler, &instance ); instance.serviceStatusHandle = RegisterServiceCtrlHandlerEx( serviceName, TelldusWinService::serviceControlHandler, &instance );
if ( instance.serviceStatusHandle ) { if ( instance.serviceStatusHandle ) {
// service is starting // service is starting
instance.serviceStatus.dwCurrentState = SERVICE_START_PENDING; instance.serviceStatus.dwCurrentState = SERVICE_START_PENDING;
SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus ); SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus );
// running // running
instance.serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); instance.serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);
// Register for power management notification // Register for power management notification
instance.serviceStatus.dwControlsAccepted |= SERVICE_ACCEPT_POWEREVENT; instance.serviceStatus.dwControlsAccepted |= SERVICE_ACCEPT_POWEREVENT;
instance.serviceStatus.dwCurrentState = SERVICE_RUNNING; instance.serviceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus ); SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus );
// Register for device notification // Register for device notification
DEV_BROADCAST_DEVICEINTERFACE devInterface; DEV_BROADCAST_DEVICEINTERFACE devInterface;
ZeroMemory( &devInterface, sizeof(devInterface) ); ZeroMemory( &devInterface, sizeof(devInterface) );
devInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); devInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
devInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devInterface.dbcc_classguid = GUID_DEVINTERFACE_USBRAW; devInterface.dbcc_classguid = GUID_DEVINTERFACE_USBRAW;
HDEVNOTIFY deviceNotificationHandle = RegisterDeviceNotificationW(instance.serviceStatusHandle, &devInterface, DEVICE_NOTIFY_SERVICE_HANDLE); HDEVNOTIFY deviceNotificationHandle = RegisterDeviceNotificationW(instance.serviceStatusHandle, &devInterface, DEVICE_NOTIFY_SERVICE_HANDLE);
Log::notice("TelldusService started"); Log::notice("TelldusService started");
//Start our main-loop //Start our main-loop
instance.tm->start(); instance.tm->start();
Log::notice("TelldusService stopping"); Log::notice("TelldusService stopping");
Log::destroy(); Log::destroy();
// service was stopped // service was stopped
instance.serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; instance.serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus ); SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus );
// service is now stopped // service is now stopped
instance.serviceStatus.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); instance.serviceStatus.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);
instance.serviceStatus.dwCurrentState = SERVICE_STOPPED; instance.serviceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus ); SetServiceStatus( instance.serviceStatusHandle, &instance.serviceStatus );
} }
} }

View file

@ -1,35 +1,35 @@
#ifndef TELLDUSSERVICE_WIN_H #ifndef TELLDUSSERVICE_WIN_H
#define TELLDUSSERVICE_WIN_H #define TELLDUSSERVICE_WIN_H
#include <windows.h> #include <windows.h>
extern int g_argc; extern int g_argc;
extern char **g_argv; extern char **g_argv;
class TelldusMain; class TelldusMain;
#define serviceName TEXT("TelldusCore") #define serviceName TEXT("TelldusCore")
class TelldusWinService { class TelldusWinService {
public: public:
TelldusWinService(); TelldusWinService();
~TelldusWinService(); ~TelldusWinService();
static void WINAPI serviceMain( DWORD /*argc*/, TCHAR* /*argv*/[] ); static void WINAPI serviceMain( DWORD /*argc*/, TCHAR* /*argv*/[] );
protected: protected:
void stop(); void stop();
DWORD WINAPI serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ); DWORD WINAPI serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData );
DWORD WINAPI deviceNotificationHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData ); DWORD WINAPI deviceNotificationHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData );
private: private:
TelldusMain *tm; TelldusMain *tm;
SERVICE_STATUS serviceStatus; SERVICE_STATUS serviceStatus;
SERVICE_STATUS_HANDLE serviceStatusHandle; SERVICE_STATUS_HANDLE serviceStatusHandle;
static DWORD WINAPI serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext ); static DWORD WINAPI serviceControlHandler( DWORD controlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext );
}; };
#endif TELLDUSSERVICE_WIN_H #endif TELLDUSSERVICE_WIN_H

View file

@ -1,114 +1,114 @@
#include "Timer.h" #include "Timer.h"
#include "Mutex.h" #include "Mutex.h"
#ifdef _WINDOWS #ifdef _WINDOWS
#else #else
#include <sys/time.h> #include <sys/time.h>
#include <errno.h> #include <errno.h>
#endif #endif
class Timer::PrivateData { class Timer::PrivateData {
public: public:
PrivateData() : interval(0), running(false) {} PrivateData() : interval(0), running(false) {}
TelldusCore::EventRef event; TelldusCore::EventRef event;
int interval; int interval;
bool running; bool running;
#ifdef _WINDOWS #ifdef _WINDOWS
HANDLE cond; HANDLE cond;
TelldusCore::Mutex mutex; TelldusCore::Mutex mutex;
#else #else
pthread_mutex_t waitMutex; pthread_mutex_t waitMutex;
pthread_cond_t cond; pthread_cond_t cond;
#endif #endif
}; };
Timer::Timer(TelldusCore::EventRef event) Timer::Timer(TelldusCore::EventRef event)
:TelldusCore::Thread(), d(new PrivateData) :TelldusCore::Thread(), d(new PrivateData)
{ {
d->event = event; d->event = event;
#ifdef _WINDOWS #ifdef _WINDOWS
d->cond = CreateEventW(NULL, false, false, NULL); d->cond = CreateEventW(NULL, false, false, NULL);
#else #else
pthread_cond_init(&d->cond, NULL); pthread_cond_init(&d->cond, NULL);
pthread_mutex_init(&d->waitMutex, NULL); pthread_mutex_init(&d->waitMutex, NULL);
#endif #endif
} }
Timer::~Timer() { Timer::~Timer() {
this->stop(); this->stop();
this->wait(); this->wait();
#ifdef _WINDOWS #ifdef _WINDOWS
#else #else
pthread_mutex_destroy(&d->waitMutex); pthread_mutex_destroy(&d->waitMutex);
pthread_cond_destroy(&d->cond); pthread_cond_destroy(&d->cond);
delete d; delete d;
#endif #endif
} }
void Timer::setInterval(int sec) { void Timer::setInterval(int sec) {
d->interval = sec; d->interval = sec;
} }
void Timer::stop() { void Timer::stop() {
#ifdef _WINDOWS #ifdef _WINDOWS
TelldusCore::MutexLocker(&d->mutex); TelldusCore::MutexLocker(&d->mutex);
d->running = false; d->running = false;
SetEvent(d->cond); SetEvent(d->cond);
#else #else
//Signal event //Signal event
pthread_mutex_lock(&d->waitMutex); pthread_mutex_lock(&d->waitMutex);
if (d->running) { if (d->running) {
d->running = false; d->running = false;
pthread_cond_signal(&d->cond); pthread_cond_signal(&d->cond);
} }
pthread_mutex_unlock(&d->waitMutex); pthread_mutex_unlock(&d->waitMutex);
#endif #endif
} }
void Timer::run() { void Timer::run() {
#ifdef _WINDOWS #ifdef _WINDOWS
int interval = 0; int interval = 0;
{ {
TelldusCore::MutexLocker(&d->mutex); TelldusCore::MutexLocker(&d->mutex);
d->running = true; d->running = true;
interval = d->interval*1000; interval = d->interval*1000;
} }
while(1) { while(1) {
DWORD retval = WaitForSingleObject(d->cond, interval); DWORD retval = WaitForSingleObject(d->cond, interval);
if (retval == WAIT_TIMEOUT) { if (retval == WAIT_TIMEOUT) {
d->event->signal(); d->event->signal();
} }
TelldusCore::MutexLocker(&d->mutex); TelldusCore::MutexLocker(&d->mutex);
if (!d->running) { if (!d->running) {
break; break;
} }
} }
#else #else
struct timespec ts; struct timespec ts;
struct timeval tp; struct timeval tp;
pthread_mutex_lock(&d->waitMutex); pthread_mutex_lock(&d->waitMutex);
d->running = true; d->running = true;
pthread_mutex_unlock(&d->waitMutex); pthread_mutex_unlock(&d->waitMutex);
while(1) { while(1) {
int rc = gettimeofday(&tp, NULL); int rc = gettimeofday(&tp, NULL);
ts.tv_sec = tp.tv_sec; ts.tv_sec = tp.tv_sec;
ts.tv_nsec = tp.tv_usec * 1000; ts.tv_nsec = tp.tv_usec * 1000;
ts.tv_sec += d->interval; ts.tv_sec += d->interval;
pthread_mutex_lock( &d->waitMutex ); pthread_mutex_lock( &d->waitMutex );
if (d->running) { if (d->running) {
rc = pthread_cond_timedwait(&d->cond, &d->waitMutex, &ts); rc = pthread_cond_timedwait(&d->cond, &d->waitMutex, &ts);
} else { } else {
pthread_mutex_unlock( &d->waitMutex ); pthread_mutex_unlock( &d->waitMutex );
break; break;
} }
pthread_mutex_unlock( &d->waitMutex ); pthread_mutex_unlock( &d->waitMutex );
if (rc == ETIMEDOUT) { if (rc == ETIMEDOUT) {
d->event->signal(); d->event->signal();
} }
} }
#endif #endif
} }

View file

@ -1,15 +1,15 @@
#ifdef LIBFTD2XX #ifdef LIBFTD2XX
#ifdef _WINDOWS #ifdef _WINDOWS
#include <windows.h> #include <windows.h>
#include "win\ftd2xx.h" #include "win\ftd2xx.h"
#else #else
#include "osx/WinTypes.h" #include "osx/WinTypes.h"
#include "osx/ftd2xx.h" #include "osx/ftd2xx.h"
#endif #endif
#endif #endif
#ifdef LIBFTDI #ifdef LIBFTDI
#include <ftdi.h> #include <ftdi.h>
#endif #endif

View file

@ -1,20 +1,20 @@
#include "TelldusWinService_win.h" #include "TelldusWinService_win.h"
//#include <QCoreApplication> //#include <QCoreApplication>
#include <windows.h> #include <windows.h>
#include <Dbt.h> #include <Dbt.h>
int main(int argc, char **argv) { int main(int argc, char **argv) {
g_argc = argc; g_argc = argc;
g_argv = argv; g_argv = argv;
SERVICE_TABLE_ENTRY serviceTable[] = { SERVICE_TABLE_ENTRY serviceTable[] = {
{serviceName, TelldusWinService::serviceMain }, {serviceName, TelldusWinService::serviceMain },
{ 0, 0 } { 0, 0 }
}; };
StartServiceCtrlDispatcher( serviceTable ); StartServiceCtrlDispatcher( serviceTable );
return 0; return 0;
} }

File diff suppressed because it is too large Load diff

View file

@ -1,79 +1,79 @@
PROJECT(tdadmin) PROJECT(tdadmin)
cmake_policy(SET CMP0005 NEW) cmake_policy(SET CMP0005 NEW)
SET (tdadmin_DESCRIPTION SET (tdadmin_DESCRIPTION
"a command line utility to edit devices and controllers for Telldus TellStick" "a command line utility to edit devices and controllers for Telldus TellStick"
) )
SET(tdadmin_SRCS SET(tdadmin_SRCS
main.cpp main.cpp
) )
ADD_EXECUTABLE(tdadmin ADD_EXECUTABLE(tdadmin
${tdadmin_SRCS} ${tdadmin_SRCS}
) )
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_SOURCE_DIR}/driver ${CMAKE_SOURCE_DIR}/driver
) )
ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" ) ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" )
IF (WIN32) IF (WIN32)
FIND_LIBRARY(TELLDUSCORE_LIBRARY TelldusCore) FIND_LIBRARY(TELLDUSCORE_LIBRARY TelldusCore)
TARGET_LINK_LIBRARIES(tdadmin TARGET_LINK_LIBRARIES(tdadmin
${TELLDUSCORE_LIBRARY} ${TELLDUSCORE_LIBRARY}
) )
ELSEIF (APPLE) ELSEIF (APPLE)
TARGET_LINK_LIBRARIES(tdadmin TARGET_LINK_LIBRARIES(tdadmin
TelldusCore TelldusCore
) )
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD") ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
# FreeBSD does not have argp in base libc; port devel/argp-standalone is required. # FreeBSD does not have argp in base libc; port devel/argp-standalone is required.
FIND_LIBRARY(ARGP_LIBRARY argp) FIND_LIBRARY(ARGP_LIBRARY argp)
TARGET_LINK_LIBRARIES(tdadmin TARGET_LINK_LIBRARIES(tdadmin
${CMAKE_BINARY_DIR}/client/libtelldus-core.so ${CMAKE_BINARY_DIR}/client/libtelldus-core.so
${ARGP_LIBRARY} ${ARGP_LIBRARY}
) )
ELSE (WIN32) ELSE (WIN32)
TARGET_LINK_LIBRARIES(tdadmin TARGET_LINK_LIBRARIES(tdadmin
${CMAKE_BINARY_DIR}/client/libtelldus-core.so ${CMAKE_BINARY_DIR}/client/libtelldus-core.so
) )
ENDIF (WIN32) ENDIF (WIN32)
IF (UNIX) IF (UNIX)
IF (GENERATE_MAN) IF (GENERATE_MAN)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET tdadmin TARGET tdadmin
POST_BUILD POST_BUILD
COMMAND help2man -n ${tdadmin_DESCRIPTION} ./tdadmin > tdadmin.1 COMMAND help2man -n ${tdadmin_DESCRIPTION} ./tdadmin > tdadmin.1
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating man file tdadmin.1" COMMENT "Generating man file tdadmin.1"
) )
INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/tdadmin.1 DESTINATION share/man/man1) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/tdadmin.1 DESTINATION share/man/man1)
ENDIF (GENERATE_MAN) ENDIF (GENERATE_MAN)
ENDIF (UNIX) ENDIF (UNIX)
INSTALL(TARGETS tdadmin RUNTIME DESTINATION sbin) INSTALL(TARGETS tdadmin RUNTIME DESTINATION sbin)
IF (UNIX AND NOT APPLE) IF (UNIX AND NOT APPLE)
SET(UDEV_RULES_DIR "/etc/udev/rules.d" CACHE PATH "The directory where udev store its rules" ) SET(UDEV_RULES_DIR "/etc/udev/rules.d" CACHE PATH "The directory where udev store its rules" )
CONFIGURE_FILE( CONFIGURE_FILE(
${CMAKE_CURRENT_SOURCE_DIR}/05-tellstick.rules ${CMAKE_CURRENT_SOURCE_DIR}/05-tellstick.rules
${CMAKE_BINARY_DIR}/parsed/05-tellstick.rules ${CMAKE_BINARY_DIR}/parsed/05-tellstick.rules
@ONLY @ONLY
) )
CONFIGURE_FILE( CONFIGURE_FILE(
${CMAKE_CURRENT_SOURCE_DIR}/udev.sh ${CMAKE_CURRENT_SOURCE_DIR}/udev.sh
${CMAKE_BINARY_DIR}/parsed/udev.sh ${CMAKE_BINARY_DIR}/parsed/udev.sh
@ONLY @ONLY
) )
INSTALL(FILES ${CMAKE_BINARY_DIR}/parsed/05-tellstick.rules INSTALL(FILES ${CMAKE_BINARY_DIR}/parsed/05-tellstick.rules
DESTINATION ${UDEV_RULES_DIR} DESTINATION ${UDEV_RULES_DIR}
) )
INSTALL(PROGRAMS ${CMAKE_BINARY_DIR}/parsed/udev.sh INSTALL(PROGRAMS ${CMAKE_BINARY_DIR}/parsed/udev.sh
DESTINATION share/telldus-core/helpers/ DESTINATION share/telldus-core/helpers/
) )
ENDIF (UNIX AND NOT APPLE) ENDIF (UNIX AND NOT APPLE)

View file

@ -1,85 +1,85 @@
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
#include <stdlib.h> #include <stdlib.h>
#include <errno.h> #include <errno.h>
#include <argp.h> #include <argp.h>
#include <string> #include <string>
const char *argp_program_version = "tdadmin " VERSION ; const char *argp_program_version = "tdadmin " VERSION ;
const char *argp_program_bug_address = "<info.tech@telldus.com>"; const char *argp_program_bug_address = "<info.tech@telldus.com>";
static char args_doc[] = "COMMAND ACTION"; static char args_doc[] = "COMMAND ACTION";
static char doc[] = "TellStick admin tool -- a command line utility to edit devices and controllers for Telldus TellStick"; static char doc[] = "TellStick admin tool -- a command line utility to edit devices and controllers for Telldus TellStick";
const int VID = 1; const int VID = 1;
const int PID = 2; const int PID = 2;
const int SERIAL = 3; const int SERIAL = 3;
static struct argp_option options[] = { static struct argp_option options[] = {
{0,0,0,0, {0,0,0,0,
"COMMAND: controller, ACTION: connect/disconnect\n" "COMMAND: controller, ACTION: connect/disconnect\n"
"Tells the daemon to add or remove a TellStick (duo)" "Tells the daemon to add or remove a TellStick (duo)"
}, },
{"vid",VID,"VID",0, "The vendor id (1781)" }, {"vid",VID,"VID",0, "The vendor id (1781)" },
{"pid",PID,"PID",0,"The product id (0c30 or 0c31)" }, {"pid",PID,"PID",0,"The product id (0c30 or 0c31)" },
{"serial",SERIAL,"SERIAL",0,"The usb serial number" }, {"serial",SERIAL,"SERIAL",0,"The usb serial number" },
{ 0 } { 0 }
}; };
static std::string command, action; static std::string command, action;
int vid, pid; int vid, pid;
static std::string serial; static std::string serial;
static error_t parse_opt (int key, char *arg, struct argp_state *state) { static error_t parse_opt (int key, char *arg, struct argp_state *state) {
switch (key) { switch (key) {
case PID: case PID:
pid = strtol(arg, NULL, 16); pid = strtol(arg, NULL, 16);
break; break;
case SERIAL: case SERIAL:
serial = arg; serial = arg;
break; break;
case VID: case VID:
vid = strtol(arg, NULL, 16); vid = strtol(arg, NULL, 16);
break; break;
case ARGP_KEY_NO_ARGS: case ARGP_KEY_NO_ARGS:
argp_usage (state); argp_usage (state);
case ARGP_KEY_ARG: case ARGP_KEY_ARG:
command = arg; command = arg;
action = state->argv[state->next]; action = state->argv[state->next];
state->next = state->argc; state->next = state->argc;
break; break;
default: default:
return ARGP_ERR_UNKNOWN; return ARGP_ERR_UNKNOWN;
} }
return 0; return 0;
} }
static struct argp argp = { options, parse_opt, args_doc, doc }; static struct argp argp = { options, parse_opt, args_doc, doc };
void handle_controller(void) { void handle_controller(void) {
if (vid == 0 || pid == 0) { if (vid == 0 || pid == 0) {
fprintf(stderr, "Missing parameter vid or pid\n"); fprintf(stderr, "Missing parameter vid or pid\n");
} }
if (action.compare("connect") == 0) { if (action.compare("connect") == 0) {
tdConnectTellStickController(vid,pid,serial.c_str()); tdConnectTellStickController(vid,pid,serial.c_str());
} else if (action.compare("disconnect") == 0) { } else if (action.compare("disconnect") == 0) {
tdDisconnectTellStickController(vid,pid,serial.c_str()); tdDisconnectTellStickController(vid,pid,serial.c_str());
} }
} }
int main(int argc, char **argv) { int main(int argc, char **argv) {
argp_parse (&argp, argc, argv, 0, 0, 0); argp_parse (&argp, argc, argv, 0, 0, 0);
if (command.compare("controller") == 0) { if (command.compare("controller") == 0) {
handle_controller(); handle_controller();
} }
return 0; return 0;
} }

View file

@ -1,56 +1,56 @@
PROJECT(tdtool) PROJECT(tdtool)
cmake_policy(SET CMP0005 NEW) cmake_policy(SET CMP0005 NEW)
SET (tdtool_DESCRIPTION SET (tdtool_DESCRIPTION
"a command line utility to send commands to a Telldus TellStick" "a command line utility to send commands to a Telldus TellStick"
) )
SET(tdtool_SRCS SET(tdtool_SRCS
main.cpp main.cpp
) )
ADD_EXECUTABLE(tdtool ADD_EXECUTABLE(tdtool
${tdtool_SRCS} ${tdtool_SRCS}
) )
SIGN(tdtool) SIGN(tdtool)
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_SOURCE_DIR}/driver ${CMAKE_SOURCE_DIR}/driver
) )
ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" ) ADD_DEFINITIONS( -DVERSION="${DISPLAYED_VERSION}" )
IF (WIN32) IF (WIN32)
TARGET_LINK_LIBRARIES(tdtool TARGET_LINK_LIBRARIES(tdtool
TelldusCore TelldusCore
openbsd-getopt openbsd-getopt
) )
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
${CMAKE_SOURCE_DIR}/3rdparty/openbsd-getopt ${CMAKE_SOURCE_DIR}/3rdparty/openbsd-getopt
) )
ELSEIF (APPLE) ELSEIF (APPLE)
TARGET_LINK_LIBRARIES(tdtool TARGET_LINK_LIBRARIES(tdtool
TelldusCore TelldusCore
) )
ELSE (WIN32) ELSE (WIN32)
TARGET_LINK_LIBRARIES(tdtool TARGET_LINK_LIBRARIES(tdtool
${CMAKE_BINARY_DIR}/client/libtelldus-core.so ${CMAKE_BINARY_DIR}/client/libtelldus-core.so
) )
ENDIF (WIN32) ENDIF (WIN32)
IF (UNIX) IF (UNIX)
IF (GENERATE_MAN) IF (GENERATE_MAN)
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET tdtool TARGET tdtool
POST_BUILD POST_BUILD
COMMAND help2man -n ${tdtool_DESCRIPTION} ./tdtool > tdtool.1 COMMAND help2man -n ${tdtool_DESCRIPTION} ./tdtool > tdtool.1
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating man file tdtool.1" COMMENT "Generating man file tdtool.1"
) )
INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/tdtool.1 DESTINATION share/man/man1) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/tdtool.1 DESTINATION share/man/man1)
ENDIF (GENERATE_MAN) ENDIF (GENERATE_MAN)
ENDIF (UNIX) ENDIF (UNIX)
INSTALL(TARGETS tdtool RUNTIME DESTINATION bin) INSTALL(TARGETS tdtool RUNTIME DESTINATION bin)

View file

@ -1,486 +1,486 @@
#include <stdio.h> #include <stdio.h>
#include <getopt.h> #include <getopt.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctime> #include <ctime>
#include "../client/telldus-core.h" #include "../client/telldus-core.h"
#ifdef _WINDOWS #ifdef _WINDOWS
#define strcasecmp _stricmp #define strcasecmp _stricmp
#define DEGREE " " #define DEGREE " "
#else #else
#define DEGREE "°" #define DEGREE "°"
#endif #endif
const int SUPPORTED_METHODS = const int SUPPORTED_METHODS =
TELLSTICK_TURNON | TELLSTICK_TURNON |
TELLSTICK_TURNOFF | TELLSTICK_TURNOFF |
TELLSTICK_BELL | TELLSTICK_BELL |
TELLSTICK_DIM; TELLSTICK_DIM;
const int DATA_LENGTH = 20; const int DATA_LENGTH = 20;
void print_usage( char *name ) { void print_usage( char *name ) {
printf("Usage: %s [ options ]\n", name); printf("Usage: %s [ options ]\n", name);
printf("\n"); printf("\n");
printf("Options:\n"); printf("Options:\n");
printf(" -[bdefhlnrv] [ --list ] [ --help ]\n"); printf(" -[bdefhlnrv] [ --list ] [ --help ]\n");
printf(" [ --list-sensors ] [ --list-devices ]\n"); printf(" [ --list-sensors ] [ --list-devices ]\n");
printf(" [ --on device ] [ --off device ] [ --bell device ]\n"); printf(" [ --on device ] [ --off device ] [ --bell device ]\n");
printf(" [ --learn device ]\n"); printf(" [ --learn device ]\n");
printf(" [ --dimlevel level --dim device ]\n"); printf(" [ --dimlevel level --dim device ]\n");
printf(" [ --raw input ]\n"); printf(" [ --raw input ]\n");
printf("\n"); printf("\n");
printf(" --list (-l short option)\n"); printf(" --list (-l short option)\n");
printf(" List currently configured devices and all discovered sensors.\n"); printf(" List currently configured devices and all discovered sensors.\n");
printf("\n"); printf("\n");
printf(" --list-sensors\n"); printf(" --list-sensors\n");
printf(" --list-devices\n"); printf(" --list-devices\n");
printf(" Alternative devices/sensors listing:\n"); printf(" Alternative devices/sensors listing:\n");
printf(" Shows devices and/or sensors using key=value format (with tabs as\n"); printf(" Shows devices and/or sensors using key=value format (with tabs as\n");
printf(" separators, one device/sensor per line, no header lines.)\n"); printf(" separators, one device/sensor per line, no header lines.)\n");
printf("\n"); printf("\n");
printf(" --help (-h short option)\n"); printf(" --help (-h short option)\n");
printf(" Shows this screen.\n"); printf(" Shows this screen.\n");
printf("\n"); printf("\n");
printf(" --on device (-n short option)\n"); printf(" --on device (-n short option)\n");
printf(" Turns on device. 'device' could either be an integer of the\n"); printf(" Turns on device. 'device' could either be an integer of the\n");
printf(" device-id, or the name of the device.\n"); printf(" device-id, or the name of the device.\n");
printf(" Both device-id and name is outputed with the --list option\n"); printf(" Both device-id and name is outputed with the --list option\n");
printf("\n"); printf("\n");
printf(" --off device (-f short option)\n"); printf(" --off device (-f short option)\n");
printf(" Turns off device. 'device' could either be an integer of the\n"); printf(" Turns off device. 'device' could either be an integer of the\n");
printf(" device-id, or the name of the device.\n"); printf(" device-id, or the name of the device.\n");
printf(" Both device-id and name is outputed with the --list option\n"); printf(" Both device-id and name is outputed with the --list option\n");
printf("\n"); printf("\n");
printf(" --dim device (-d short option)\n"); printf(" --dim device (-d short option)\n");
printf(" Dims device. 'device' could either be an integer of the device-id,\n"); printf(" Dims device. 'device' could either be an integer of the device-id,\n");
printf(" or the name of the device.\n"); printf(" or the name of the device.\n");
printf(" Both device-id and name is outputed with the --list option\n"); printf(" Both device-id and name is outputed with the --list option\n");
printf(" Note: The dimlevel parameter must be set before using this option.\n"); printf(" Note: The dimlevel parameter must be set before using this option.\n");
printf("\n"); printf("\n");
printf(" --dimlevel level (-v short option)\n"); printf(" --dimlevel level (-v short option)\n");
printf(" Set dim level. 'level' should an integer, 0-255.\n"); printf(" Set dim level. 'level' should an integer, 0-255.\n");
printf(" Note: This parameter must be set before using dim.\n"); printf(" Note: This parameter must be set before using dim.\n");
printf("\n"); printf("\n");
printf(" --bell device (-b short option)\n"); printf(" --bell device (-b short option)\n");
printf(" Sends bell command to devices supporting this. 'device' could\n"); printf(" Sends bell command to devices supporting this. 'device' could\n");
printf(" either be an integer of the device-id, or the name of the device.\n"); printf(" either be an integer of the device-id, or the name of the device.\n");
printf(" Both device-id and name is outputed with the --list option\n"); printf(" Both device-id and name is outputed with the --list option\n");
printf("\n"); printf("\n");
printf(" --learn device (-e short option)\n"); printf(" --learn device (-e short option)\n");
printf(" Sends a special learn command to devices supporting this. This is normaly\n"); printf(" Sends a special learn command to devices supporting this. This is normaly\n");
printf(" devices of 'selflearning' type. 'device' could either be an integer\n"); printf(" devices of 'selflearning' type. 'device' could either be an integer\n");
printf(" of the device-id, or the name of the device.\n"); printf(" of the device-id, or the name of the device.\n");
printf(" Both device-id and name is outputed with the --list option\n"); printf(" Both device-id and name is outputed with the --list option\n");
printf("\n"); printf("\n");
printf(" --raw input (-r short option)\n"); printf(" --raw input (-r short option)\n");
printf(" This command sends a raw command to TellStick.\n"); printf(" This command sends a raw command to TellStick.\n");
printf(" input can be either - or a filename. If input is - the data is\n"); printf(" input can be either - or a filename. If input is - the data is\n");
printf(" taken from stdin, otherwise the data is taken from the supplied filename.\n"); printf(" taken from stdin, otherwise the data is taken from the supplied filename.\n");
printf("\n"); printf("\n");
printf(" Example to turn on an ArcTech codeswitch A1:\n"); printf(" Example to turn on an ArcTech codeswitch A1:\n");
printf(" echo 'S$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$kk$$kk$$kk$$}+' | tdtool --raw -\n"); printf(" echo 'S$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$k$kk$$kk$$kk$$}+' | tdtool --raw -\n");
printf("\n"); printf("\n");
printf("Report bugs to <info.tech@telldus.se>\n"); printf("Report bugs to <info.tech@telldus.se>\n");
} }
void print_version() { void print_version() {
printf("tdtool " VERSION "\n"); printf("tdtool " VERSION "\n");
printf("\n"); printf("\n");
printf("Copyright (C) 2011 Telldus Technologies AB\n"); printf("Copyright (C) 2011 Telldus Technologies AB\n");
printf("\n"); printf("\n");
printf("Written by Micke Prag <micke.prag@telldus.se>\n"); printf("Written by Micke Prag <micke.prag@telldus.se>\n");
} }
void print_device( int index ) { void print_device( int index ) {
tdInit(); tdInit();
int intId = tdGetDeviceId(index); int intId = tdGetDeviceId(index);
char *name = tdGetName(intId); char *name = tdGetName(intId);
printf("%i\t%s\t", intId, name); printf("%i\t%s\t", intId, name);
tdReleaseString(name); tdReleaseString(name);
int lastSentCommand = tdLastSentCommand(intId, SUPPORTED_METHODS); int lastSentCommand = tdLastSentCommand(intId, SUPPORTED_METHODS);
char *level = 0; char *level = 0;
switch(lastSentCommand) { switch(lastSentCommand) {
case TELLSTICK_TURNON: case TELLSTICK_TURNON:
printf("ON"); printf("ON");
break; break;
case TELLSTICK_TURNOFF: case TELLSTICK_TURNOFF:
printf("OFF"); printf("OFF");
break; break;
case TELLSTICK_DIM: case TELLSTICK_DIM:
level = tdLastSentValue(intId); level = tdLastSentValue(intId);
printf("DIMMED:%s", level); printf("DIMMED:%s", level);
tdReleaseString(level); tdReleaseString(level);
break; break;
default: default:
printf("Unknown state"); printf("Unknown state");
} }
printf("\n"); printf("\n");
} }
int list_devices() { int list_devices() {
tdInit(); tdInit();
int intNum = tdGetNumberOfDevices(); int intNum = tdGetNumberOfDevices();
if (intNum < 0) { if (intNum < 0) {
char *errorString = tdGetErrorString(intNum); char *errorString = tdGetErrorString(intNum);
fprintf(stderr, "Error fetching devices: %s\n", errorString); fprintf(stderr, "Error fetching devices: %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return intNum; return intNum;
} }
printf("Number of devices: %i\n", intNum); printf("Number of devices: %i\n", intNum);
int i = 0; int i = 0;
while (i < intNum) { while (i < intNum) {
print_device( i ); print_device( i );
i++; i++;
} }
char protocol[DATA_LENGTH], model[DATA_LENGTH]; char protocol[DATA_LENGTH], model[DATA_LENGTH];
int sensorId = 0, dataTypes = 0; int sensorId = 0, dataTypes = 0;
int sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes); int sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes);
if(sensorStatus == 0){ if(sensorStatus == 0){
printf("\n\nSENSORS:\n\n%-20s\t%-20s\t%-5s\t%-5s\t%-8s\t%-20s\n", "PROTOCOL", "MODEL", "ID", "TEMP", "HUMIDITY", "LAST UPDATED"); printf("\n\nSENSORS:\n\n%-20s\t%-20s\t%-5s\t%-5s\t%-8s\t%-20s\n", "PROTOCOL", "MODEL", "ID", "TEMP", "HUMIDITY", "LAST UPDATED");
} }
while(sensorStatus == 0){ while(sensorStatus == 0){
char tempvalue[DATA_LENGTH]; char tempvalue[DATA_LENGTH];
tempvalue[0] = 0; tempvalue[0] = 0;
char humidityvalue[DATA_LENGTH]; char humidityvalue[DATA_LENGTH];
humidityvalue[0] = 0; humidityvalue[0] = 0;
char timeBuf[80]; char timeBuf[80];
timeBuf[0] = 0; timeBuf[0] = 0;
time_t timestamp = 0; time_t timestamp = 0;
if (dataTypes & TELLSTICK_TEMPERATURE) { if (dataTypes & TELLSTICK_TEMPERATURE) {
tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp); tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp);
strcat(tempvalue, DEGREE); strcat(tempvalue, DEGREE);
strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
} }
if (dataTypes & TELLSTICK_HUMIDITY) { if (dataTypes & TELLSTICK_HUMIDITY) {
tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp); tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp);
strcat(humidityvalue, "%"); strcat(humidityvalue, "%");
strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
} }
printf("%-20s\t%-20s\t%-5i\t%-5s\t%-8s\t%-20s\n", protocol, model, sensorId, tempvalue, humidityvalue, timeBuf); printf("%-20s\t%-20s\t%-5i\t%-5s\t%-8s\t%-20s\n", protocol, model, sensorId, tempvalue, humidityvalue, timeBuf);
sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes); sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes);
} }
printf("\n"); printf("\n");
if(sensorStatus != TELLSTICK_ERROR_DEVICE_NOT_FOUND){ if(sensorStatus != TELLSTICK_ERROR_DEVICE_NOT_FOUND){
char *errorString = tdGetErrorString(sensorStatus); char *errorString = tdGetErrorString(sensorStatus);
fprintf(stderr, "Error fetching sensors: %s\n", errorString); fprintf(stderr, "Error fetching sensors: %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return sensorStatus; return sensorStatus;
} }
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
/* list sensors using key=value format, one sensor/line, no header lines /* list sensors using key=value format, one sensor/line, no header lines
* and no degree or percent signs attached to the numbers - just * and no degree or percent signs attached to the numbers - just
* plain values. */ * plain values. */
int list_kv_sensors() { int list_kv_sensors() {
char protocol[DATA_LENGTH], model[DATA_LENGTH]; char protocol[DATA_LENGTH], model[DATA_LENGTH];
tdInit(); tdInit();
int sensorId = 0, dataTypes = 0; int sensorId = 0, dataTypes = 0;
time_t now = 0; time_t now = 0;
int sensorStatus; int sensorStatus;
time(&now); time(&now);
while(1) { while(1) {
sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes); sensorStatus = tdSensor(protocol, DATA_LENGTH, model, DATA_LENGTH, &sensorId, &dataTypes);
if (sensorStatus != 0) break; if (sensorStatus != 0) break;
printf("type=sensor\tprotocol=%s\tmodel=%s\tid=%d", printf("type=sensor\tprotocol=%s\tmodel=%s\tid=%d",
protocol, model, sensorId); protocol, model, sensorId);
time_t timestamp = 0; time_t timestamp = 0;
if (dataTypes & TELLSTICK_TEMPERATURE) { if (dataTypes & TELLSTICK_TEMPERATURE) {
char tempvalue[DATA_LENGTH]; char tempvalue[DATA_LENGTH];
tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp); tdSensorValue(protocol, model, sensorId, TELLSTICK_TEMPERATURE, tempvalue, DATA_LENGTH, (int *)&timestamp);
printf("\ttemperature=%s", tempvalue); printf("\ttemperature=%s", tempvalue);
} }
if (dataTypes & TELLSTICK_HUMIDITY) { if (dataTypes & TELLSTICK_HUMIDITY) {
char humidityvalue[DATA_LENGTH]; char humidityvalue[DATA_LENGTH];
tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp); tdSensorValue(protocol, model, sensorId, TELLSTICK_HUMIDITY, humidityvalue, DATA_LENGTH, (int *)&timestamp);
printf("\thumidity=%s", humidityvalue); printf("\thumidity=%s", humidityvalue);
} }
if (dataTypes & (TELLSTICK_TEMPERATURE | TELLSTICK_HUMIDITY)) { if (dataTypes & (TELLSTICK_TEMPERATURE | TELLSTICK_HUMIDITY)) {
/* timestamp has been set, print time & age */ /* timestamp has been set, print time & age */
/* (age is more useful on e.g. embedded systems /* (age is more useful on e.g. embedded systems
* which may not have real-time clock chips => * which may not have real-time clock chips =>
* time is useful only as a relative value) */ * time is useful only as a relative value) */
char timeBuf[80]; char timeBuf[80];
strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp)); strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
printf("\ttime=%s\tage=%d", timeBuf, (int)(now - timestamp)); printf("\ttime=%s\tage=%d", timeBuf, (int)(now - timestamp));
} }
printf("\n"); printf("\n");
} }
if(sensorStatus != TELLSTICK_ERROR_DEVICE_NOT_FOUND){ if(sensorStatus != TELLSTICK_ERROR_DEVICE_NOT_FOUND){
char *errorString = tdGetErrorString(sensorStatus); char *errorString = tdGetErrorString(sensorStatus);
fprintf(stderr, "Error fetching sensors: %s\n", errorString); fprintf(stderr, "Error fetching sensors: %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return sensorStatus; return sensorStatus;
} }
return TELLSTICK_SUCCESS; return TELLSTICK_SUCCESS;
} }
/* list devices using key=value format, one device/line, no header lines */ /* list devices using key=value format, one device/line, no header lines */
int list_kv_devices() { int list_kv_devices() {
tdInit(); tdInit();
int intNum = tdGetNumberOfDevices(); int intNum = tdGetNumberOfDevices();
if (intNum < 0) { if (intNum < 0) {
char *errorString = tdGetErrorString(intNum); char *errorString = tdGetErrorString(intNum);
fprintf(stderr, "Error fetching devices: %s\n", errorString); fprintf(stderr, "Error fetching devices: %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return intNum; return intNum;
} }
int index = 0; int index = 0;
while (index < intNum) { while (index < intNum) {
tdInit(); tdInit();
int intId = tdGetDeviceId(index); int intId = tdGetDeviceId(index);
char *name = tdGetName(intId); char *name = tdGetName(intId);
printf("type=device\tid=%i\tname=%s", intId, name); printf("type=device\tid=%i\tname=%s", intId, name);
tdReleaseString(name); tdReleaseString(name);
int lastSentCommand = tdLastSentCommand(intId, SUPPORTED_METHODS); int lastSentCommand = tdLastSentCommand(intId, SUPPORTED_METHODS);
char *level = 0; char *level = 0;
switch(lastSentCommand) { switch(lastSentCommand) {
case TELLSTICK_TURNON: case TELLSTICK_TURNON:
printf("\tlastsentcommand=ON"); printf("\tlastsentcommand=ON");
break; break;
case TELLSTICK_TURNOFF: case TELLSTICK_TURNOFF:
printf("\tlastsentcommand=OFF"); printf("\tlastsentcommand=OFF");
break; break;
case TELLSTICK_DIM: case TELLSTICK_DIM:
level = tdLastSentValue(intId); level = tdLastSentValue(intId);
printf("\tlastsentcommand=DIMMED\tdimlevel=%s", level); printf("\tlastsentcommand=DIMMED\tdimlevel=%s", level);
tdReleaseString(level); tdReleaseString(level);
break; break;
/* default: state is unknown, print nothing. */ /* default: state is unknown, print nothing. */
} }
printf("\n"); printf("\n");
index++; index++;
} }
} }
int find_device( char *device ) { int find_device( char *device ) {
tdInit(); tdInit();
int deviceId = atoi(device); int deviceId = atoi(device);
if (deviceId == 0) { //Try to find the id from the name if (deviceId == 0) { //Try to find the id from the name
int intNum = tdGetNumberOfDevices(); int intNum = tdGetNumberOfDevices();
int index = 0; int index = 0;
while (index < intNum) { while (index < intNum) {
int id = tdGetDeviceId(index); int id = tdGetDeviceId(index);
char *name = tdGetName( id ); char *name = tdGetName( id );
if (strcasecmp(name, device) == 0) { if (strcasecmp(name, device) == 0) {
deviceId = id; deviceId = id;
tdReleaseString(name); tdReleaseString(name);
break; break;
} }
tdReleaseString(name); tdReleaseString(name);
index++; index++;
} }
} }
return deviceId; return deviceId;
} }
int switch_device( bool turnOn, char *device ) { int switch_device( bool turnOn, char *device ) {
tdInit(); tdInit();
int deviceId = find_device( device ); int deviceId = find_device( device );
if (deviceId == 0) { if (deviceId == 0) {
printf("Device '%s', not found!\n", device); printf("Device '%s', not found!\n", device);
return TELLSTICK_ERROR_DEVICE_NOT_FOUND; return TELLSTICK_ERROR_DEVICE_NOT_FOUND;
} }
char *name = tdGetName( deviceId ); char *name = tdGetName( deviceId );
int deviceType = tdGetDeviceType( deviceId ); int deviceType = tdGetDeviceType( deviceId );
printf("Turning %s %s %i, %s", printf("Turning %s %s %i, %s",
(turnOn ? "on" : "off"), (turnOn ? "on" : "off"),
(deviceType == TELLSTICK_TYPE_DEVICE ? "device" : "group"), (deviceType == TELLSTICK_TYPE_DEVICE ? "device" : "group"),
deviceId, deviceId,
name); name);
tdReleaseString(name); tdReleaseString(name);
int retval = (turnOn ? tdTurnOn( deviceId ) : tdTurnOff( deviceId )); int retval = (turnOn ? tdTurnOn( deviceId ) : tdTurnOff( deviceId ));
char *errorString = tdGetErrorString(retval); char *errorString = tdGetErrorString(retval);
printf(" - %s\n", errorString); printf(" - %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return retval; return retval;
} }
int dim_device( char *device, int level ) { int dim_device( char *device, int level ) {
tdInit(); tdInit();
int deviceId = find_device( device ); int deviceId = find_device( device );
if (deviceId == 0) { if (deviceId == 0) {
printf("Device '%s', not found!\n", device); printf("Device '%s', not found!\n", device);
return TELLSTICK_ERROR_DEVICE_NOT_FOUND; return TELLSTICK_ERROR_DEVICE_NOT_FOUND;
} }
if (level < 0 || level > 255) { if (level < 0 || level > 255) {
printf("Level %i out of range!\n", level); printf("Level %i out of range!\n", level);
return TELLSTICK_ERROR_SYNTAX; return TELLSTICK_ERROR_SYNTAX;
} }
char *name = tdGetName( deviceId ); char *name = tdGetName( deviceId );
int retval = tdDim( deviceId, (unsigned char)level ); int retval = tdDim( deviceId, (unsigned char)level );
char *errorString = tdGetErrorString(retval); char *errorString = tdGetErrorString(retval);
printf("Dimming device: %i %s to %i - %s\n", deviceId, name, level, errorString); printf("Dimming device: %i %s to %i - %s\n", deviceId, name, level, errorString);
tdReleaseString(name); tdReleaseString(name);
tdReleaseString(errorString); tdReleaseString(errorString);
return retval; return retval;
} }
int bell_device( char *device ) { int bell_device( char *device ) {
tdInit(); tdInit();
int deviceId = find_device( device ); int deviceId = find_device( device );
if (deviceId == 0) { if (deviceId == 0) {
printf("Device '%s', not found!\n", device); printf("Device '%s', not found!\n", device);
return TELLSTICK_ERROR_DEVICE_NOT_FOUND; return TELLSTICK_ERROR_DEVICE_NOT_FOUND;
} }
char *name = tdGetName( deviceId ); char *name = tdGetName( deviceId );
int retval = tdBell( deviceId ); int retval = tdBell( deviceId );
char *errorString = tdGetErrorString(retval); char *errorString = tdGetErrorString(retval);
printf("Sending bell to: %i %s - %s\n", deviceId, name, errorString); printf("Sending bell to: %i %s - %s\n", deviceId, name, errorString);
tdReleaseString(name); tdReleaseString(name);
tdReleaseString(errorString); tdReleaseString(errorString);
return retval; return retval;
} }
int learn_device( char *device ) { int learn_device( char *device ) {
tdInit(); tdInit();
int deviceId = find_device( device ); int deviceId = find_device( device );
if (deviceId == 0) { if (deviceId == 0) {
printf("Device '%s', not found!\n", device); printf("Device '%s', not found!\n", device);
return TELLSTICK_ERROR_DEVICE_NOT_FOUND; return TELLSTICK_ERROR_DEVICE_NOT_FOUND;
} }
char *name = tdGetName( deviceId ); char *name = tdGetName( deviceId );
int retval = tdLearn( deviceId ); int retval = tdLearn( deviceId );
char *errorString = tdGetErrorString(retval); char *errorString = tdGetErrorString(retval);
printf("Learning device: %i %s - %s\n", deviceId, name, errorString); printf("Learning device: %i %s - %s\n", deviceId, name, errorString);
tdReleaseString(name); tdReleaseString(name);
tdReleaseString(errorString); tdReleaseString(errorString);
return retval; return retval;
} }
int send_raw_command( char *command ) { int send_raw_command( char *command ) {
tdInit(); tdInit();
const int MAX_LENGTH = 100; const int MAX_LENGTH = 100;
char msg[MAX_LENGTH]; char msg[MAX_LENGTH];
if (strcmp(command, "-") == 0) { if (strcmp(command, "-") == 0) {
fgets(msg, MAX_LENGTH, stdin); fgets(msg, MAX_LENGTH, stdin);
} else { } else {
FILE *fd; FILE *fd;
fd = fopen(command, "r"); fd = fopen(command, "r");
if (fd == NULL) { if (fd == NULL) {
printf("Error opening file %s\n", command); printf("Error opening file %s\n", command);
return TELLSTICK_ERROR_UNKNOWN; return TELLSTICK_ERROR_UNKNOWN;
} }
fgets(msg, MAX_LENGTH, fd); fgets(msg, MAX_LENGTH, fd);
fclose(fd); fclose(fd);
} }
int retval = tdSendRawCommand( msg, 0 ); int retval = tdSendRawCommand( msg, 0 );
char *errorString = tdGetErrorString(retval); char *errorString = tdGetErrorString(retval);
printf("Sending raw command: %s\n", errorString); printf("Sending raw command: %s\n", errorString);
tdReleaseString(errorString); tdReleaseString(errorString);
return retval; return retval;
} }
#define LIST_KV_SENSORS 1 #define LIST_KV_SENSORS 1
#define LIST_KV_DEVICES 2 #define LIST_KV_DEVICES 2
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int optch, longindex; int optch, longindex;
static char optstring[] = "ln:f:d:b:v:e:r:hi"; static char optstring[] = "ln:f:d:b:v:e:r:hi";
static struct option long_opts[] = { static struct option long_opts[] = {
{ "list", 0, 0, 'l' }, { "list", 0, 0, 'l' },
{ "list-sensors", 0, 0, LIST_KV_SENSORS }, { "list-sensors", 0, 0, LIST_KV_SENSORS },
{ "list-devices", 0, 0, LIST_KV_DEVICES }, { "list-devices", 0, 0, LIST_KV_DEVICES },
{ "on", 1, 0, 'n' }, { "on", 1, 0, 'n' },
{ "off", 1, 0, 'f' }, { "off", 1, 0, 'f' },
{ "dim", 1, 0, 'd' }, { "dim", 1, 0, 'd' },
{ "bell", 1, 0, 'b' }, { "bell", 1, 0, 'b' },
{ "dimlevel", 1, 0, 'v' }, { "dimlevel", 1, 0, 'v' },
{ "learn", 1, 0, 'e' }, { "learn", 1, 0, 'e' },
{ "raw", 1, 0, 'r' }, { "raw", 1, 0, 'r' },
{ "help", 0, 0, 'h' }, { "help", 0, 0, 'h' },
{ "version", 0, 0, 'i'}, { "version", 0, 0, 'i'},
{ 0, 0, 0, 0} { 0, 0, 0, 0}
}; };
int level = -1; int level = -1;
if (argc < 2) { if (argc < 2) {
print_usage( argv[0] ); print_usage( argv[0] );
return -TELLSTICK_ERROR_SYNTAX; return -TELLSTICK_ERROR_SYNTAX;
} }
int returnSuccess = 0; int returnSuccess = 0;
while ( (optch = getopt_long(argc,argv,optstring,long_opts,&longindex)) != -1 ){ while ( (optch = getopt_long(argc,argv,optstring,long_opts,&longindex)) != -1 ){
int success = 0; int success = 0;
switch (optch) { switch (optch) {
case 'b' : case 'b' :
success = bell_device( &optarg[0] ); success = bell_device( &optarg[0] );
break; break;
case 'd' : case 'd' :
if (level >= 0) { if (level >= 0) {
success = dim_device( &optarg[0], level ); success = dim_device( &optarg[0], level );
break; break;
} }
printf("Dim level missing or incorrect value.\n"); printf("Dim level missing or incorrect value.\n");
success = TELLSTICK_ERROR_SYNTAX; success = TELLSTICK_ERROR_SYNTAX;
break; break;
case 'f' : case 'f' :
success = switch_device(false, &optarg[0]); success = switch_device(false, &optarg[0]);
break; break;
case 'h' : case 'h' :
print_usage( argv[0] ); print_usage( argv[0] );
success = TELLSTICK_SUCCESS; success = TELLSTICK_SUCCESS;
break; break;
case 'i' : case 'i' :
print_version( ); print_version( );
success = TELLSTICK_SUCCESS; success = TELLSTICK_SUCCESS;
break; break;
case 'l' : case 'l' :
success = list_devices(); success = list_devices();
break; break;
case LIST_KV_SENSORS: case LIST_KV_SENSORS:
success = list_kv_sensors(); success = list_kv_sensors();
break; break;
case LIST_KV_DEVICES: case LIST_KV_DEVICES:
success = list_kv_devices(); success = list_kv_devices();
break; break;
case 'n' : case 'n' :
success = switch_device(true, &optarg[0]); success = switch_device(true, &optarg[0]);
break; break;
case 'e' : case 'e' :
success = learn_device(&optarg[0]); success = learn_device(&optarg[0]);
break; break;
case 'r' : case 'r' :
success = send_raw_command(&optarg[0]); success = send_raw_command(&optarg[0]);
break; break;
case 'v' : case 'v' :
level = atoi( &optarg[0] ); level = atoi( &optarg[0] );
break; break;
default : default :
print_usage( argv[0] ); print_usage( argv[0] );
success = TELLSTICK_ERROR_SYNTAX; success = TELLSTICK_ERROR_SYNTAX;
} }
if(success != TELLSTICK_SUCCESS){ if(success != TELLSTICK_SUCCESS){
returnSuccess = success; //return last error message returnSuccess = success; //return last error message
} }
} }
tdClose(); //Cleaning up tdClose(); //Cleaning up
return -returnSuccess; return -returnSuccess;
} }

View file

@ -1,9 +1,9 @@
FILE(GLOB SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*Test.cpp" ) FILE(GLOB SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*Test.cpp" )
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/common) INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/common)
ADD_LIBRARY(TelldusCommonTests SHARED ${SRCS} ) ADD_LIBRARY(TelldusCommonTests SHARED ${SRCS} )
TARGET_LINK_LIBRARIES( TelldusCommonTests TelldusCommon ) TARGET_LINK_LIBRARIES( TelldusCommonTests TelldusCommon )
ADD_DEPENDENCIES( TelldusCommonTests TelldusCommon ) ADD_DEPENDENCIES( TelldusCommonTests TelldusCommon )