agozwave.cpp 112 KB
Newer Older
1
/*
2
   Copyright (C) 2013 Harald Klein <hari@vt100.at>
3

4 5 6
   This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License.
   This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7

8
   See the GNU General Public License for more details.
9 10 11 12 13 14 15 16 17 18 19 20 21 22

*/

#include <iostream>
#include <sstream>
#include <string.h>

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>

#include <limits.h>
#include <float.h>
23
#include <time.h>
24

25

26 27 28
#define __STDC_FORMAT_MACROS
#include <inttypes.h>

Harald Klein's avatar
Harald Klein committed
29
#include "agoapp.h"
30 31 32 33 34 35 36 37 38 39 40 41 42

#include <openzwave/Options.h>
#include <openzwave/Manager.h>
#include <openzwave/Driver.h>
#include <openzwave/Node.h>
#include <openzwave/Group.h>
#include <openzwave/Notification.h>
#include <openzwave/platform/Log.h>
#include <openzwave/value_classes/ValueStore.h>
#include <openzwave/value_classes/Value.h>
#include <openzwave/value_classes/ValueBool.h>

#include "ZWApi.h"
43
#include "ZWaveNode.h"
44

45 46 47
#define CONFIG_BASE_PATH "/etc/openzwave/"
#define CONFIG_MANUFACTURER_SPECIFIC CONFIG_BASE_PATH "manufacturer_specific.xml"

48 49 50
// Helper method to cap an int to 0x00-0xFF
#define CAP_8BIT_INT(value) (max(min(value, 0xFF), 0x00))

51 52 53 54 55 56 57 58 59 60 61 62 63 64
/* Use with #if when we want to exclude certain parts to minimum OpenZWave versions.
 * This relies on OPENZWAVE_VERSION_ defines from CMake, they are not official.
 * Note that gitrev is 0 when not built from git.
 * To get a minimium gitrev, you can use 'git describe --long --tags <somecommit>'.
 */
#define HAVE_ZWAVE_VERSION(major,minor,gitrev) \
    (OPENZWAVE_VERSION_MAJOR > (major) || \
        (OPENZWAVE_VERSION_MAJOR == (major) && \
            (OPENZWAVE_VERSION_MINOR > (minor) || \
                (OPENZWAVE_VERSION_MINOR == (minor) && OPENZWAVE_VERSION_REVISION >= (gitrev) ) \
            ) \
        ) \
    )

65 66 67
using namespace agocontrol;
using namespace OpenZWave;

68 69 70
static pthread_mutex_t g_criticalSection;
static pthread_cond_t  initCond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER;
71

Harald Klein's avatar
Harald Klein committed
72 73 74 75 76
class AgoZwave: public AgoApp {
private:
    int unitsystem;
    uint32 g_homeId;
    bool g_initFailed;
77
    Json::Value sentEvents;
Harald Klein's avatar
Harald Klein committed
78 79 80 81 82 83 84 85 86

    typedef struct {
        uint32			m_homeId;
        uint8			m_nodeId;
        bool			m_polled;
        list<ValueID>	m_values;
    } NodeInfo;
    
    list<NodeInfo*> g_nodes;
87
    map<ValueID, Json::Value> valueCache;
Harald Klein's avatar
Harald Klein committed
88 89
    ZWaveNodes devices;

90 91 92
    const char *controllerErrorStr(Driver::ControllerError err);
    NodeInfo* getNodeInfo(Notification const* _notification);
    NodeInfo* getNodeInfo(uint32 homeId, uint8 nodeId);
93
    ValueID* getValueID(int nodeid, int instance, std::string label);
94 95
    Json::Value getCommandClassConfigurationParameter(OpenZWave::ValueID* valueID);
    Json::Value getCommandClassWakeUpParameter(OpenZWave::ValueID* valueID);
96
    bool setCommandClassParameter(uint32 homeId, uint8 nodeId, uint8 commandClassId, uint8 index, std::string newValue);
97
    void requestAllNodeConfigParameters();
98
    bool filterEvent(const char *internalId, const char *eventType, std::string level);
99 100 101
    bool emitFilteredEvent(const char *internalId, const char *eventType, const char *level, const char *unit);
    bool emitFilteredEvent(const char *internalId, const char *eventType, double level, const char *unit);
    bool emitFilteredEvent(const char *internalId, const char *eventType, int level, const char *unit);
Harald Klein's avatar
Harald Klein committed
102

103
    Json::Value commandHandler(const Json::Value& content);
Harald Klein's avatar
Harald Klein committed
104 105
    void setupApp();
    void cleanupApp();
106 107
    std::string getHRCommandClassId(uint8_t commandClassId);
    std::string getHRNotification(Notification::NotificationType notificationType);
108

Harald Klein's avatar
Harald Klein committed
109 110 111 112 113
public:
    AGOAPP_CONSTRUCTOR_HEAD(AgoZwave)
        , unitsystem(0)
        , g_homeId(0)
        , g_initFailed(false)
114
        , sentEvents(Json::objectValue)
115 116
     //   , initCond(PTHREAD_COND_INITIALIZER)
     //   , initMutex(PTHREAD_MUTEX_INITIALIZER)
Harald Klein's avatar
Harald Klein committed
117 118 119 120
        {}


    void _OnNotification (Notification const* _notification);
121
    void _controller_update(Driver::ControllerState state,  Driver::ControllerError err);
Harald Klein's avatar
Harald Klein committed
122
};
123

Harald Klein's avatar
Harald Klein committed
124 125
void controller_update(Driver::ControllerState state,  Driver::ControllerError err, void *context) {
    AgoZwave *inst = static_cast<AgoZwave*>(context);
126
    if (inst != NULL) inst->_controller_update(state, err); 
Harald Klein's avatar
Harald Klein committed
127
}
128

Harald Klein's avatar
Harald Klein committed
129 130 131 132
void on_notification(Notification const* _notification, void *context) {
    AgoZwave *inst = static_cast<AgoZwave*>(context);
    inst->_OnNotification(_notification);
}
133

134
class MyLog : public i_LogImpl {
135 136 137 138
    void Write( LogLevel _level, uint8 const _nodeId, char const* _format, va_list _args );
    void QueueDump();
    void QueueClear();
    void SetLoggingState(OpenZWave::LogLevel, OpenZWave::LogLevel, OpenZWave::LogLevel);
139
    void SetLogFileName(const std::string&);
140
    std::string GetNodeString(uint8 const _nodeId);
141 142
};

143 144 145 146 147 148
void MyLog::QueueDump() {
}
void MyLog::QueueClear() {
}
void MyLog::SetLoggingState(OpenZWave::LogLevel, OpenZWave::LogLevel, OpenZWave::LogLevel) {
}
149
void MyLog::SetLogFileName(const std::string&) {
150
}
151
void MyLog::Write( LogLevel _level, uint8 const _nodeId, char const* _format, va_list _args ) {
152 153 154 155 156
    char lineBuf[1024] = {};
    if( _format != NULL && _format[0] != '\0' )
    {
        va_list saveargs;
        va_copy( saveargs, _args );
157
        vsnprintf( lineBuf, sizeof(lineBuf), _format, _args );
158 159
        va_end( saveargs );
    }
160
    std::string nodeString = GetNodeString(_nodeId);
161

162 163 164 165 166 167 168 169 170 171
    if (_level == LogLevel_StreamDetail) AGO_TRACE() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Debug) AGO_DEBUG() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Detail) AGO_DEBUG() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Info) AGO_INFO() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Alert) AGO_WARNING() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Warning) AGO_WARNING() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Error) AGO_ERROR() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Fatal) AGO_FATAL() << "OZW " << nodeString << std::string(lineBuf);
    else if (_level == LogLevel_Always) AGO_FATAL() << "OZW " << nodeString << std::string(lineBuf);
    else AGO_FATAL() << "OZW (Unknown level) << " << nodeString << std::string(lineBuf);
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
}

// Copied directly from open-zwave LogImpl
std::string MyLog::GetNodeString(uint8 const _nodeId)
{
    if( _nodeId == 0 )
    {
        return "";
    }
    else if( _nodeId == 255 )
    {
        // should make distinction between broadcast and controller better for SwitchAll broadcast
        return "contrlr, ";
    }
    else
    {
        char buf[20];
        snprintf( buf, sizeof(buf), "Node%03d, ", _nodeId );
        return buf;
    }
192
}
193

Harald Klein's avatar
Harald Klein committed
194
const char *AgoZwave::controllerErrorStr (Driver::ControllerError err) {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    switch (err) {
        case Driver::ControllerError_None:
            return "None";
        case Driver::ControllerError_ButtonNotFound:
            return "Button Not Found";
        case Driver::ControllerError_NodeNotFound:
            return "Node Not Found";
        case Driver::ControllerError_NotBridge:
            return "Not a Bridge";
        case Driver::ControllerError_NotPrimary:
            return "Not Primary Controller";
        case Driver::ControllerError_IsPrimary:
            return "Is Primary Controller";
        case Driver::ControllerError_NotSUC:
            return "Not Static Update Controller";
        case Driver::ControllerError_NotSecondary:
            return "Not Secondary Controller";
        case Driver::ControllerError_NotFound:
            return "Not Found";
        case Driver::ControllerError_Busy:
            return "Controller Busy";
        case Driver::ControllerError_Failed:
            return "Failed";
        case Driver::ControllerError_Disabled:
            return "Disabled";
        case Driver::ControllerError_Overflow:
            return "Overflow";
        default:
            return "Unknown error";
    }
225 226
}

227
void AgoZwave::_controller_update(Driver::ControllerState state,  Driver::ControllerError err) {
228
    Json::Value eventmap;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    eventmap["statecode"]=state;
    switch(state) {
        case Driver::ControllerState_Normal:
            AGO_INFO() << "controller state update: no command in progress";
            eventmap["state"]="normal";
            eventmap["description"]="Normal: No command in progress";
            // nothing to do
            break;
        case Driver::ControllerState_Waiting:
            AGO_INFO() << "controller state update: waiting for user action";
            eventmap["state"]="awaitaction";
            eventmap["description"]="Waiting for user action";
            // waiting for user action
            break;
        case Driver::ControllerState_Cancel:
            AGO_INFO() << "controller state update: command was cancelled";
            eventmap["state"]="cancel";
            eventmap["description"]="Command was cancelled";
            break;
        case Driver::ControllerState_Error:
            AGO_ERROR() << "controller state update: command returned error";
            eventmap["state"]="error";
            eventmap["description"]="Command returned error";
            eventmap["error"] = err;
            eventmap["errorstring"] = controllerErrorStr(err);
            break;
        case Driver::ControllerState_Sleeping:
            AGO_INFO() << "controller state update: device went to sleep";
            eventmap["state"]="sleep";
            eventmap["description"]="Device went to sleep";
            break;

        case Driver::ControllerState_InProgress:
            AGO_INFO() << "controller state update: communicating with other device";
            eventmap["state"]="inprogress";
            eventmap["description"]="Communication in progress";
            // communicating with device
            break;
        case Driver::ControllerState_Completed:
            AGO_INFO() << "controller state update: command has completed successfully";
            eventmap["state"]="success";
            eventmap["description"]="Command completed";
            break;
        case Driver::ControllerState_Failed:
            AGO_ERROR() << "controller state update: command has failed";
            eventmap["state"]="failed";
            eventmap["description"]="Command failed";
            // houston..
            break;
        case Driver::ControllerState_NodeOK:
            AGO_INFO() << "controller state update: node ok";
            eventmap["state"]="nodeok";
            eventmap["description"]="Node OK";
            break;
        case Driver::ControllerState_NodeFailed:
            AGO_ERROR() << "controller state update: node failed";
            eventmap["state"]="nodefailed";
            eventmap["description"]="Node failed";
            break;
        default:
289
            AGO_INFO() << "controller state update: unknown controller update";
290
            eventmap["state"]="unknown";
291
            eventmap["description"]="Unknown controller update";
292 293
            break;
    }
294 295 296

    agoConnection->emitEvent("zwavecontroller", "event.zwave.controllerstate", eventmap);

297 298 299
    if (err != Driver::ControllerError_None)  {
        AGO_ERROR() << "Controller error: " << controllerErrorStr(err);
    }
300 301
}

302
/**
303
 * Return Human Readable CommandClassId
304
 */
305
string AgoZwave::getHRCommandClassId(uint8_t commandClassId)
306
{
307
    std::string output;
308
    switch(commandClassId)
309
    {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
        case COMMAND_CLASS_MARK:
            output="COMMAND_CLASS_MARK";
            break;
        case COMMAND_CLASS_BASIC:
            output="COMMAND_CLASS_BASIC";
            break;
        case COMMAND_CLASS_VERSION:
            output="COMMAND_CLASS_VERSION";
            break;
        case COMMAND_CLASS_BATTERY:
            output="COMMAND_CLASS_BATTERY";
            break;
        case COMMAND_CLASS_WAKE_UP:
            output="COMMAND_CLASS_WAKE_UP";
            break;
        case COMMAND_CLASS_CONTROLLER_REPLICATION:
            output="COMMAND_CLASS_CONTROLLER_REPLICATION";
            break;
        case COMMAND_CLASS_SWITCH_MULTILEVEL:
            output="COMMAND_CLASS_SWITCH_MULTILEVEL";
            break;
        case COMMAND_CLASS_SWITCH_ALL:
            output="COMMAND_CLASS_SWITCH_ALL";
            break;
        case COMMAND_CLASS_SENSOR_BINARY:
            output="COMMAND_CLASS_SENSOR_BINARY";
            break;
        case COMMAND_CLASS_SENSOR_MULTILEVEL:
            output="COMMAND_CLASS_SENSOR_MULTILEVEL";
            break;
        case COMMAND_CLASS_SENSOR_ALARM:
            output="COMMAND_CLASS_SENSOR_ALARM";
            break;
        case COMMAND_CLASS_ALARM:
            output="COMMAND_CLASS_ALARM";
            break;
        case COMMAND_CLASS_MULTI_CMD:
            output="COMMAND_CLASS_MULTI_CMD";
            break;
        case COMMAND_CLASS_CLIMATE_CONTROL_SCHEDULE:
            output="COMMAND_CLASS_CLIMATE_CONTROL_SCHEDULE";
            break;
        case COMMAND_CLASS_CLOCK:
            output="COMMAND_CLASS_CLOCK";
            break;
        case COMMAND_CLASS_ASSOCIATION:
            output="COMMAND_CLASS_ASSOCIATION";
            break;
        case COMMAND_CLASS_CONFIGURATION:
            output="COMMAND_CLASS_CONFIGURATION";
            break;
        case COMMAND_CLASS_MANUFACTURER_SPECIFIC:
            output="COMMAND_CLASS_MANUFACTURER_SPECIFIC";
            break;
        case COMMAND_CLASS_APPLICATION_STATUS:
            output="COMMAND_CLASS_APPLICATION_STATUS";
            break;
        case COMMAND_CLASS_ASSOCIATION_COMMAND_CONFIGURATION:
            output="COMMAND_CLASS_ASSOCIATION_COMMAND_CONFIGURATION";
            break;
        case COMMAND_CLASS_AV_CONTENT_DIRECTORY_MD:
            output="COMMAND_CLASS_AV_CONTENT_DIRECTORY_MD";
            break;
        case COMMAND_CLASS_AV_CONTENT_SEARCH_MD:
            output="COMMAND_CLASS_AV_CONTENT_SEARCH_MD";
            break;
        case COMMAND_CLASS_AV_RENDERER_STATUS:
            output="COMMAND_CLASS_AV_RENDERER_STATUS";
            break;
        case COMMAND_CLASS_AV_TAGGING_MD:
            output="COMMAND_CLASS_AV_TAGGING_MD";
            break;
        case COMMAND_CLASS_BASIC_WINDOW_COVERING:
            output="COMMAND_CLASS_BASIC_WINDOW_COVERING";
            break;
        case COMMAND_CLASS_CHIMNEY_FAN:
            output="COMMAND_CLASS_CHIMNEY_FAN";
            break;
        case COMMAND_CLASS_COMPOSITE:
            output="COMMAND_CLASS_COMPOSITE";
            break;
        case COMMAND_CLASS_DOOR_LOCK:
            output="COMMAND_CLASS_DOOR_LOCK";
            break;
        case COMMAND_CLASS_ENERGY_PRODUCTION:
            output="COMMAND_CLASS_ENERGY_PRODUCTION";
            break;
        case COMMAND_CLASS_FIRMWARE_UPDATE_MD:
            output="COMMAND_CLASS_FIRMWARE_UPDATE_MD";
            break;
        case COMMAND_CLASS_GEOGRAPHIC_LOCATION:
            output="COMMAND_CLASS_GEOGRAPHIC_LOCATION";
            break;
        case COMMAND_CLASS_GROUPING_NAME:
            output="COMMAND_CLASS_GROUPING_NAME";
            break;
        case COMMAND_CLASS_HAIL:
            output="COMMAND_CLASS_HAIL";
            break;
        case COMMAND_CLASS_INDICATOR:
            output="COMMAND_CLASS_INDICATOR";
            break;
        case COMMAND_CLASS_IP_CONFIGURATION:
            output="COMMAND_CLASS_IP_CONFIGURATION";
            break;
        case COMMAND_CLASS_LANGUAGE:
            output="COMMAND_CLASS_LANGUAGE";
            break;
        case COMMAND_CLASS_LOCK:
            output="COMMAND_CLASS_LOCK";
            break;
        case COMMAND_CLASS_MANUFACTURER_PROPRIETARY:
            output="COMMAND_CLASS_MANUFACTURER_PROPRIETARY";
            break;
        case COMMAND_CLASS_METER_PULSE:
            output="COMMAND_CLASS_METER_PULSE";
            break;
        case COMMAND_CLASS_METER:
            output="COMMAND_CLASS_METER";
            break;
        case COMMAND_CLASS_MTP_WINDOW_COVERING:
            output="COMMAND_CLASS_MTP_WINDOW_COVERING";
            break;
        case COMMAND_CLASS_MULTI_INSTANCE_ASSOCIATION:
            output="COMMAND_CLASS_MULTI_INSTANCE_ASSOCIATION";
            break;
        case COMMAND_CLASS_MULTI_INSTANCE:
            output="COMMAND_CLASS_MULTI_INSTANCE";
            break;
        case COMMAND_CLASS_NO_OPERATION:
            output="COMMAND_CLASS_NO_OPERATION";
            break;
        case COMMAND_CLASS_NODE_NAMING:
            output="COMMAND_CLASS_NODE_NAMING";
            break;
        case COMMAND_CLASS_NON_INTEROPERABLE:
            output="COMMAND_CLASS_NON_INTEROPERABLE";
            break;
        case COMMAND_CLASS_POWERLEVEL:
            output="COMMAND_CLASS_POWERLEVEL";
            break;
        case COMMAND_CLASS_PROPRIETARY:
            output="COMMAND_CLASS_PROPRIETARY";
            break;
        case COMMAND_CLASS_PROTECTION:
            output="COMMAND_CLASS_PROTECTION";
            break;
        case COMMAND_CLASS_REMOTE_ASSOCIATION_ACTIVATE:
            output="COMMAND_CLASS_REMOTE_ASSOCIATION_ACTIVATE";
            break;
        case COMMAND_CLASS_REMOTE_ASSOCIATION:
            output="COMMAND_CLASS_REMOTE_ASSOCIATION";
            break;
        case COMMAND_CLASS_SCENE_ACTIVATION:
            output="COMMAND_CLASS_SCENE_ACTIVATION";
            break;
        case COMMAND_CLASS_SCENE_ACTUATOR_CONF:
            output="COMMAND_CLASS_SCENE_ACTUATOR_CONF";
            break;
        case COMMAND_CLASS_SCENE_CONTROLLER_CONF:
            output="COMMAND_CLASS_SCENE_CONTROLLER_CONF";
            break;
        case COMMAND_CLASS_SCREEN_ATTRIBUTES:
            output="COMMAND_CLASS_SCREEN_ATTRIBUTES";
            break;
        case COMMAND_CLASS_SCREEN_MD:
            output="COMMAND_CLASS_SCREEN_MD";
            break;
        case COMMAND_CLASS_SECURITY:
            output="COMMAND_CLASS_SECURITY";
            break;
        case COMMAND_CLASS_SENSOR_CONFIGURATION:
            output="COMMAND_CLASS_SENSOR_CONFIGURATION";
            break;
        case COMMAND_CLASS_SILENCE_ALARM:
            output="COMMAND_CLASS_SILENCE_ALARM";
            break;
        case COMMAND_CLASS_SIMPLE_AV_CONTROL:
            output="COMMAND_CLASS_SIMPLE_AV_CONTROL";
            break;
        case COMMAND_CLASS_SWITCH_BINARY:
            output="COMMAND_CLASS_SWITCH_BINARY";
            break;
        case COMMAND_CLASS_SWITCH_TOGGLE_BINARY:
            output="COMMAND_CLASS_SWITCH_TOGGLE_BINARY";
            break;
        case COMMAND_CLASS_SWITCH_TOGGLE_MULTILEVEL:
            output="COMMAND_CLASS_SWITCH_TOGGLE_MULTILEVEL";
            break;
        case COMMAND_CLASS_THERMOSTAT_FAN_MODE:
            output="COMMAND_CLASS_THERMOSTAT_FAN_MODE";
            break;
        case COMMAND_CLASS_THERMOSTAT_FAN_STATE:
            output="COMMAND_CLASS_THERMOSTAT_FAN_STATE";
            break;
        case COMMAND_CLASS_THERMOSTAT_HEATING:
            output="COMMAND_CLASS_THERMOSTAT_HEATING";
            break;
        case COMMAND_CLASS_THERMOSTAT_MODE:
            output="COMMAND_CLASS_THERMOSTAT_MODE";
            break;
        case COMMAND_CLASS_THERMOSTAT_OPERATING_STATE:
            output="COMMAND_CLASS_THERMOSTAT_OPERATING_STATE";
            break;
        case COMMAND_CLASS_THERMOSTAT_SETBACK:
            output="COMMAND_CLASS_THERMOSTAT_SETBACK";
            break;
        case COMMAND_CLASS_THERMOSTAT_SETPOINT:
            output="COMMAND_CLASS_THERMOSTAT_SETPOINT";
            break;
        case COMMAND_CLASS_TIME_PARAMETERS:
            output="COMMAND_CLASS_TIME_PARAMETERS";
            break;
        case COMMAND_CLASS_TIME:
            output="COMMAND_CLASS_TIME";
            break;
        case COMMAND_CLASS_USER_CODE:
            output="COMMAND_CLASS_USER_CODE";
            break;
        case COMMAND_CLASS_ZIP_ADV_CLIENT:
            output="COMMAND_CLASS_ZIP_ADV_CLIENT";
            break;
532 533 534
        //case COMMAND_CLASS_ZIP_ADV_SERVER:
        //    output="COMMAND_CLASS_ZIP_ADV_SERVER";
        //    break;
535 536 537 538 539 540 541 542 543 544 545 546
        case COMMAND_CLASS_ZIP_ADV_SERVICES:
            output="COMMAND_CLASS_ZIP_ADV_SERVICES";
            break;
        case COMMAND_CLASS_ZIP_CLIENT:
            output="COMMAND_CLASS_ZIP_CLIENT";
            break;
        case COMMAND_CLASS_ZIP_SERVER:
            output="COMMAND_CLASS_ZIP_SERVER";
            break;
        case COMMAND_CLASS_ZIP_SERVICES:
            output="COMMAND_CLASS_ZIP_SERVICES";
            break;
547 548 549
        case COMMAND_CLASS_COLOR:
            output="COMMAND_CLASS_COLOR";
            break;
550
        default:
551
            std::stringstream temp;
552
            temp << "COMMAND_UNKNOWN[" << (int)commandClassId << "]";
553
            output = temp.str();
554 555 556 557 558
    }
    return output;
}

/**
559
 * Return human readable notification type.
560 561 562
 */
string AgoZwave::getHRNotification(Notification::NotificationType notificationType)
{
563
    std::string output;
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    switch( notificationType )
    {
        case Notification::Type_ValueAdded:
            output="Type_ValueAdded";
            break;
        case Notification::Type_ValueRemoved:
            output="Type_ValueRemoved";
            break;
        case Notification::Type_ValueChanged:
            output="Type_ValueChanged";
            break;
        case Notification::Type_ValueRefreshed:
            output="Type_ValueRefreshed";
            break;
        case Notification::Type_Group:
            output="Type_Group";
            break;
        case Notification::Type_NodeNew:
            output="Type_NodeNew";
            break;
        case Notification::Type_NodeAdded:
            output="Type_NodeAdded";
            break;
        case Notification::Type_NodeRemoved:
            output="Type_NodeRemoved";
            break;
        case Notification::Type_NodeProtocolInfo:
            output="Type_NodeProtocolInfo";
            break;
        case Notification::Type_NodeNaming:
            output="Type_NodeNaming";
            break;
        case Notification::Type_NodeEvent:
            output="Type_NodeEvent";
            break;
        case Notification::Type_PollingDisabled:
            output="Type_PollingDisabled";
            break;
        case Notification::Type_PollingEnabled:
            output="Type_PollingEnabled";
            break;
        case Notification::Type_SceneEvent:
            output="Type_SceneEvent";
            break;
        case Notification::Type_CreateButton:
            output="Type_CreateButton";
            break;
        case Notification::Type_DeleteButton:
            output="Type_DeleteButton";
            break;
        case Notification::Type_ButtonOn:
            output="Type_ButtonOn";
            break;
        case Notification::Type_ButtonOff:
            output="Type_ButtonOff";
            break;
        case Notification::Type_DriverReady:
            output="Type_DriverReady";
            break;
        case Notification::Type_DriverFailed:
            output="Type_DriverFailed";
            break;
        case Notification::Type_DriverReset:
            output="Type_DriverReset";
            break;
        case Notification::Type_EssentialNodeQueriesComplete:
            output="Type_EssentialNodeQueriesComplete";
            break;
        case Notification::Type_NodeQueriesComplete:
            output="Type_NodeQueriesComplete";
            break;
        case Notification::Type_AwakeNodesQueried:
            output="Type_AwakeNodesQueried";
            break;
        case Notification::Type_AllNodesQueriedSomeDead:
            output="Type_AllNodesQueriedSomeDead";
            break;
        case Notification::Type_AllNodesQueried:
            output="Type_AllNodesQueried";
            break;
        case Notification::Type_Notification:
            output="Type_Notification";
            break;
        case Notification::Type_DriverRemoved:
            output="Type_DriverRemoved";
            break;
650 651 652 653 654
#if HAVE_ZWAVE_VERSION(1,3,397)
        case Notification::Type_ControllerCommand:
            output="Type_ControllerCommand";
            break;
#endif
655 656
        default:
            output="Type_Unknown";
657 658 659 660
    }
    return output;
}

661 662 663
/**
 * Emit event like in agoconnection but filtered duplicated event within the same second
 */
664
bool AgoZwave::filterEvent(const char *internalId, const char *eventType, std::string level)
665
{
Tang's avatar
Tang committed
666
    bool filtered = false;
667 668
    std::string sInternalId = std::string(internalId);
    std::string sEventType = std::string(eventType);
669

670
    Json::Value infos;
671
    uint64_t now = (uint64_t)(time(NULL));
672
    if( sentEvents.isMember(sInternalId) )
673 674
    {
        //add new entry
675
        AGO_TRACE() << "filterEvent: create new entry for internalid " << sInternalId;
676 677 678 679 680
        infos["eventype"] = sEventType;
        infos["level"] = level;
        infos["timestamp"] = now;
        sentEvents[sInternalId] = infos;

Tang's avatar
Tang committed
681 682
        //no filtering
        filtered = false;
683 684 685
    }
    else
    {
686
        infos = sentEvents[sInternalId];
687
        //check level
688
        if( infos.isMember("level") )
689
        {
690
            std::string oldLevel = infos["level"].asString();
691 692
            if( oldLevel==level )
            {
693
                if( infos.isMember("timestamp") )
694 695
                {
                    //same level received, check timestamp
696
                    uint64_t oldTimestamp = infos["timestamp"].asUInt64();
697 698
                    //1 seconds seems to be enough
                    if( now<=(oldTimestamp+1) )
699 700
                    {
                        //same event sent too quickly, drop it
701
                        AGO_TRACE() << "filterEvent: event " << sEventType  << " for " << sInternalId << " is filtered";
Tang's avatar
Tang committed
702
                        filtered = true;
703 704 705
                    }
                    else
                    {
Tang's avatar
Tang committed
706
                        //last event was sent some time ago, no filtering
707
                        AGO_TRACE() << "filterEvent: duplicated event " << sEventType << " detected for " << sInternalId << "but timeout expired";
Tang's avatar
Tang committed
708
                        filtered = false;
709 710 711 712 713
                    }
                }
                else
                {
                    //should not happen
714
                    AGO_TRACE() << "filterEvent: infos[timestamp] isn't exist";
Tang's avatar
Tang committed
715
                    filtered = false;
716 717 718 719 720
                }
            }
            else
            {
                //level is different, no filtering
721
                AGO_TRACE() << "filterEvent: level " << level << " is different from old one " << oldLevel << " for " << sInternalId;
Tang's avatar
Tang committed
722
                filtered = false;
723 724 725 726 727
            }
        }
        else
        {
            //should not happen
728
            AGO_TRACE() << "filterEvent: infos[level] isn't exist";
Tang's avatar
Tang committed
729
            filtered = false;
730
        }
Tang's avatar
Tang committed
731

732 733 734 735 736 737 738
        //update map
        if( !filtered )
        {
            infos["level"] = level;
            infos["timestamp"] = now;
            sentEvents[sInternalId] = infos;
        }
Tang's avatar
Tang committed
739 740
    }

741
    AGO_TRACE() << "filterEvent: sentEvent: " << sentEvents;
742

Tang's avatar
Tang committed
743
    return filtered;
744 745 746 747
}

bool AgoZwave::emitFilteredEvent(const char *internalId, const char *eventType, const char *level, const char *unit)
{
748
    std::string sLevel = std::string(level);
749 750 751 752 753 754 755 756 757 758 759 760 761
    if( !filterEvent(internalId, eventType, sLevel) )
    {
        return agoConnection->emitEvent(internalId, eventType, level, unit);
    }
    else
    {
        AGO_DEBUG() << "Event '" << eventType << "' from '" << internalId << "' at level '" << level << "' is filtered";
        return true;
    }
}

bool AgoZwave::emitFilteredEvent(const char *internalId, const char *eventType, double level, const char *unit)
{
762
    std::stringstream sLevel;
763 764 765 766 767 768 769 770 771 772 773 774 775 776
    sLevel << level;
    if( !filterEvent(internalId, eventType, sLevel.str()) )
    {
        return agoConnection->emitEvent(internalId, eventType, level, unit);
    }
    else
    {
        AGO_DEBUG() << "Event '" << eventType << "' from '" << internalId << "' at level '" << level << "' is filtered";
        return true;
    }
}

bool AgoZwave::emitFilteredEvent(const char *internalId, const char *eventType, int level, const char *unit)
{
777
    std::stringstream sLevel;
778 779 780 781 782 783 784 785 786 787 788
    sLevel << level;
    if( !filterEvent(internalId, eventType, sLevel.str()) )
    {
        return agoConnection->emitEvent(internalId, eventType, level, unit);
    }
    else
    {
        AGO_DEBUG() << "Event '" << eventType << "' from '" << internalId << "' at level '" << level << "' is filtered";
        return true;
    }
}
789

790
//-----------------------------------------------------------------------------
791
// <getNodeInfo>
792 793
// Callback that is triggered when a value, group or node changes
//-----------------------------------------------------------------------------
794
AgoZwave::NodeInfo* AgoZwave::getNodeInfo (Notification const* _notification)
795
{
796 797 798 799 800 801 802 803 804 805 806 807
    uint32 const homeId = _notification->GetHomeId();
    uint8 const nodeId = _notification->GetNodeId();
    for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
    {
        NodeInfo* nodeInfo = *it;
        if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) )
        {
            return nodeInfo;
        }
    }

    return NULL;
808 809
}

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
AgoZwave::NodeInfo* AgoZwave::getNodeInfo(uint32 homeId, uint8 nodeId)
{
    NodeInfo* result = NULL;

    for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
    {
        NodeInfo* nodeInfo = *it;
        if( nodeInfo->m_homeId==homeId && nodeInfo->m_nodeId==nodeId )
        {
            result = nodeInfo;
            break;
        }
    }

    return result;
}

827

828
ValueID* AgoZwave::getValueID(int nodeid, int instance, std::string label)
829
{
830 831
    for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
    {
832 833 834 835
        for (list<ValueID>::iterator it2 = (*it)->m_values.begin(); it2 != (*it)->m_values.end(); it2++ )
        {
            if ( ((*it)->m_nodeId == nodeid) && ((*it2).GetInstance() == instance) )
            {
836
                std::string valuelabel = OpenZWave::Manager::Get()->GetValueLabel((*it2));
837 838
                if (label == valuelabel)
                {
839 840 841 842 843 844 845
                    // AGO_TRACE() << "Found ValueID: " << (*it2).GetId();
                    return &(*it2);
                }
            }
        }
    }
    return NULL;
846 847
}

848 849 850 851
/**
 * Get COMMAND_CLASS_CONFIGURATION parameter
 * @return map containing all parameter infos
 */
852
Json::Value AgoZwave::getCommandClassConfigurationParameter(OpenZWave::ValueID* valueID)
853 854
{
    //init
855
    Json::Value param(Json::objectValue);
856 857 858 859 860 861 862 863 864 865
    if( valueID==NULL )
    {
        return param;
    }

    //add invalid parameter property
    //give info to ui that parameter is invalid
    param["invalid"] = false;

    //get parameter type
866 867
    std::vector<string> ozwItems;
    Json::Value items(Json::arrayValue);
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    switch( valueID->GetType() )
    {
        case ValueID::ValueType_Decimal:
            //Represents a non-integer value as a string, to avoid floating point accuracy issues. 
            param["type"] = "float";
            break;
        case ValueID::ValueType_Bool:
            //Boolean, true or false 
            param["type"] = "bool";
            break;
        case ValueID::ValueType_Byte:
            //8-bit unsigned value 
            param["type"] = "byte";
            break;
        case ValueID::ValueType_Short:
            //16-bit signed value 
            param["type"] = "short";
            break;
        case ValueID::ValueType_Int:
            //32-bit signed value 
            param["type"] = "int";
            break;
        case ValueID::ValueType_Button:
            //A write-only value that is the equivalent of pressing a button to send a command to a device
            param["type"] = "button";
            param["invalid"] = true;
            break;
        case ValueID::ValueType_List:
            //List from which one item can be selected 
            param["type"] = "list";

            //get list items
            Manager::Get()->GetValueListItems(*valueID, &ozwItems);
901
            for( auto it3 = ozwItems.begin(); it3 != ozwItems.end(); it3++ )
902
            {
903
                items.append(*it3);
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
            }
            param["items"] = items;
            break;
        case ValueID::ValueType_Schedule:
            //Complex type used with the Climate Control Schedule command class
            param["type"] = "notsupported";
            param["invalid"] = true;
            break;
        case ValueID::ValueType_String:
            //Text string
            param["type"] = "string";
            break;
        case ValueID::ValueType_Raw:
            //A collection of bytes 
            param["type"] = "notsupported";
            param["invalid"] = true;
            break;
        default:
            param["invalid"] = true;
            param["type"] = "unknown";
    }

    //get parameter value
927
    std::string currentValue = "";
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    if( Manager::Get()->GetValueAsString(*valueID, &currentValue) )
    {
        param["currentvalue"] = currentValue;
    }
    else
    {
        //unable to get current value
        param["invalid"] = true;
        param["currentvalue"] = "";
    }

    //get other infos
    param["label"] = Manager::Get()->GetValueLabel(*valueID);
    param["units"] = Manager::Get()->GetValueUnits(*valueID);
    param["help"] = Manager::Get()->GetValueHelp(*valueID);
    param["min"] = Manager::Get()->GetValueMin(*valueID);
    param["max"] = Manager::Get()->GetValueMax(*valueID);
    param["readonly"] = Manager::Get()->IsValueReadOnly(*valueID);
    param["commandclassid"] = COMMAND_CLASS_CONFIGURATION;
    param["instance"] = valueID->GetInstance();
    param["index"] = valueID->GetIndex();


    return param;
}

/**
 * Get COMMAND_CLASS_WAKE_UP parameter
 * @return map containing all parameter infos
 */
958
Json::Value AgoZwave::getCommandClassWakeUpParameter(OpenZWave::ValueID* valueID)
959
{
960
    Json::Value param(Json::objectValue);
961
    std::string currentValue = "";
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

    if( Manager::Get()->GetValueAsString(*valueID, &currentValue) )
    {
        //everything's good, fill param
        param["currentvalue"] = currentValue;
        param["type"] = "int";
        param["label"] = Manager::Get()->GetValueLabel(*valueID);
        param["units"] = Manager::Get()->GetValueUnits(*valueID);
        param["help"] = Manager::Get()->GetValueHelp(*valueID);
        param["readonly"] = Manager::Get()->IsValueReadOnly(*valueID);
        param["min"] = Manager::Get()->GetValueMin(*valueID);
        param["max"] = Manager::Get()->GetValueMax(*valueID);
        param["invalid"] = 0;
        param["commandclassid"] = COMMAND_CLASS_WAKE_UP;
        param["instance"] = valueID->GetInstance();
        param["index"] = valueID->GetIndex();
    }

    return param;
}

/**
 * Set device parameter
 * @return true if parameter found and set successfully
 */
987
bool AgoZwave::setCommandClassParameter(uint32 homeId, uint8 nodeId, uint8 commandClassId, uint8 index, std::string newValue)
988 989 990 991 992 993 994 995
{
    bool result = false;

    //get node info
    NodeInfo* nodeInfo = getNodeInfo(homeId, nodeId);

    if( nodeInfo!=NULL )
    {
996
        for( auto it=nodeInfo->m_values.begin(); it!=nodeInfo->m_values.end(); it++ )
997 998 999 1000 1001 1002 1003
        {
            AGO_DEBUG() << "--> commandClassId=" << getHRCommandClassId(it->GetCommandClassId()) << " index=" << std::dec << (int)it->GetIndex();
            if( it->GetCommandClassId()==commandClassId && it->GetIndex()==index )
            {
                //parameter found

                //check if value has been modified
1004
                std::string oldValue;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
                Manager::Get()->GetValueAsString(*it, &oldValue);

                if( oldValue!=newValue )
                {                  
                    if( it->GetType()==ValueID::ValueType_List )
                    {
                        //set list value
                        result = Manager::Get()->SetValueListSelection(*it, newValue);
                        if( !result )
                        {
                            AGO_ERROR() << "Unable to set value list selection with newValue=" << newValue;
                        }
                    }
                    else
                    {
                        //set value
                        result = Manager::Get()->SetValue(*it, newValue);
                        if( !result )
                        {
                            AGO_ERROR() << "Unable to set value with newValue=" << newValue;
                        }
                    }
                }
                else
                {
                    //oldValue == newValue. Nothing done but return true anyway
                    AGO_DEBUG() << "setCommandClassParameter: try to set parameter with same value [" << oldValue << "=" << newValue << "]. Nothing done.";
                    result = true;
                }

                //stop statement
                break;
            }
        }
    }

    //handle error
    if( result==false )
    {
        if( nodeInfo==NULL )
        {
            //node not found!
1047
            AGO_ERROR() << "Node not found! (homeId=" << homeId << " nodeId=" << (int)nodeId << " commandClassId=" << (int)commandClassId << " index=" << (int)index << ")";
1048 1049 1050 1051
        }
        else
        {
            //ValueID not found!
1052
            AGO_ERROR() << "ValueID not found! (homeId=" << homeId << " nodeId=" << (int)nodeId << " commandClassId=" << (int)commandClassId << " index=" << (int)index << ")";
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
        }
    }

    return result;
}

/**
 * Request config parameters for all nodes
 */
void AgoZwave::requestAllNodeConfigParameters()
{
    for( list<NodeInfo*>::iterator it=g_nodes.begin(); it!=g_nodes.end(); ++it )
    {
        NodeInfo* nodeInfo = *it;
        Manager::Get()->RequestAllConfigParams(nodeInfo->m_homeId, nodeInfo->m_nodeId);
    }
}

1071

1072 1073 1074 1075
//-----------------------------------------------------------------------------
// <OnNotification>
// Callback that is triggered when a value, group or node changes
//-----------------------------------------------------------------------------
1076 1077
void AgoZwave::_OnNotification (Notification const* _notification)
{
1078
    Json::Value eventmap;
1079 1080 1081
    // Must do this inside a critical section to avoid conflicts with the main thread
    pthread_mutex_lock( &g_criticalSection );

1082
    AGO_DEBUG() << "Notification " << getHRNotification(_notification->GetType()) << " received";
1083

1084 1085 1086
    switch( _notification->GetType() )
    {
        case Notification::Type_ValueAdded:
1087
        {
1088
            if( NodeInfo* nodeInfo = getNodeInfo( _notification ) )
1089
            {
1090 1091 1092 1093 1094 1095
                // Add the new value to our list
                nodeInfo->m_values.push_back( _notification->GetValueID() );
                uint8 basic = Manager::Get()->GetNodeBasic(_notification->GetHomeId(),_notification->GetNodeId());
                uint8 generic = Manager::Get()->GetNodeGeneric(_notification->GetHomeId(),_notification->GetNodeId());
                /*uint8 specific =*/ Manager::Get()->GetNodeSpecific(_notification->GetHomeId(),_notification->GetNodeId());
                ValueID id = _notification->GetValueID();
1096 1097
                std::string label = Manager::Get()->GetValueLabel(id);
                std::stringstream tempstream;
1098 1099 1100
                tempstream << (int) _notification->GetNodeId();
                tempstream << "/";
                tempstream << (int) id.GetInstance();
1101
                std::string nodeinstance = tempstream.str();
1102 1103
                tempstream << "-";
                tempstream << label;
1104
                std::string tempstring = tempstream.str();
1105
                ZWaveNode *device;
1106

1107
                if (id.GetGenre() == ValueID::ValueGenre_Config)
1108
                {
1109 1110 1111 1112 1113 1114 1115 1116
                    AGO_INFO() << "Configuration parameter Value Added: Home=" << std::hex <<  _notification->GetHomeId()
                        << " Node=" << std::dec << (int) _notification->GetNodeId()
                        << " Genre=" << std::dec << (int) id.GetGenre()
                        << " Class=" << getHRCommandClassId(id.GetCommandClassId())
                        << " Instance=" << (int)id.GetInstance()
                        << " Index=" << (int)id.GetIndex()
                        << " Type=" << (int)id.GetType()
                        << " Label=" << label;
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
                }
                else if (basic == BASIC_TYPE_CONTROLLER)
                {
                    if ((device = devices.findId(nodeinstance)) != NULL)
                    {
                        device->addValue(label, id);
                        device->setDevicetype("remote");
                    }
                    else
                    {
1127
                        device = new ZWaveNode(nodeinstance, "remote");
1128 1129
                        device->addValue(label, id);
                        devices.add(device);
1130
                        AGO_DEBUG() << "Controller: add new remote [" << device->getId() << ", " << device->getDevicetype() << "]";
1131
                        agoConnection->addDevice(device->getId(), device->getDevicetype());
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
                    }
                }
                else
                {
                    switch (generic)
                    {
                        case GENERIC_TYPE_THERMOSTAT:
                            if ((device = devices.findId(nodeinstance)) == NULL)
                            {
                                device = new ZWaveNode(nodeinstance, "thermostat");
                                devices.add(device);
1143
                                AGO_DEBUG() << "Thermostat: add new thermostat [" << device->getId() << ", " << device->getDevicetype() << "]";
1144
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1145 1146 1147 1148 1149 1150 1151
                            }
                            break;
                        case GENERIC_TYPE_SWITCH_MULTILEVEL:
                            if ((device = devices.findId(nodeinstance)) == NULL)
                            {
                                device = new ZWaveNode(nodeinstance, "dimmer");
                                devices.add(device);
1152
                                AGO_DEBUG() << "Switch multilevel: add new dimmer [" << device->getId() << ", " << device->getDevicetype() << "]";
1153
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
                            }
                            break;
                    }

                    switch(id.GetCommandClassId())
                    {
                        case COMMAND_CLASS_CONFIGURATION:
                            AGO_DEBUG() << "COMMAND_CLASS_CONFIGURATION received";
                            break;
                        case COMMAND_CLASS_BATTERY:
                            if( label=="Battery Level" )
                            {
1166
                                if ((device = devices.findId(tempstring)) != NULL)
1167 1168 1169 1170 1171 1172
                                {
                                    AGO_DEBUG() << "Battery: append batterysensor [" << label << "]";
                                    device->addValue(label, id);
                                }
                                else
                                {
1173
                                    device = new ZWaveNode(tempstring, "batterysensor");
1174
                                    device->addValue(label, id);
1175
                                    devices.add(device);
1176
                                    AGO_DEBUG() << "Battery: add new batterysensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1177
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1178
                                }
1179 1180
                            }
                            break;
Harald Klein's avatar
Harald Klein committed
1181 1182 1183 1184
                        case COMMAND_CLASS_COLOR:
                            if (label == "Color")
                            {
                                if ((device = devices.findId(nodeinstance)) != NULL)
1185
                                {
Harald Klein's avatar
Harald Klein committed
1186 1187
                                    device->addValue(label, id);
                                    device->setDevicetype("dimmerrgb");
1188
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
Harald Klein's avatar
Harald Klein committed
1189 1190 1191 1192 1193 1194 1195
                                }
                                else
                                {
                                    device = new ZWaveNode(nodeinstance, "dimmerrgb");
                                    device->addValue(label, id);
                                    devices.add(device);
                                    AGO_DEBUG() << "Color: add new dimmerrgb [" << device->getId() << ", " << device->getDevicetype() << "]";
1196
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
Harald Klein's avatar
Harald Klein committed
1197 1198 1199
                                }
                            }
                            break;
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
                        case COMMAND_CLASS_SWITCH_MULTILEVEL:
                            if (label == "Level")
                            {
                                if ((device = devices.findId(nodeinstance)) != NULL)
                                {
                                    device->addValue(label, id);
                                    // device->setDevicetype("dimmer");
                                }
                                else
                                {
1210
                                    device = new ZWaveNode(nodeinstance, "dimmer");
1211
                                    device->addValue(label, id);
1212
                                    devices.add(device);
1213
                                    AGO_DEBUG() << "Switch multilevel: add new dimmer [" << device->getId() << ", " << device->getDevicetype() << "]";
1214
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1215
                                }
1216 1217 1218 1219 1220 1221 1222 1223 1224
                                // Manager::Get()->EnablePoll(id);
                            }
                            break;
                        case COMMAND_CLASS_SWITCH_BINARY:
                            if (label == "Switch")
                            {
                                if ((device = devices.findId(nodeinstance)) != NULL)
                                {
                                    device->addValue(label, id);
1225
                                }
1226 1227
                                else
                                {
1228
                                    device = new ZWaveNode(nodeinstance, "switch");
1229 1230
                                    device->addValue(label, id);
                                    devices.add(device);
1231
                                    AGO_DEBUG() << "Switch binary: add new switch [" << device->getId() << ", " << device->getDevicetype() << "]";
1232
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1233
                                }
1234 1235 1236 1237 1238 1239 1240
                                // Manager::Get()->EnablePoll(id);
                            }
                            break;
                        case COMMAND_CLASS_SENSOR_BINARY:
                            if (label == "Sensor")
                            {
                                if ((device = devices.findId(tempstring)) != NULL)
1241 1242 1243 1244 1245
                                {
                                    device->addValue(label, id);
                                }
                                else
                                {
1246
                                    device = new ZWaveNode(tempstring, "binarysensor");
1247 1248
                                    device->addValue(label, id);
                                    devices.add(device);
1249
                                    AGO_DEBUG() << "Sensor binary: add new binarysensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1250
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1251 1252
                                }
                                // Manager::Get()->EnablePoll(id);
1253 1254 1255 1256 1257
                            }
                            break;
                        case COMMAND_CLASS_SENSOR_MULTILEVEL:
                            if (label == "Luminance")
                            {
1258
                                device = new ZWaveNode(tempstring, "brightnesssensor");
1259 1260
                                device->addValue(label, id);
                                devices.add(device);
1261
                                AGO_DEBUG() << "Sensor multilevel: add new brightnesssensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1262
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1263
                            }
Harald Klein's avatar
Harald Klein committed
1264 1265 1266 1267 1268 1269
                            else if (label == "Ultraviolet")
                            {
                                device = new ZWaveNode(tempstring, "uvsensor");
                                device->addValue(label, id);
                                devices.add(device);
                                AGO_DEBUG() << "Sensor multilevel: add new uvsensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1270
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
Harald Klein's avatar
Harald Klein committed
1271
                            }
1272 1273 1274 1275 1276 1277
                            else if (label == "Temperature")
                            {
                                if (generic == GENERIC_TYPE_THERMOSTAT)
                                {
                                    if ((device = devices.findId(nodeinstance)) != NULL)
                                    {
1278 1279
                                        device->addValue(label, id);
                                    }
1280 1281
                                    else
                                    {
1282
                                        device = new ZWaveNode(nodeinstance, "thermostat");
1283 1284
                                        device->addValue(label, id);
                                        devices.add(device);
1285
                                        AGO_DEBUG() << "Sensor multilevel: add new thermostat [" << device->getId() << ", " << device->getDevicetype() << "]";
1286
                                        agoConnection->addDevice(device->getId(), device->getDevicetype());
1287 1288
                                    }
                                }
1289 1290
                                else
                                {
1291
                                    device = new ZWaveNode(tempstring, "temperaturesensor");
1292 1293
                                    device->addValue(label, id);
                                    devices.add(device);
1294
                                    AGO_DEBUG() << "Sensor multilevel: add new temperaturesensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1295
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1296 1297
                                }
                            }
1298 1299 1300 1301 1302 1303
                            else if( label.find("Humidity")!=std::string::npos )
                            {
                                device = new ZWaveNode(tempstring, "humiditysensor");
                                device->addValue(label, id);
                                devices.add(device);
                                AGO_DEBUG() << "Sensor multilevel: add new humiditysensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1304
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1305
                            }
1306 1307
                            else
                            {
1308
                                AGO_WARNING() << "Unhandled label for SENSOR_MULTILEVEL. Adding generic multilevelsensor for label: " << label;
1309 1310 1311 1312 1313 1314
                                if ((device = devices.findId(nodeinstance)) != NULL)
                                {
                                    device->addValue(label, id);
                                }
                                else
                                {
1315
                                    device = new ZWaveNode(nodeinstance, "multilevelsensor");
1316 1317
                                    device->addValue(label, id);
                                    devices.add(device);
1318
                                    AGO_DEBUG() << "Sensor multilevel: add new multisensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1319
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1320
                                }
1321 1322 1323 1324 1325 1326
                            }
                            // Manager::Get()->EnablePoll(id);
                            break;
                        case COMMAND_CLASS_METER:
                            if (label == "Power")
                            {
1327
                                device = new ZWaveNode(tempstring, "powermeter");
1328 1329
                                device->addValue(label, id);
                                devices.add(device);
1330
                                AGO_DEBUG() << "Meter: add new powermeter [" << device->getId() << ", " << device->getDevicetype() << "]";
1331
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1332 1333 1334
                            }
                            else if (label == "Energy")
                            {
1335
                                device = new ZWaveNode(tempstring, "energymeter");
1336 1337
                                device->addValue(label, id);
                                devices.add(device);
1338
                                AGO_DEBUG() << "Meter: add new energymeter [" << device->getId() << ", " << device->getDevicetype() << "]";
1339
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1340 1341 1342 1343 1344 1345
                            }
                            else
                            {
                                AGO_WARNING() << "unhandled label for CLASS_METER. Adding generic multilevelsensor for label: " << label;
                                if ((device = devices.findId(nodeinstance)) != NULL)
                                {
1346
                                    device->addValue(label, id);
1347 1348 1349
                                }
                                else
                                {
1350
                                    device = new ZWaveNode(nodeinstance, "multilevelsensor");
1351 1352
                                    device->addValue(label, id);
                                    devices.add(device);
1353
                                    AGO_DEBUG() << "Meter: add new multilevelsensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1354
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1355
                                }
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
                            }
                            // Manager::Get()->EnablePoll(id);
                            break;
                        case COMMAND_CLASS_BASIC_WINDOW_COVERING:
                            // if (label == "Open") {
                            if ((device = devices.findId(nodeinstance)) != NULL)
                            {
                                device->addValue(label, id);
                                device->setDevicetype("drapes");
                            }
                            else
                            {
1368
                                device = new ZWaveNode(nodeinstance, "drapes");
1369 1370
                                device->addValue(label, id);
                                devices.add(device);
1371
                                AGO_DEBUG() << "Basic window covering: add new drapes [" << device->getId() << ", " << device->getDevicetype() << "]";
1372
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1373 1374
                            }
                            // Manager::Get()->EnablePoll(id);
1375
                            //}
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
                            break;
                        case COMMAND_CLASS_THERMOSTAT_SETPOINT:
                        case COMMAND_CLASS_THERMOSTAT_MODE:
                        case COMMAND_CLASS_THERMOSTAT_FAN_MODE:
                        case COMMAND_CLASS_THERMOSTAT_FAN_STATE:
                        case COMMAND_CLASS_THERMOSTAT_OPERATING_STATE:
                            AGO_DEBUG() << "adding thermostat label: " << label;
                            if ((device = devices.findId(nodeinstance)) != NULL)
                            {
                                device->addValue(label, id);
                                device->setDevicetype("thermostat");
                            }
                            else
                            {
1390
                                device = new ZWaveNode(nodeinstance, "thermostat");
1391 1392
                                device->addValue(label, id);
                                devices.add(device);
1393
                                AGO_DEBUG() << "Thermostat: add new thermostat [" << device->getId() << ", " << device->getDevicetype() << "]";
1394
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1395 1396
                            }
                            break;
1397
                        case COMMAND_CLASS_ALARM:
1398 1399 1400 1401 1402
                        case COMMAND_CLASS_SENSOR_ALARM:
                            if (label == "Sensor" || label == "Alarm Level" || label == "Flood")
                            {
                                if ((device = devices.findId(tempstring)) != NULL)
                                {
1403
                                    device->addValue(label, id);
1404 1405 1406
                                }
                                else
                                {
1407
                                    device = new ZWaveNode(tempstring, "binarysensor");
1408 1409
                                    device->addValue(label, id);
                                    devices.add(device);
1410
                                    AGO_DEBUG() << "Alarm: add new binarysensor [" << device->getId() << ", " << device->getDevicetype() << "]";
1411
                                    agoConnection->addDevice(device->getId(), device->getDevicetype());
1412
                                }
1413 1414 1415
                                // Manager::Get()->EnablePoll(id);
                            }
                            break;
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
                        case COMMAND_CLASS_DOOR_LOCK:
                            AGO_DEBUG() << "adding door lock label: " << label;
                            if ((device = devices.findId(nodeinstance)) != NULL)
                            {
                                device->addValue(label, id);
                                device->setDevicetype("doorlock");
                            }
                            else
                            {
                                device = new ZWaveNode(nodeinstance, "doorlock");
                                device->addValue(label, id);
                                devices.add(device);
                                AGO_DEBUG() << "Doorlock: add new doorlock [" << device->getId() << ", " << device->getDevicetype() << "]";
1429
                                agoConnection->addDevice(device->getId(), device->getDevicetype());
1430 1431
                            }
                            break;
1432
                        default:
1433 1434 1435 1436 1437 1438 1439 1440
                            AGO_INFO() << "Notification: Unassigned Value Added Home=" << std::hex << _notification->GetHomeId()
                            << " Node=" << std::dec << (int)_notification->GetNodeId()
                            << " Genre=" << std::dec << (int)id.GetGenre()
                            << " Class=" << getHRCommandClassId(id.GetCommandClassId())
                            << " Instance=" << std::dec << (int)id.GetInstance()
                            << " Index=" << std::dec << (int)id.GetIndex()
                            << " Type=" << (int)id.GetType()
                            << " Label: " << label;
1441

1442 1443
                    }
                }
1444 1445 1446 1447 1448 1449 1450
            }else{
                ValueID id = _notification->GetValueID();
                string label = Manager::Get()->GetValueLabel(id);
                AGO_DEBUG() << "ValueAdded for unknown node Home="
                    << _notification->GetHomeId()
                    << ", Node=" <<  (int)_notification->GetNodeId()
                    << " Label= " << label;
1451
            }
1452 1453
            break;
        }
1454
        case Notification::Type_ValueRemoved:
1455
        {
1456
            if( NodeInfo* nodeInfo = getNodeInfo( _notification ) )
1457
            {
1458 1459
                // Remove the value from out list
                for( list<ValueID>::iterator it = nodeInfo->m_values.begin(); it != nodeInfo->m_values.end(); ++it )
1460
                {
1461
                    if( (*it) == _notification->GetValueID() )
1462
                    {
1463 1464
                        nodeInfo->m_values.erase( it );
                        break;
1465 1466 1467
                    }
                }
            }
1468 1469 1470 1471
            break;
        }

        case Notification::Type_ValueRefreshed:
1472
            AGO_DEBUG() << "Notification='ValueRefreshed'";
1473
            break;
1474 1475

        case Notification::Type_ValueChanged:
1476
        {
1477
            if( /*NodeInfo* nodeInfo =*/ getNodeInfo( _notification ) )
1478
            {
1479 1480 1481 1482
                // One of the node values has changed
                // TBD...
                // nodeInfo = nodeInfo;
                ValueID id = _notification->GetValueID();
1483
                std::string str;
1484 1485 1486 1487 1488
                AGO_INFO() << "Notification='Value Changed' Home=" << std::hex << _notification->GetHomeId()
                    << " Node=" << std::dec << (int)_notification->GetNodeId()
                    << " Genre=" << std::dec << (int)id.GetGenre()
                    << " Class=" << getHRCommandClassId(id.GetCommandClassId()) << std::dec
                    << " Type=" << id.GetType();
1489 1490

                if (Manager::Get()->GetValueAsString(id, &str))
1491
                {
1492
                    ZWaveNode* device = NULL;
1493
                    Json::Value cachedValue = parseToJson(str);
1494
                    valueCache[id] = cachedValue;
1495 1496
                    std::string label = Manager::Get()->GetValueLabel(id);
                    std::string units = Manager::Get()->GetValueUnits(id);
1497 1498

                    // TODO: send proper types and don't convert everything to string
1499 1500
                    std::string level = str;
                    std::string eventtype = "";
1501 1502 1503 1504 1505 1506 1507 1508 1509
                    if (str == "True")
                    {
                        level="255";
                    }
                    if (str == "False")
                    {
                        level="0";
                    }
                    AGO_DEBUG() << "Value=" << str << " Label=" << label << " Units=" << units;
1510 1511 1512 1513
                    if ((label == "Basic") || (label == "Switch") || (label == "Level"))
                    {
                        eventtype="event.device.statechanged";
                    }
1514
                    else if (label == "Luminance")
1515 1516 1517
                    {
                        eventtype="event.environment.brightnesschanged";
                    }
Harald Klein's avatar
Harald Klein committed
1518 1519 1520 1521
                    else if (label == "Ultraviolet")
                    {
                        eventtype="event.environment.ultravioletchanged";
                    }
1522
                    else if (label == "Temperature")
1523 1524
                    {
                        eventtype="event.environment.temperaturechanged";
1525 1526 1527 1528 1529 1530
                        //fix unit
                        if( units=="F" )
                        {
                            units = "degF";
                        }
                        else
1531
                        {
Tang's avatar
Tang committed
1532
                            units = "degC";
1533 1534 1535 1536
                        }
                        //convert value according to configured metrics
                        if (units=="F" && unitsystem==0)
                        {
1537
                            str = std::to_string((std::stof(str)-32)*5/9);
1538
                            level = str;
1539
                        }
1540 1541
                        else if (units =="C" && unitsystem==1)
                        {
1542
                            str = std::to_string(std::stof(str)*9/5 + 32);
1543
                            level = str;
1544
                        }
1545
                    }
1546
                    else if (label == "Relative Humidity")
1547 1548 1549
                    {
                        eventtype="event.environment.humiditychanged";
                    }
1550
                    else if (label == "Battery Level")
1551 1552 1553
                    {
                        eventtype="event.device.batterylevelchanged";
                    }
1554
                    else if (