示例#1
0
KLCSC_DECL KLSTD_NORETURN void KLERR_throwLocError(
    const ErrLocAdapt&  locinfo,
	const wchar_t*	    szwModule,
	int				    nId,
	const char*		    szaFile, 
	int				    nLine,
	const wchar_t*	    szwMessage ...)
{
    ErrorPtr pError = CreateError(
                    &locinfo, 
                    szwModule, 
                    nId, 
                    szaFile, 
                    nLine, 
                    szwMessage);
    try
    {
	    va_list lst;
	    va_start(lst, szwMessage);
	    pError->SetMessageParams(lst);
        va_end(lst);
    }
    catch(std::exception& err)
    {
        KLERR_TRACE_UNEXPECTED();
    };
	throw pError.Detach();
};
示例#2
0
ErrorPtr JsonRpcComm::sendError(const char *aJsonRpcId, ErrorPtr aErrorToSend)
{
  if (!Error::isOK(aErrorToSend)) {
    return sendError(aJsonRpcId, (uint32_t)aErrorToSend->getErrorCode(), aErrorToSend->getErrorMessage());
  }
  return ErrorPtr();
}
示例#3
0
 void initDiscovery()
 {
   // get discovery params
   // - host name
   string s;
   string hostname;
   if (!getStringOption("hostname", hostname)) {
     // none specified, create default
     hostname = string_format("plan44-vdcd-%s", p44VdcHost->getDsUid().getString().c_str());
   }
   // start DS advertising if not disabled
   if (!getOption("nodiscovery")) {
     // start the basic service
     ErrorPtr err = DiscoveryManager::sharedDiscoveryManager().start(
       hostname.c_str()
     );
     if (Error::isOK(err)) {
       // started ok, set discovery params
       int sshPort = 0;
       getIntOption("sshport", sshPort);
       // start discovery manager
       DiscoveryManager::sharedDiscoveryManager().advertiseDS(
         p44VdcHost,
         getOption("noauto"),
         p44VdcHost->webUiPort,
         p44VdcHost->webUiPath,
         sshPort
       );
     }
     else {
       LOG(LOG_ERR, "**** Cannot start discovery manager: %s", err->description().c_str());
     }
   }
 }
示例#4
0
文件: vdcapi.cpp 项目: chhitz/vdcd
ErrorPtr VdcApiRequest::sendError(ErrorPtr aErrorToSend)
{
    if (!Error::isOK(aErrorToSend)) {
        return sendError((uint32_t)aErrorToSend->getErrorCode(), aErrorToSend->getErrorMessage());
    }
    return ErrorPtr();
}
示例#5
0
bool FdComm::transmitString(const string &aString)
{
  ErrorPtr err;
  size_t res = transmitBytes(aString.length(), (uint8_t *)aString.c_str(), err);
  if (!Error::isOK(err)) {
    FOCUSLOG("FdComm: Error sending data: %s", err->description().c_str());
  }
  return Error::isOK(err) && res==aString.length(); // ok if no error and all bytes sent
}
示例#6
0
void SerialComm::reconnectHandler()
{
  if (reconnecting) {
    ErrorPtr err = establishConnection();
    if (!Error::isOK(err)) {
      LOG(LOG_ERR, "SerialComm: re-connect failed: %s -> retry again later", err->description().c_str());
      reconnecting = true;
      MainLoop::currentMainLoop().executeOnce(boost::bind(&SerialComm::reconnectHandler, this), 15*Second);
    }
    else {
      LOG(LOG_NOTICE, "SerialComm: successfully reconnected to %s", connectionPath.c_str());
    }
  }
}
示例#7
0
文件: vdcapi.cpp 项目: plan44/p44vdc
ErrorPtr VdcApiRequest::sendError(ErrorPtr aErrorToSend)
{
  if (!Error::isOK(aErrorToSend)) {
    VdcApiErrorPtr ve = boost::dynamic_pointer_cast<VdcApiError>(aErrorToSend);
    if (ve) {
      // special VdcApiError, has extra user facing information
      return sendError((uint32_t)aErrorToSend->getErrorCode(), aErrorToSend->getErrorMessage(), ApiValuePtr(), ve->getErrorType(), ve->getUserFacingMessage());
    }
    else {
      return sendError((uint32_t)aErrorToSend->getErrorCode(), aErrorToSend->getErrorMessage());
    }
  }
  return ErrorPtr();
}
示例#8
0
void DaliDeviceContainer::testRWResponse(CompletedCB aCompletedCB, DaliAddress aShortAddr, uint8_t aTestByte, bool aNoOrTimeout, uint8_t aResponse, ErrorPtr aError)
{
  if (Error::isOK(aError) && !aNoOrTimeout && aResponse==aTestByte) {
    LOG(LOG_NOTICE,"  - sent 0x%02X, received 0x%02X\n",aTestByte, aResponse, aNoOrTimeout);
    // successfully read back same value from DTR as sent before
    // - check if more tests
    switch (aTestByte) {
      case 0x55: aTestByte = 0xAA; break; // next test: inverse
      case 0xAA: aTestByte = 0x00; break; // next test: all 0
      case 0x00: aTestByte = 0xFF; break; // next test: all 1
      case 0xFF: aTestByte = 0xF0; break; // next test: half / half
      case 0xF0: aTestByte = 0x0F; break; // next test: half / half inverse
      default:
        // all tests done
        aCompletedCB(aError);
        // turn off lights
        daliComm->daliSendDirectPower(DaliBroadcast, 0); // off
        return;
    }
    // launch next test
    testRW(aCompletedCB, aShortAddr, aTestByte);
  }
  else {
    // not ok
    if (Error::isOK(aError) && aNoOrTimeout) aError = ErrorPtr(new DaliCommError(DaliCommErrorMissingData));
    // report
    LOG(LOG_ERR,"DALI self test error: sent 0x%02X, error: %s\n",aTestByte, aError->description().c_str());
    aCompletedCB(aError);
  }
}
示例#9
0
void SsdpSearch::socketStatusHandler(ErrorPtr aError)
{
  FOCUSLOG("SSDP socket status: %s", aError ? aError->description().c_str() : "<no error>");
  if (Error::isOK(aError)) {
    FOCUSLOG("### sending UDP M-SEARCH");
    // unregister socket status handler (or we'll get called when connection closes)
    setConnectionStatusHandler(NULL);
    // send search request
    string ssdpSearch = string_format(
      "M-SEARCH * HTTP/1.1\n"
      "HOST: %s:%s\n"
      "MAN: \"ssdp:discover\"\n"
      "MX: %d\n"
      "ST: %s\n",
      SSDP_BROADCAST_ADDR,
      SSDP_PORT,
      SSDP_MX,
      searchTarget.c_str()
    );
    transmitString(ssdpSearch);
    // start timer (wait 1.5 the MX for answers)
    timeoutTicket = MainLoop::currentMainLoop().executeOnce(boost::bind(&SsdpSearch::searchTimedOut, this), SSDP_MX*1500*MilliSecond);
  }
  else {
    // error starting search
    if (searchResultHandler) {
      searchResultHandler(this, aError);
    }
  }
}
示例#10
0
文件: huecomm.cpp 项目: chhitz/vdcd
 void handleCreateUserAnswer(JsonObjectPtr aJsonResponse, ErrorPtr aError)
 {
   if (Error::isOK(aError)) {
     FOCUSLOG("Received success answer:\n%s", aJsonResponse->json_c_str());
     JsonObjectPtr s = HueComm::getSuccessItem(aJsonResponse);
     // apparently successful, extract user name
     if (s) {
       JsonObjectPtr u = s->get("username");
       if (u) {
         hueComm.userName = u->stringValue();
         hueComm.uuid = currentAuthCandidate->first;
         hueComm.baseURL = currentAuthCandidate->second;
         hueComm.apiReady = true; // can use API now
         FOCUSLOG("hue Bridge %s @ %s: successfully registered as user %s", hueComm.uuid.c_str(), hueComm.baseURL.c_str(), hueComm.userName.c_str());
         // successfully registered with hue bridge, let caller know
         callback(ErrorPtr());
         // done!
         keepAlive.reset(); // will delete object if nobody else keeps it
         return;
       }
     }
   }
   else {
     LOG(LOG_ERR, "hue Bridge: Error creating user: %s", aError->description().c_str());
   }
   // try next
   ++currentAuthCandidate;
   processCurrentAuthCandidate(); // process next, if any
 }
示例#11
0
bool SocketComm::connectionMonitorHandler(MLMicroSeconds aCycleStartTime, int aFd, int aPollFlags)
{
  ErrorPtr err;
  if ((aPollFlags & POLLOUT) && isConnecting) {
    // became writable, check status
    err = socketError(aFd);
  }
  else if (aPollFlags & POLLHUP) {
    err = ErrorPtr(new SocketCommError(SocketCommErrorHungUp, "Connection HUP while opening (= connection rejected)"));
  }
  else if (aPollFlags & POLLERR) {
    err = socketError(aFd);
  }
  // now check if successful
  if (Error::isOK(err)) {
    // successfully connected
    connectionOpen = true;
    isConnecting = false;
    currentAddressInfo = NULL; // no more addresses to check
    freeAddressInfo();
    LOG(LOG_DEBUG, "Connection to %s:%s established", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str());
    // call handler if defined
    if (connectionStatusHandler) {
      // connection ok
      connectionStatusHandler(this, ErrorPtr());
    }
    // let FdComm base class operate open connection (will install handlers)
    setFd(aFd);
  }
  else {
    // this attempt has failed, try next (if any)
    LOG(LOG_DEBUG, "- Connection attempt failed: %s", err->description().c_str());
    // this will return no error if we have another address to try
    err = connectNextAddress();
    if (err) {
      // no next attempt started, report error
      LOG(LOG_WARNING, "Connection to %s:%s failed: %s", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str(), err->description().c_str());
      if (connectionStatusHandler) {
        connectionStatusHandler(this, err);
      }
      freeAddressInfo();
      internalCloseConnection();
    }
  }
  // handled
  return true;
}
示例#12
0
void SocketComm::dataExceptionHandler(int aFd, int aPollFlags)
{
  SocketCommPtr keepMyselfAlive(this);
  DBGLOG(LOG_DEBUG, "SocketComm::dataExceptionHandler(fd==%d, pollflags==0x%X)", aFd, aPollFlags);
  if (!isClosing) {
    if (aPollFlags & POLLHUP) {
      // other end has closed connection
      // - report
      if (connectionStatusHandler) {
        // report reason for closing
        connectionStatusHandler(this, ErrorPtr(new SocketCommError(SocketCommErrorHungUp,"Connection closed (HUP)")));
      }
    }
    else if (aPollFlags & POLLIN) {
      // Note: on linux a socket closed server side does not return POLLHUP, but POLLIN with no data
      // alerted for read, but nothing to read any more: assume connection closed
      ErrorPtr err = socketError(aFd);
      if (Error::isOK(err))
        err = ErrorPtr(new SocketCommError(SocketCommErrorHungUp,"Connection closed (POLLIN but no data -> interpreted as HUP)"));
      DBGLOG(LOG_DEBUG, "Connection to %s:%s has POLLIN but no data; error: %s", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str(), err->description().c_str());
      // - report
      if (connectionStatusHandler) {
        // report reason for closing
        connectionStatusHandler(this, err);
      }
    }
    else if (aPollFlags & POLLERR) {
      // error
      ErrorPtr err = socketError(aFd);
      LOG(LOG_WARNING, "Connection to %s:%s reported error: %s", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str(), err->description().c_str());
      // - report
      if (connectionStatusHandler) {
        // report reason for closing
        connectionStatusHandler(this, err);
      }
    }
    else {
      // NOP
      return;
    }
    // - shut down (Note: if nobody else retains the connection except the server SocketComm, this will delete the connection)
    internalCloseConnection();
  }
}
示例#13
0
void Application::terminateAppWith(ErrorPtr aError)
{
  if (Error::isOK(aError)) {
    mainLoop.terminate(EXIT_SUCCESS);
  }
  else {
    LOG(LOG_ERR, "Terminating because of error: %s", aError->description().c_str());
    mainLoop.terminate(EXIT_FAILURE);
  }
}
示例#14
0
	KLSTD_NOTHROW KLCSC_DECL void SayFailure(
		int level,
		Error* perror,
		const wchar_t* module,
		const char* file,
		int line) throw()
	{
        int nTraceLevel = 0;
        if(KLSTD::IsTraceStarted(&nTraceLevel) && nTraceLevel >= level)
        {
		    try
            {
			    if(!perror)
                {
                    Trace(
					    level,
					    KLCS_MODULENAME,
					    L"Unknown error was caught in module \"%ls\" in file \"%hs\" on line %d\n",
					    module,
					    file,
					    line);
                }
			    else
                {
                    ErrorPtr pError = perror;
                    for( size_t i = 0; pError; ++i )
                    {
                        KLSTD::klwstr_t wstrLoc;
                        KLERR_LocFormatErrorString(pError, wstrLoc.outref());
                        Trace(
					        level,
					        KLCS_MODULENAME,
					        L"#%u, Error was caught in module \"%ls\" in file \"%hs\" on line %d."
					        L" Error params: (%u/0x%X (\"%ls\"), \"%ls\", \"%hs\", %d)\n\tError loc: '%ls'.\n",
                            (i+1),
					        module,
					        file,
					        line,
					        pError->GetId(),
					        pError->GetErrorSubcode(),
					        pError->GetMsg(),
					        pError->GetModuleName(),
					        pError->GetFileName(),
					        pError->GetLine(),
                            wstrLoc.c_str());
                        ;
                        KLERR::ErrorPtr pOldErr = pError; 
                        pError = NULL;
                        pOldErr->GetError2()->GetPreviousError(&pError);
                    };
                };
            }
            catch(std::exception& err)
            {
                KLERR_TRACE_UNEXPECTED();
            };
        };
	};
示例#15
0
void EnoceanDeviceContainer::handleRadioPacket(Esp3PacketPtr aEsp3PacketPtr, ErrorPtr aError)
{
  if (aError) {
    LOG(LOG_INFO, "Radio packet error: %s\n", aError->description().c_str());
    return;
  }
  // check learning mode
  if (learningMode) {
    // no learn/unlearn actions detected so far
    // - check if we know that device address already. If so, it is a learn-out
    bool learnIn = enoceanDevices.find(aEsp3PacketPtr->radioSender())==enoceanDevices.end();
    // now add/remove the device (if the action is a valid learn/unlearn)
    // detect implicit (RPS) learn in only with sufficient radio strength (or explicit override of that check),
    // explicit ones are always recognized
    if (aEsp3PacketPtr->eepHasTeachInfo(disableProximityCheck ? 0 : MIN_LEARN_DBM, false)) {
      LOG(LOG_NOTICE, "Received EnOcean learn packet while learn mode enabled: %s\n", aEsp3PacketPtr->description().c_str());
      // This is actually a valid learn action
      ErrorPtr learnStatus;
      if (learnIn) {
        // new device learned in, add logical devices for it
        int numNewDevices = EnoceanDevice::createDevicesFromEEP(this, aEsp3PacketPtr->radioSender(), aEsp3PacketPtr->eepProfile(), aEsp3PacketPtr->eepManufacturer());
        if (numNewDevices>0) {
          // successfully learned at least one device
          // - update learn status (device learned)
          getDeviceContainer().reportLearnEvent(true, ErrorPtr());
        }
      }
      else {
        // device learned out, un-pair all logical dS devices it has represented
        // but keep dS level config in case it is reconnected
        unpairDevicesByAddress(aEsp3PacketPtr->radioSender(), false);
        getDeviceContainer().reportLearnEvent(false, ErrorPtr());
      }
      // - only allow one learn action (to prevent learning out device when
      //   button is released or other repetition of radio packet)
      learningMode = false;
    } // learn action
  }
  else {
    // not learning mode, dispatch packet to all devices known for that address
    for (EnoceanDeviceMap::iterator pos = enoceanDevices.lower_bound(aEsp3PacketPtr->radioSender()); pos!=enoceanDevices.upper_bound(aEsp3PacketPtr->radioSender()); ++pos) {
      if (aEsp3PacketPtr->eepHasTeachInfo(MIN_LEARN_DBM, false) && aEsp3PacketPtr->eepRorg()!=rorg_RPS) {
        // learning packet in non-learn mode -> report as non-regular user action, may be attempt to identify a device
        // Note: RPS devices are excluded because for these all telegrams are regular regular user actions. signalDeviceUserAction() will be called
        //   from button
        if (getDeviceContainer().signalDeviceUserAction(*(pos->second), false)) {
          // consumed for device identification purposes, suppress further processing
          break;
        }
      }
      // handle regularily (might be RPS switch which does not have separate learn/action packets
      pos->second->handleRadioPacket(aEsp3PacketPtr);
    }
  }
}
示例#16
0
文件: dalicomm.cpp 项目: viiimmx/vdcd
bool DaliComm::isYes(bool aNoOrTimeout, uint8_t aResponse, ErrorPtr &aError, bool aCollisionIsYes)
{
  bool isYes = !aNoOrTimeout;
  if (aError && aCollisionIsYes && aError->isError(DaliCommError::domain(), DaliCommErrorDALIFrame)) {
    // framing error -> consider this a YES
    isYes = true;
    aError.reset(); // not considered an error when aCollisionIsYes is set
  }
  else if (isYes && !aCollisionIsYes) {
    // regular answer, must be DALIANSWER_YES to be a regular YES
    if (aResponse!=DALIANSWER_YES) {
      // invalid YES response
      aError.reset(new DaliCommError(DaliCommErrorInvalidAnswer));
    }
  }
  if (aError)
    return false; // real error, consider NO
  // return YES/NO
  return isYes;
}
示例#17
0
void MainLoop::childAnswerCollected(ExecCB aCallback, FdStringCollectorPtr aAnswerCollector, ErrorPtr aError)
{
  LOG(LOG_DEBUG, "childAnswerCollected: error = %s", Error::isOK(aError) ? "none" : aError->description().c_str());
  // close my end of the pipe
  aAnswerCollector->stopMonitoringAndClose();
  // now get answer
  string answer = aAnswerCollector->collectedData;
  LOG(LOG_DEBUG, "- Answer = %s", answer.c_str());
  // call back directly
  aCallback(cycleStartTime, aError, answer);
}
示例#18
0
void DaliDeviceContainer::deviceInfoReceived(DaliBusDeviceListPtr aBusDevices, DaliBusDeviceList::iterator aNextDev, CompletedCB aCompletedCB, DaliComm::DaliDeviceInfoPtr aDaliDeviceInfoPtr, ErrorPtr aError)
{
  bool missingData = aError && aError->isError(DaliCommError::domain(), DaliCommErrorMissingData);
  bool badData =
    aError &&
    (aError->isError(DaliCommError::domain(), DaliCommErrorBadChecksum) || aError->isError(DaliCommError::domain(), DaliCommErrorBadDeviceInfo));
  if (!aError || missingData || badData) {
    // no error, or error but due to missing or bad data -> device exists
    if (missingData) { LOG(LOG_INFO,"Device at shortAddress %d does not have device info\n",aDaliDeviceInfoPtr->shortAddress); }
    if (badData) { LOG(LOG_INFO,"Device at shortAddress %d does not have valid device info\n",aDaliDeviceInfoPtr->shortAddress); }
    // update device info entry in dali bus device
    (*aNextDev)->setDeviceInfo(*aDaliDeviceInfoPtr);
  }
  else {
    LOG(LOG_ERR,"Error reading device info: %s\n",aError->description().c_str());
    return aCompletedCB(aError);
  }
  // check next
  ++aNextDev;
  queryNextDev(aBusDevices, aNextDev, aCompletedCB, ErrorPtr());
}
示例#19
0
bool SerialComm::requestConnection()
{
  ErrorPtr err = establishConnection();
  if (!Error::isOK(err)) {
    if (!reconnecting) {
      LOG(LOG_ERR, "SerialComm: requestConnection() could not open connection now: %s -> entering background retry mode", err->description().c_str());
      reconnecting = true;
      MainLoop::currentMainLoop().executeOnce(boost::bind(&SerialComm::reconnectHandler, this), 5*Second);
    }
    return false;
  }
  return true;
}
示例#20
0
void P44VdcHost::sendCfgApiResponse(JsonCommPtr aJsonComm, JsonObjectPtr aResult, ErrorPtr aError)
{
  // create response
  JsonObjectPtr response = JsonObject::newObj();
  if (!Error::isOK(aError)) {
    // error, return error response
    response->add("error", JsonObject::newInt32((int32_t)aError->getErrorCode()));
    response->add("errormessage", JsonObject::newString(aError->getErrorMessage()));
    response->add("errordomain", JsonObject::newString(aError->getErrorDomain()));
    VdcApiErrorPtr ve = boost::dynamic_pointer_cast<VdcApiError>(aError);
    if (ve) {
      response->add("errortype", JsonObject::newInt32(ve->getErrorType()));
      response->add("userfacingmessage", JsonObject::newString(ve->getUserFacingMessage()));
    }
  }
  else {
    // no error, return result (if any)
    response->add("result", aResult);
  }
  LOG(LOG_DEBUG, "Config API response: %s", response->c_strValue());
  aJsonComm->sendMessage(response);
}
示例#21
0
文件: huecomm.cpp 项目: chhitz/vdcd
 void handleServiceDescriptionAnswer(const string &aResponse, ErrorPtr aError)
 {
   if (Error::isOK(aError)) {
     // show
     //FOCUSLOG("Received bridge description:\n%s", aResponse.c_str());
     FOCUSLOG("Received service description XML");
     // TODO: this is poor man's XML scanning, use some real XML parser eventually
     // do some basic checking for model
     size_t i = aResponse.find("<manufacturer>Royal Philips Electronics</manufacturer>");
     if (i!=string::npos) {
       // is from Philips
       // - check model number
       i = aResponse.find("<modelNumber>929000226503</modelNumber>"); // original 2012 hue bridge, FreeRTOS
       if (i==string::npos) i = aResponse.find("<modelNumber>BSB002</modelNumber>"); // hue bridge 2015 with homekit, Linux
       if (i!=string::npos) {
         // is the right model
         // - get base URL
         string token = "<URLBase>";
         i = aResponse.find(token);
         if (i!=string::npos) {
           i += token.size();
           size_t e = aResponse.find("</URLBase>", i);
           if (e!=string::npos) {
             // create the base address for the API
             string url = aResponse.substr(i,e-i) + "api";
             if (refind) {
               // that's my known hue bridge, save the URL and report success
               hueComm.baseURL = url; // save it
               hueComm.apiReady = true; // can use API now
               FOCUSLOG("pre-known hue Bridge %s found at %s", hueComm.uuid.c_str(), hueComm.baseURL.c_str());
               callback(ErrorPtr()); // success
               keepAlive.reset(); // will delete object if nobody else keeps it
               return; // done
             }
             else {
               // that's a hue bridge, remember it for trying to authorize
               FOCUSLOG("- Seems to be a hue bridge at %s", url.c_str());
               authCandidates[currentBridgeCandidate->first] = url;
             }
           }
         }
       }
     }
   }
   else {
     FOCUSLOG("Error accessing bridge description: %s", aError->description().c_str());
   }
   // try next
   ++currentBridgeCandidate;
   processCurrentBridgeCandidate(); // process next, if any
 }
示例#22
0
文件: huecomm.cpp 项目: chhitz/vdcd
 void bridgeDiscoveryHandler(SsdpSearchPtr aSsdpSearch, ErrorPtr aError)
 {
   if (Error::isOK(aError)) {
     // check device for possibility of being a hue bridge
     if (aSsdpSearch->server.find("IpBridge")!=string::npos) {
       LOG(LOG_INFO, "hue bridge candidate device found at %s, server=%s, uuid=%s", aSsdpSearch->locationURL.c_str(), aSsdpSearch->server.c_str(), aSsdpSearch->uuid.c_str());
       // put into map
       bridgeCandiates[aSsdpSearch->uuid.c_str()] = aSsdpSearch->locationURL.c_str();
     }
   }
   else {
     FOCUSLOG("discovery ended, error = %s (usually: timeout)", aError->description().c_str());
     aSsdpSearch->stopSearch();
     // now process the results
     currentBridgeCandidate = bridgeCandiates.begin();
     processCurrentBridgeCandidate();
   }
 }
示例#23
0
 void deviceLearnHandler(bool aLearnIn, ErrorPtr aError)
 {
   // back to normal...
   stopLearning(false);
   // ...but as we acknowledge the learning with the LEDs, schedule a update for afterwards
   shutDownTicket.executeOnce(boost::bind(&P44Vdcd::showAppStatus, this), 2*Second);
   // acknowledge the learning (if any, can also be timeout or manual abort)
   if (Error::isOK(aError)) {
     if (aLearnIn) {
       // show device learned
       indicateTempStatus(tempstatus_success);
     }
     else {
       // show device unlearned
       indicateTempStatus(tempstatus_failure);
     }
   }
   else {
     LOG(LOG_ERR, "Learning error: %s", aError->description().c_str());
   }
 }
示例#24
0
ErrorPtr PersistentParams::deleteFromStore()
{
  ErrorPtr err;
  dirty = false; // forget any unstored changes
  if (rowid!=0) {
    FOCUSLOG("deleteFromStore: deleting row %lld in table %s\n", rowid, tableName());
    if (paramStore.executef("DELETE FROM %s WHERE ROWID=%lld", tableName(), rowid) != SQLITE_OK) {
      err = paramStore.error();
    }
    // deleted, forget
    rowid = 0;
  }
  // anyway, remove children
  if (Error::isOK(err)) {
    err = deleteChildren();
  }
  if (!Error::isOK(err)) {
    LOG(LOG_ERR, "deleteFromStore: table=%s, ROWID=%lld - failed: %s\n", tableName(), rowid, err->description().c_str());
  }
  return err;
}
示例#25
0
 virtual void initialized(ErrorPtr aError)
 {
   #if SELFTESTING_ENABLED
   if (selfTesting) {
     // self test mode
     if (Error::isOK(aError)) {
       // start self testing (which might do some collecting if needed for testing)
       p44VdcHost->selfTest(boost::bind(&P44Vdcd::selfTestDone, this, _1), button, redLED, greenLED); // do the self test
     }
     else {
       // - init already unsuccessful, consider test failed, call test end routine directly
       selfTestDone(aError);
     }
   }
   else
   #endif // SELFTESTING_ENABLED
   if (!Error::isOK(aError)) {
     // cannot initialize, this is a fatal error
     setAppStatus(status_fatalerror);
     // exit in 15 seconds
     LOG(LOG_ALERT, "****** Fatal error - vdc host initialisation failed: %s", aError->description().c_str());
     shutDownTicket.executeOnce(boost::bind(&P44Vdcd::terminateAppWith, this, aError), 15*Second);
     return;
   }
   else {
     // Initialized ok and not testing
     #if !DISABLE_DISCOVERY
     // - initialize discovery
     initDiscovery();
     #endif
     // - start running normally
     p44VdcHost->startRunning();
     // - collect devices
     collectDevices(rescanmode_normal);
   }
 }
示例#26
0
ErrorPtr PropertyContainer::accessProperty(PropertyAccessMode aMode, ApiValuePtr aQueryObject, ApiValuePtr aResultObject, int aDomain, PropertyDescriptorPtr aParentDescriptor)
{
  ErrorPtr err;
  #if DEBUGFOCUSLOGGING
  FOCUSLOG("\naccessProperty: entered with query = %s\n", aQueryObject->description().c_str());
  if (aParentDescriptor) {
    FOCUSLOG("- parentDescriptor '%s' (%s), fieldKey=%u, objectKey=%u\n", aParentDescriptor->name(), aParentDescriptor->isStructured() ? "structured" : "scalar", aParentDescriptor->fieldKey(), aParentDescriptor->objectKey());
  }
  #endif
  // for reading, NULL query is like query { "":NULL }
  if (aQueryObject->isNull() && aMode==access_read) {
    aQueryObject->setType(apivalue_object);
    aQueryObject->add("", aQueryObject->newValue(apivalue_null));
  }
  // aApiObject must be of type apivalue_object
  if (!aQueryObject->isType(apivalue_object))
    return ErrorPtr(new VdcApiError(415, "Query or Value written must be object"));
  if (aMode==access_read) {
    if (!aResultObject)
      return ErrorPtr(new VdcApiError(415, "accessing property for read must provide result object"));
    aResultObject->setType(apivalue_object); // must be object
  }
  // Iterate trough elements of query object
  aQueryObject->resetKeyIteration();
  string queryName;
  ApiValuePtr queryValue;
  string errorMsg;
  while (aQueryObject->nextKeyValue(queryName, queryValue)) {
    FOCUSLOG("- starting to process query element named '%s' : %s\n", queryName.c_str(), queryValue->description().c_str());
    if (aMode==access_read && queryName=="#") {
      // asking for number of elements at this level -> generate and return int value
      queryValue = queryValue->newValue(apivalue_int64); // integer
      queryValue->setInt32Value(numProps(aDomain, aParentDescriptor));
      aResultObject->add(queryName, queryValue);
    }
    else {
      // accessing an element or series of elements at this level
      bool wildcard = isMatchAll(queryName);
      // - find all descriptor(s) for this queryName
      PropertyDescriptorPtr propDesc;
      int propIndex = 0;
      bool foundone = false;
      do {
        propDesc = getDescriptorByName(queryName, propIndex, aDomain, aParentDescriptor);
        if (propDesc) {
          foundone = true; // found at least one descriptor for this query element
          FOCUSLOG("  - processing descriptor '%s' (%s), fieldKey=%u, objectKey=%u\n", propDesc->name(), propDesc->isStructured() ? "structured" : "scalar", propDesc->fieldKey(), propDesc->objectKey());
          // actually access by descriptor
          if (propDesc->isStructured()) {
            ApiValuePtr subQuery;
            // property is a container. Now check the value
            if (queryValue->isType(apivalue_object)) {
              subQuery = queryValue; // query specifies next level, just use it
            }
            else if (queryName!="*" && (!wildcard || propDesc->isWildcardAddressable())) {
              // don't recurse deeper when query name is "*" or property is not wildcard-adressable
              // special case is "*" as leaf in query - only recurse if it is not present
              // - autocreate subquery
              subQuery = queryValue->newValue(apivalue_object);
              subQuery->add("", queryValue->newValue(apivalue_null));
            }
            if (subQuery) {
              // addressed property is a container by itself -> recurse
              // - get the PropertyContainer
              int containerDomain = aDomain; // default to same, but getContainer may modify it
              PropertyDescriptorPtr containerPropDesc = propDesc;
              PropertyContainerPtr container = getContainer(containerPropDesc, containerDomain);
              if (container) {
                FOCUSLOG("  - container for '%s' is 0x%p\n", propDesc->name(), container.get());
                FOCUSLOG("    >>>> RECURSING into accessProperty()\n");
                if (aMode==access_read) {
                  // read needs a result object
                  ApiValuePtr resultValue = queryValue->newValue(apivalue_object);
                  err = container->accessProperty(aMode, subQuery, resultValue, containerDomain, containerPropDesc);
                  if (Error::isOK(err)) {
                    // add to result with actual name (from descriptor)
                    FOCUSLOG("\n  <<<< RETURNED from accessProperty() recursion\n");
                    FOCUSLOG("  - accessProperty of container for '%s' returns %s\n", propDesc->name(), resultValue->description().c_str());
                    aResultObject->add(propDesc->name(), resultValue);
                  }
                }
                else {
                  // for write, just pass the query value
                  err = container->accessProperty(aMode, subQuery, ApiValuePtr(), containerDomain, containerPropDesc);
                  FOCUSLOG("    <<<< RETURNED from accessProperty() recursion\n", propDesc->name(), container.get());
                }
                if ((aMode!=access_read) && Error::isOK(err)) {
                  // give this container a chance to post-process write access
                  err = writtenProperty(aMode, propDesc, aDomain, container);
                }
                // 404 errors are collected, but dont abort the query
                if (Error::isError(err, VdcApiError::domain(), 404)) {
                  if (!errorMsg.empty()) errorMsg += "; ";
                  errorMsg += string_format("Error(s) accessing subproperties of '%s' : { %s }", queryName.c_str(), err->description().c_str());
                  err.reset(); // forget the error on this level
                }
              }
            }
          }
          else {
            // addressed (and known by descriptor!) property is a simple value field -> access it
            if (aMode==access_read) {
              // read access: create a new apiValue and have it filled
              ApiValuePtr fieldValue = queryValue->newValue(propDesc->type()); // create a value of correct type to get filled
              bool accessOk = accessField(aMode, fieldValue, propDesc); // read
              // for read, not getting an OK from accessField means: property does not exist (even if known per descriptor),
              // so it will not be added to the result
              if (accessOk) {
                // add to result with actual name (from descriptor)
                aResultObject->add(propDesc->name(), fieldValue);
              }
              FOCUSLOG("    - accessField for '%s' returns %s\n", propDesc->name(), fieldValue->description().c_str());
            }
            else {
              // write access: just pass the value
              if (!accessField(aMode, queryValue, propDesc)) { // write
                err = ErrorPtr(new VdcApiError(403,string_format("Write access to '%s' denied", propDesc->name())));
              }
            }
          }
        }
        else {
          // no descriptor found for this query element
          // Note: this means that property is not KNOWN, which IS not the same as getting false from accessField
          //   (latter means that property IS known, but has no value in the context it was queried)
          //   HOWEVER, for the vdc API it was decided that for reading, these cases should NOT be
          //   distinguished for getProperty. If a property does not exist for either reason, the return tree just does
          //   no contain that property.
          //   Also note that not having a property is not the same as not having a property VALUE:
          //   latter case will explicitly return a NULL value
          if (!wildcard && !foundone && aMode!=access_read) {
            // query did address a specific property but it is unknown -> report as error (for read AND write!)
            // - collect error message, but do not abort query processing
            if (!errorMsg.empty()) errorMsg += "; ";
            errorMsg += string_format("Unknown property '%s' -> ignored", queryName.c_str());
          }
        }
      } while (Error::isOK(err) && propIndex!=PROPINDEX_NONE);
    }
    // now generate error if we have collected a non-empty error message
    if (!errorMsg.empty()) {
      err = ErrorPtr(new VdcApiError(404,errorMsg));
    }
    #if DEBUGLOGGING
    if (aMode==access_read) {
      FOCUSLOG("- query element named '%s' now has result object: %s\n", queryName.c_str(), aResultObject->description().c_str());
    }
    #endif
  }
  return err;
}
示例#27
0
ErrorPtr SocketComm::initiateConnection()
{
  int res;
  ErrorPtr err;

  if (!connectionOpen && !isConnecting && !serverConnection) {
    freeAddressInfo();
    // check for protocolfamily auto-choice
    if (protocolFamily==PF_UNSPEC) {
      // not specified, choose local socket if service spec begins with slash
      if (serviceOrPortOrSocket.size()>1 && serviceOrPortOrSocket[0]=='/')
        protocolFamily = PF_LOCAL; // absolute paths are considered local sockets
    }
    if (protocolFamily==PF_LOCAL) {
      // local socket -> just connect, no lists to try
      LOG(LOG_DEBUG, "Initiating local socket %s connection", serviceOrPortOrSocket.c_str());
      hostNameOrAddress = "local"; // set it for log display
      // synthesize address info for unix socket, because standard UN*X getaddrinfo() call usually does not handle PF_LOCAL
      addressInfoList = new struct addrinfo;
      memset(addressInfoList, 0, sizeof(addrinfo));
      addressInfoList->ai_family = protocolFamily;
      addressInfoList->ai_socktype = socketType;
      addressInfoList->ai_protocol = protocol;
      struct sockaddr_un *sunP = new struct sockaddr_un;
      addressInfoList->ai_addr = (struct sockaddr *)sunP;
      addressInfoList->ai_addrlen = sizeof(struct sockaddr_un);
      memset((char *)sunP, 0, addressInfoList->ai_addrlen);
      sunP->sun_family = (sa_family_t)protocolFamily;
      strncpy(sunP->sun_path, serviceOrPortOrSocket.c_str(), sizeof (sunP->sun_path));
      sunP->sun_path[sizeof (sunP->sun_path) - 1] = '\0'; // emergency terminator
    }
    else {
      // assume internet connection -> get list of possible addresses and try them
      if (hostNameOrAddress.empty()) {
        err = ErrorPtr(new SocketCommError(SocketCommErrorNoParams,"Missing connection parameters"));
        goto done;
      }
      // try to resolve host name
      struct addrinfo hint;
      memset(&hint, 0, sizeof(addrinfo));
      hint.ai_flags = 0; // no flags
      hint.ai_family = protocolFamily;
      hint.ai_socktype = socketType;
      hint.ai_protocol = protocol;
      res = getaddrinfo(hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str(), &hint, &addressInfoList);
      if (res!=0) {
        // error
        err = ErrorPtr(new SocketCommError(SocketCommErrorCannotResolve, string_format("getaddrinfo error %d: %s", res, gai_strerror(res))));
        DBGLOG(LOG_DEBUG, "SocketComm: getaddrinfo failed: %s", err->description().c_str());
        goto done;
      }
    }
    // now try all addresses in the list
    // - init iterator pointer
    currentAddressInfo = addressInfoList;
    // - try connecting first address
    LOG(LOG_DEBUG, "Initiating connection to %s:%s", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str());
    err = connectNextAddress();
  }
done:
  if (!Error::isOK(err) && connectionStatusHandler) {
    connectionStatusHandler(this, err);
  }
  // return it
  return err;
}
示例#28
0
ErrorPtr SocketComm::connectNextAddress()
{
  int res;
  ErrorPtr err;
  const int one = 1;

  // close possibly not fully open connection FD
  internalCloseConnection();
  // try to create a socket
  int socketFD = -1;
  // as long as we have more addresses to check and not already connecting
  bool startedConnecting = false;
  while (currentAddressInfo && !startedConnecting) {
    err.reset();
    socketFD = socket(currentAddressInfo->ai_family, currentAddressInfo->ai_socktype, currentAddressInfo->ai_protocol);
    if (socketFD==-1) {
      err = SysError::errNo("Cannot create client socket: ");
    }
    else {
      // usable address found, socket created
      // - make socket non-blocking
      makeNonBlocking(socketFD);
      // Now we have a socket
      if (connectionLess) {
        // UDP: no connect phase
        // - enable for broadcast if requested
        if (broadcast) {
          // needs SO_BROADCAST
          if (setsockopt(socketFD, SOL_SOCKET, SO_BROADCAST, (char *)&one, (int)sizeof(one)) == -1) {
            err = SysError::errNo("Cannot setsockopt(SO_BROADCAST): ");
          }
          else {
            // to receive answers, we also need to bind to INADDR_ANY
            // - get port number
            char sbuf[NI_MAXSERV];
            int s = getnameinfo(
              currentAddressInfo->ai_addr, currentAddressInfo->ai_addrlen,
              NULL, 0, // no host address
              sbuf, sizeof sbuf, // only service/port
              NI_NUMERICSERV
            );
            if (s==0) {
              // convert to numeric port number
              int port;
              if (sscanf(sbuf, "%d", &port)==1) {
                // bind connectionless socket to INADDR_ANY to receive broadcasts at all
                struct sockaddr_in recvaddr;
                memset(&recvaddr, 0, sizeof recvaddr);
                recvaddr.sin_family = AF_INET;
                recvaddr.sin_port = htons(port);
                recvaddr.sin_addr.s_addr = INADDR_ANY;
                if (::bind(socketFD, (struct sockaddr*)&recvaddr, sizeof recvaddr) == -1) {
                  err = SysError::errNo("Cannot bind to INADDR_ANY: ");
                }
              }
            }
          }
        }
        if (Error::isOK(err)) {
          startedConnecting = true;
          // save valid address info for later use (UDP needs it to send datagrams)
          if (currentSockAddrP)
            free(currentSockAddrP);
          currentSockAddrLen = currentAddressInfo->ai_addrlen;
          currentSockAddrP = (sockaddr *)malloc(currentSockAddrLen);
          memcpy(currentSockAddrP, currentAddressInfo->ai_addr, currentAddressInfo->ai_addrlen);
        }
      }
      else {
        // TCP: initiate connection
        res = connect(socketFD, currentAddressInfo->ai_addr, currentAddressInfo->ai_addrlen);
        LOG(LOG_DEBUG, "- Attempting connection with address family = %d, protocol = %d", currentAddressInfo->ai_family, currentAddressInfo->ai_protocol);
        if (res==0 || errno==EINPROGRESS) {
          // connection initiated (or already open, but connectionMonitorHandler will take care in both cases)
          startedConnecting = true;
        }
        else {
          // immediate error connecting
          err = SysError::errNo("Cannot connect: ");
        }
      }
    }
    // advance to next address
    currentAddressInfo = currentAddressInfo->ai_next;
  }
  if (!startedConnecting) {
    // exhausted addresses without starting to connect
    if (!err) err = ErrorPtr(new SocketCommError(SocketCommErrorNoConnection, "No connection could be established"));
    LOG(LOG_DEBUG, "Cannot initiate connection to %s:%s - %s", hostNameOrAddress.c_str(), serviceOrPortOrSocket.c_str(), err->description().c_str());
  }
  else {
    if (!connectionLess) {
      // connection in progress
      isConnecting = true;
      // - save FD
      connectionFd = socketFD;
      // - install callback for when FD becomes writable (or errors out)
      mainLoop.registerPollHandler(
        connectionFd,
        POLLOUT,
        boost::bind(&SocketComm::connectionMonitorHandler, this, _1, _2, _3)
      );
    }
    else {
      // UDP socket successfully created
      LOG(LOG_DEBUG, "Connectionless socket ready for address family = %d, protocol = %d", protocolFamily, protocol);
      connectionOpen = true;
      isConnecting = false;
      currentAddressInfo = NULL; // no more addresses to check
      // immediately use socket for I/O
      setFd(socketFD);
      // call handler if defined
      if (connectionStatusHandler) {
        // connection ok
        connectionStatusHandler(this, ErrorPtr());
      }
    }
  }
  // clean up if list processed
  freeAddressInfo();
  // return status
  return err;
}
示例#29
0
void VdcJsonApiConnection::jsonResponseHandler(VdcApiResponseCB aResponseHandler, int32_t aResponseId, ErrorPtr &aError, JsonObjectPtr aResultOrErrorData)
{
  if (aResponseHandler) {
    // create request object just to hold the response ID
    string respId = string_format("%d", aResponseId);
    ApiValuePtr resultOrErrorData = JsonApiValue::newValueFromJson(aResultOrErrorData);
    VdcApiRequestPtr request = VdcJsonApiRequestPtr(new VdcJsonApiRequest(VdcJsonApiConnectionPtr(this), respId.c_str()));
    if (Error::isOK(aError)) {
      LOG(LOG_INFO,"vdSM -> vDC (JSON) result received: id='%s', result=%s\n", request->requestId().c_str(), resultOrErrorData ? resultOrErrorData->description().c_str() : "<none>");
    }
    else {
      LOG(LOG_INFO,"vdSM -> vDC (JSON) error received: id='%s', error=%s, errordata=%s\n", request->requestId().c_str(), aError->description().c_str(), resultOrErrorData ? resultOrErrorData->description().c_str() : "<none>");
    }
    aResponseHandler(VdcApiConnectionPtr(this), request, aError, resultOrErrorData);
  }
}
示例#30
0
ErrorPtr PersistentParams::saveToStore(const char *aParentIdentifier, bool aMultipleChildrenAllowed)
{
  ErrorPtr err;
  if (dirty) {
    sqlite3pp::command cmd(paramStore);
    string sql;
    // cleanup: remove all previous records for that parent if not multiple children allowed
    if (!aMultipleChildrenAllowed) {
      sql = string_format("DELETE FROM %s WHERE %s='%s'", tableName(), getKeyDef(0)->fieldName, aParentIdentifier);
      if (rowid!=0) {
        string_format_append(sql, " AND ROWID!=%lld", rowid);
      }
      FOCUSLOG("- cleanup before save: %s\n", sql.c_str());
      if (paramStore.executef(sql.c_str()) != SQLITE_OK) {
        LOG(LOG_ERR, "- cleanup error (ignored): %s\n", sql.c_str(), paramStore.error()->description().c_str());
      }
    }
    // now save
    if (rowid!=0) {
      // already exists in the DB, just update
      sql = string_format("UPDATE %s SET ", tableName());
      // - update all fields, even key fields may change (as long as they don't collide with another entry)
      appendfieldList(sql, true, false, true);
      appendfieldList(sql, false, true, true);
      string_format_append(sql, " WHERE ROWID=%lld", rowid);
      // now execute command
      FOCUSLOG("saveToStore: update existing row for parent='%s': %s\n", aParentIdentifier, sql.c_str());
      if (cmd.prepare(sql.c_str())!=SQLITE_OK) {
        // error on update is always a real error - if we loaded the params from the DB, schema IS ok!
        err = paramStore.error();
      }
      if (Error::isOK(err)) {
        // bind the values
        int index = 1; // SQLite parameter indexes are 1-based!
        bindToStatement(cmd, index, aParentIdentifier, 0); // no flags yet, class hierarchy will collect them
        // now execute command
        if (cmd.execute()==SQLITE_OK) {
          // ok, updated ok
          dirty = false;
        }
        else {
          // failed
          err = paramStore.error();
        }
      }
    }
    else {
      // seems new, insert. But use INSERT OR REPLACE to make sure key constraints are enforced
      sql = string_format("INSERT OR REPLACE INTO %s (", tableName());;
      size_t numFields = appendfieldList(sql, true, false, false);
      numFields += appendfieldList(sql, false, true, false);
      sql += ") VALUES (";
      bool first = true;
      for (int i=0; i<numFields; i++) {
        if (!first) sql += ", ";
        sql += "?";
        first = false;
      }
      sql += ")";
      // prepare
      FOCUSLOG("saveToStore: insert new row for parent='%s': %s\n", aParentIdentifier, sql.c_str());
      if (cmd.prepare(sql.c_str())!=SQLITE_OK) {
        FOCUSLOG("- insert not successful - assume wrong schema -> calling checkAndUpdateSchema()\n");
        // - error on INSERT could mean schema is not up to date
        cmd.reset();
        checkAndUpdateSchema();
        FOCUSLOG("saveToStore: retrying insert after schema update: %s\n", sql.c_str());
        if (cmd.prepare(sql.c_str())!=SQLITE_OK) {
          // error now means something is really wrong
          err = paramStore.error();
        }
      }
      if (Error::isOK(err)) {
        // bind the values
        int index = 1; // SQLite parameter indexes are 1-based!
        bindToStatement(cmd, index, aParentIdentifier, 0); // no flags yet, class hierarchy will collect them
        // now execute command
        if (cmd.execute()==SQLITE_OK) {
          // get the new ROWID
          rowid = paramStore.last_insert_rowid();
          dirty = false;
        }
        else {
          // failed
          err = paramStore.error();
        }
      }
    }
    if (!Error::isOK(err)) {
      LOG(LOG_ERR, "saveToStore: %s - failed: %s\n", sql.c_str(), err->description().c_str());
    }
  }
  // anyway, have children checked
  if (Error::isOK(err)) {
    err = saveChildren();
  }
  return err;
}