Example #1
0
int main( void )
{
  // Setup an object
  MyObject obj;
  obj.id = "An identifier!";
  obj.rotation = 0.1234f;
  obj.x = 5;
  obj.y = 10;

  // Dump contents of our object
  SERIALIZE( MyObject, obj, stdout );

  // Get some space so that we can place a string in here
  obj.id = (string)malloc( sizeof( char ) * 100 );

  getchar( );

  {
    FILE *fp = fopen( "SerializedMyObject.txt", "r" );
    printf( "Deserializing from SerializedMyObject.txt:\n" );
    printf( "Press enter to deserialize...\n" );
    getchar( );
    DESERIALIZE( MyObject, obj, fp );
    SERIALIZE( MyObject, obj, stdout );
  }

  getchar( );

  free( obj.id );

  return 0;
}
Example #2
0
void siconos_io(Archive&ar, NumericsMatrix& v, unsigned int version)
{
  SERIALIZE(v, (storageType)(size0)(size1), ar);
  if (v.storageType == 0)
  {
    if (Archive::is_loading::value)
    {
      v.matrix0 = (double *) malloc(v.size0 * v.size1 * sizeof(double));
      v.matrix1 = NULL;
      v.matrix2 = NULL;
      v.internalData = NULL;
    }
    SERIALIZE_C_ARRAY(v.size0 * v.size1, v, matrix0, ar);
  }
  else
  {
    {
      if (Archive::is_loading::value)
      {
        v.matrix0 = NULL;
        v.matrix1 = (SparseBlockStructuredMatrix*) malloc(sizeof(SparseBlockStructuredMatrix));
        v.matrix2 = NULL;
        v.internalData = NULL;
      }
      SERIALIZE(v, (matrix1), ar);
    }
  }
}
Example #3
0
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		SERIALIZEIOBJPTR(m_pBlackboardGlobal);
		SERIALIZE(m_BlackboardTeam);
		SERIALIZE(m_BlackboardGroup);
		SERIALIZE(m_BlackboardIndividual);
		SERIALIZE(m_BlackboardIndividualCommon);
	}
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		BehaviorCommon::Serialize(pSerializer);

		SERIALIZE(m_TimeToNextDirChange);
		SERIALIZE(m_PatrolDir);
		SERIALIZEIOBJPTR(m_pApproachTarget);
	}
Example #5
0
void siconos_io(Archive& ar, LinearComplementarityProblem& v, unsigned int version)
{
  SERIALIZE(v, (size), ar);

  if(Archive::is_loading::value)
  {
    v.q = (double *) malloc(v.size * sizeof(double));
    v.M = NM_new();
  }
  SERIALIZE(v, (M), ar);
  SERIALIZE_C_ARRAY(v.size, v, q, ar);
}
Example #6
0
void siconos_io(Archive& ar, FrictionContactProblem& p, const unsigned int file_version)
{
  SERIALIZE(p, (dimension)(numberOfContacts), ar);

  if (Archive::is_loading::value)
  {
    p.q = (double *) malloc(p.dimension * p.numberOfContacts * sizeof(double));
    p.mu = (double *) malloc(p.numberOfContacts * sizeof(double));
    p.M = NM_new();
  }

  SERIALIZE(p, (M), ar);
  SERIALIZE_C_ARRAY(p.dimension * p.numberOfContacts, p, q, ar);
  SERIALIZE_C_ARRAY(p.dimension, p, mu, ar);
}
 void save( Archive &ar, entityx::Entity const & entity )
 {
     //        uint64_t id = entity.id().id();
     //        ar( make_nvp("entityID", id) );
     assert(entity.has_component<Tag>());
     auto e = const_cast<entityx::Entity &>(entity);
     auto tag = e.component<Tag>();
     assert(entity.valid());
     ar( cereal::make_nvp("uuid", (uint)(tag.get()->tag)) );
     
     //serialize over all components of each entity
     SERIALIZE("playerControl", PlayerControl);
     SERIALIZE("camera", Camera);
     SERIALIZE("orbitPath", OrbitPath);
 }
	virtual void Serialize( ISimpleSerializer *pSerializer )
	{
		AU_ASSERT(pSerializer);

		SERIALIZE(m_bDoUpdate);
		SerializeObjectsList( pSerializer );
	}
Example #9
0
MoveStack* generate<QUIET_CHECKS>(const Position& pos, MoveStack* mlist) {

  assert(!pos.checkers());

  CheckInfo ci(pos);
  Bitboard dc = ci.dcCandidates;

  while (dc)
  {
     Square from = pop_lsb(&dc);
     PieceType pt = type_of(pos.piece_on(from));

     if (pt == PAWN)
         continue; // Will be generated togheter with direct checks

     Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();

     if (pt == KING)
         b &= ~PseudoAttacks[QUEEN][ci.ksq];

     SERIALIZE(b);
  }

  return generate_all<QUIET_CHECKS>(pos, mlist, pos.side_to_move(), ~pos.pieces(), &ci);
}
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		AU_ASSERT(pSerializer);
		IEntityObject::Serialize(pSerializer);
		SERIALIZE(m_ImageFile);
		SERIALIZE(m_fMinViewTime);
		SERIALIZE(m_fFadeInTime);
		SERIALIZE(m_fFadeOutTime);
		SERIALIZE(m_fTimeDisplayed);
		SERIALIZE(m_fFadeOutStartTime);
		SERIALIZE(m_bAutoClose);
		SERIALIZE(m_bCloseRequested);
		SERIALIZE(m_bReadyToClose);
	}
Example #11
0
void Nes::Serialize(class Serializer& serializer)
{
	SERIALIZE(m_turbo);
	serializer.SerializeObject(m_cpu);
	serializer.SerializeObject(m_ppu);
	serializer.SerializeObject(m_apu);
	serializer.SerializeObject(m_cartridge);
	serializer.SerializeObject(m_cpuInternalRam);
}
Example #12
0
void siconos_io(Archive& ar, SolverOptions&v, unsigned int version)
{
  SERIALIZE(v, (solverId)(isSet)(iSize)(dSize)(filterOn)(numberOfInternalSolvers), ar);

  if (Archive::is_loading::value)
  {
    solver_options_nullify(&v);
    v.iparam = (int *) malloc(v.iSize * sizeof(int));
    v.dparam = (double *) malloc(v.dSize * sizeof(double));
    v.internalSolvers = (SolverOptions *) malloc(v.numberOfInternalSolvers * sizeof(SolverOptions));
    v.callback = (Callback *) malloc(sizeof(Callback));
  }
  SERIALIZE(v, (callback), ar);

  SERIALIZE_C_ARRAY(v.iSize, v, iparam, ar);
  SERIALIZE_C_ARRAY(v.dSize, v, dparam, ar);
  SERIALIZE_C_ARRAY(v.numberOfInternalSolvers, v, internalSolvers, ar);
}
Example #13
0
MoveStack* generate<EVASIONS>(const Position& pos, MoveStack* mlist) {

  assert(pos.checkers());

  Square from, checksq;
  int checkersCnt = 0;
  Color us = pos.side_to_move();
  Square ksq = pos.king_square(us);
  Bitboard sliderAttacks = 0;
  Bitboard b = pos.checkers();

  assert(pos.checkers());

  // Find squares attacked by slider checkers, we will remove them from the king
  // evasions so to skip known illegal moves avoiding useless legality check later.
  do
  {
      checkersCnt++;
      checksq = pop_lsb(&b);

      assert(color_of(pos.piece_on(checksq)) == ~us);

      switch (type_of(pos.piece_on(checksq)))
      {
      case BISHOP: sliderAttacks |= PseudoAttacks[BISHOP][checksq]; break;
      case ROOK:   sliderAttacks |= PseudoAttacks[ROOK][checksq];   break;
      case QUEEN:
          // If queen and king are far or not on a diagonal line we can safely
          // remove all the squares attacked in the other direction becuase are
          // not reachable by the king anyway.
          if (between_bb(ksq, checksq) || !(PseudoAttacks[BISHOP][checksq] & ksq))
              sliderAttacks |= PseudoAttacks[QUEEN][checksq];

          // Otherwise we need to use real rook attacks to check if king is safe
          // to move in the other direction. For example: king in B2, queen in A1
          // a knight in B1, and we can safely move to C1.
          else
              sliderAttacks |= PseudoAttacks[BISHOP][checksq] | pos.attacks_from<ROOK>(checksq);

      default:
          break;
      }
  } while (b);

  // Generate evasions for king, capture and non capture moves
  b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
  from = ksq;
  SERIALIZE(b);

  if (checkersCnt > 1)
      return mlist; // Double check, only a king move can save the day

  // Generate blocking evasions or captures of the checking piece
  Bitboard target = between_bb(checksq, ksq) | pos.checkers();

  return generate_all<EVASIONS>(pos, mlist, us, target);
}
Example #14
0
status_t
msg_send (int fd, msg_t * msg)
{
  mr_rarray_t rarray = SERIALIZE (msg_t, msg);
  if (NULL == rarray.data.ptr)
    return (ST_FAILURE);

  struct iovec iov[] = {
    { .iov_len = sizeof (rarray.MR_SIZE), .iov_base = &rarray.MR_SIZE, },
    { .iov_len = rarray.MR_SIZE, .iov_base = rarray.data.ptr, },
Example #15
0
void siconos_io(Archive& ar, SparseBlockStructuredMatrix& v, unsigned int version)
{
  SERIALIZE(v, (nbblocks)(blocknumber0)(blocknumber1)(filled1)(filled2), ar);
  if (Archive::is_loading::value)
  {
    v.block = (double **) malloc(v.nbblocks * sizeof(double *));
    v.blocksize1 = (unsigned int *) malloc (v.blocknumber1* sizeof(unsigned int));
    v.blocksize0 = (unsigned int *) malloc (v.blocknumber0* sizeof(unsigned int));
    SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar);
    SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar);
    int diagonalblocknumber  = v.blocknumber1 +
      ((v.blocknumber0 - v.blocknumber1) & -(v.blocknumber0 < v.blocknumber1));
    for (unsigned int i=0; i< diagonalblocknumber; ++i)
    {
      unsigned int size0 = v.blocksize0[i];
      if (i != 0) size0 -= v.blocksize0[i - 1];
      unsigned int size1 = v.blocksize1[i];
      if (i != 0) size1 -= v.blocksize1[i - 1];
      v.block[i] = (double*) malloc(size0 * size1 * sizeof(double));
    }
    v.index1_data = (size_t *) malloc (v.filled1 * sizeof(size_t));
    v.index2_data = (size_t *) malloc (v.filled2 * sizeof(size_t));
  }
  else
  {
    SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar);
    SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar);
  }

  int diagonalblocknumber  = v.blocknumber1 +
      ((v.blocknumber0 - v.blocknumber1) & -(v.blocknumber0 < v.blocknumber1));

  for (unsigned int i=0; i< v.nbblocks; ++i)
  {
    ar & ::boost::serialization::make_nvp("block", (long&) v.block[i]);
  }

  for (unsigned int i=0; i< diagonalblocknumber; ++i)
  {
    unsigned int size0 = v.blocksize0[i];
    if (i != 0) size0 -= v.blocksize0[i - 1];
    unsigned int size1 = v.blocksize1[i];
    if (i != 0) size1 -= v.blocksize1[i - 1];
    for (unsigned int k=0; k<size0 * size1; ++k)
    {
      ar & ::boost::serialization::make_nvp("item", v.block[i][k]);
    }
  }

  SERIALIZE_C_ARRAY(v.filled1,  v, index1_data, ar);
  SERIALIZE_C_ARRAY(v.filled2,  v, index2_data, ar);
}
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		IEntityObject::Serialize(pSerializer);

		SERIALIZE(m_gameObjectType);
		SERIALIZE(m_gameTeam);
		SERIALIZE(m_color);
		SERIALIZE(m_rotationAxis); // Demo
		SERIALIZE(m_collisionRadius);
		SERIALIZE(m_scaleModulationTime);
		SERIALIZE(m_bIsSelected);
		SERIALIZEIOBJPTR(m_pBehaviorTree);
		SERIALIZEIOBJPTR(m_pBehavior);
	}
Example #17
0
void siconos_io(Archive& ar, FrictionContact &v, unsigned int version)
{
  SERIALIZE(v, (_contactProblemDim)(_mu)(_numerics_solver_options)(_numerics_solver_id), ar);

  if (Archive::is_loading::value)
  {
    if (v._contactProblemDim == 2)
      v._frictionContact_driver = &frictionContact2D_driver;
    else
      v._frictionContact_driver = &frictionContact3D_driver;
  }

  ar & boost::serialization::make_nvp("LinearOSNS",
                                      boost::serialization::base_object<LinearOSNS>(v));

}
Example #18
0
void CTestDistortion::Test(CAlgorithm* alg, QString& params, QString& alg_params, QByteArray& result, const QString& container_name, const QString& watermark_name, int size)
{
    QImage in;
    //QImage in2;
    in.load(container_name);
    QImage orig(in);
    QFile wm(watermark_name);
    wm.open(QIODevice::ReadOnly);
    QByteArray bytes;// = wm.readAll();
    QByteArray bytes_out;
    QBitArray bits, bits_out;
    wm.close();
    if (!size) {
        size = (in.width() / 8) * (in.height() / 8) / 8;
    }
    bytes.resize(size);
    srand(QTime::currentTime().msec());
    for (int i=0; i<size; i++) {
        bytes[i] = rand() % 256;
    }

    qDebug() << params;
    SetParams(params);
    alg->SetParams(alg_params);
    alg->GenKey(bytes);
    alg->Hide(in, bytes, alg_params);
    in.save("F:\\koh.bmp");
    //alg->Restore(in, bytes_out, alg_params);


    CImgCompare::Result res = CImgCompare::PSNR_B(orig, in, ch);
    qDebug() << ch;
    /*qDebug() << "md: " << res.md;
    qDebug() << "ad: " << res.ad;
    qDebug() << "nad: " << res.nad;
    qDebug() << "mse: " << res.mse;
    qDebug() << "nmse: " << res.nmse;
    qDebug() << "l2: " << res.l2;
    qDebug() << "snr: " << res.snr;
    qDebug() << "psnr: " << res.psnr;
    qDebug() << "image fidelity: " << res.ifid;
    qDebug() << "hs: " << res.hs;
    qDebug() << "sc: " << res.sc;
    qDebug() << "cq: " << res.cq;
    qDebug() << "nc: " << res.nc;*/
    result = SERIALIZE(res);
}
	void SerializeObjectsList( ISimpleSerializer *pSerializer )
	{
		std::vector<TGameObjectIds> m_ObjectIds; 

		if ( !pSerializer->IsLoading() )
		{
			// Create a collection of ObjectIds that matches m_Objects pointer collection 

			m_ObjectIds.resize(EGO_COUNT);
			for (int i=0; i<EGO_COUNT; ++i)
			{
				size_t count = m_GameObjects[i].size();
				m_ObjectIds[i].reserve( count );
				m_ObjectIds[i].clear();

				TGameObjects::iterator it = m_GameObjects[i].begin();
				TGameObjects::iterator itEnd = m_GameObjects[i].end();
				while (it != itEnd)
				{
					m_ObjectIds[i].push_back( (*it)->GetObjectId() );
					++it;
				}
			}
		}

		SERIALIZE(m_ObjectIds);

		if ( pSerializer->IsLoading() )
		{
			// Rebuild m_objects pointer collection

			IEntitySystem* pEntitySystem = PerModuleInterface::GetInstance()->GetSystemTable()->pEntitySystem;
			for (int i=0; i<EGO_COUNT; ++i)
			{
				m_GameObjects[i].clear();
				size_t count = m_ObjectIds[i].size();

				for (size_t j=0; j<count; ++j)
				{
					IGameObject* pGameObject = 0;
					IObjectUtils::GetObject( &pGameObject, m_ObjectIds[i][j] );

					m_GameObjects[i].insert( pGameObject );
				}
			}
		}	
	}
	void SerializeObjectsList( ISimpleSerializer *pSerializer )
	{
		std::vector<TGameObjectIds> m_ObjectIds; 

		if ( !pSerializer->IsLoading() )
		{
			// Create a collection of ObjectIds that matches m_Objects pointer collection 

			m_ObjectIds.resize(EGO_COUNT);
			for (int i=0; i<EGO_COUNT; ++i)
			{
				size_t count = m_Objects[i].size();
				m_ObjectIds[i].resize( count );
				
				for (size_t j=0; j<count; ++j)
				{
					m_ObjectIds[i][j] = m_Objects[i][j]->GetObjectId();
				}
			}
		}

		SERIALIZE(m_ObjectIds);
		
		if ( pSerializer->IsLoading() )
		{
			// Rebuild m_objects pointer collection

			for (int i=0; i<EGO_COUNT; ++i)
			{
				size_t count = m_ObjectIds[i].size();
				m_Objects[i].clear();
				m_Objects[i].resize( count );

				for (size_t j=0; j<count; ++j)
				{
					IGameObject* pGameObject = 0;
					IObjectUtils::GetObject( &pGameObject, m_ObjectIds[i][j] );

					m_Objects[i][j] = pGameObject;
				}
			}
		}	
	}
Example #21
0
void rem_ctrl_http_send_data(float Temp_c__f, float Pres_hPa__f, float Humi_pct__f)
{
    // Don't run this function unless the initialization succeeded.
    if (Init_level__i < 4) return;

    timeNow = (int)time(NULL);
    sprintf(buff, "%d", timeNow);
    
    myWeather->DeviceId = "FeatherM0_w_BME280";
    myWeather->MTemperature = Temp_c__f;
    myWeather->Pressure = Pres_hPa__f;
    myWeather->Humidity = Humi_pct__f;
    myWeather->EventTime = timeNow;
    
    unsigned char* destination;
    size_t destinationSize;
    if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature, myWeather->Pressure, myWeather->Humidity) != IOT_AGENT_OK)
    {
        (void)printf("Failed to serialize\r\n");
    }
    else
    {
        IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
        if (messageHandle == NULL)
        {
            printf("unable to create a new IoTHubMessage\r\n");
        }
        else
        {
            if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
            {
                printf("failed to hand over the message to IoTHubClient");
            }
            else
            {
                printf("IoTHubClient accepted the message for delivery\r\n");
            }
    
            IoTHubMessage_Destroy(messageHandle);
        }
        free(destination);
    }
}
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		IEntityObject::Serialize(pSerializer);
		SERIALIZE(m_GlobalParameters);
		SERIALIZE(m_NextSpawnTimes);
		SERIALIZE(m_NextGameObjectNumber);
		SERIALIZE(m_CurrentState);
		SERIALIZE(m_GameObjectsToDestroy);
		SERIALIZE(m_GameObjectsToSpawn);
		SERIALIZEIOBJPTR(m_pSplashScreen);
		SERIALIZEIOBJPTR(m_pBBGlobal);

		SerializeObjectsList( pSerializer );
	}
Example #23
0
ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* mlist) {

  assert(pos.checkers());

  int checkersCnt = 0;
  Color us = pos.side_to_move();
  Square ksq = pos.king_square(us), from = ksq /* For SERIALIZE */, checksq;
  Bitboard sliderAttacks = 0;
  Bitboard b = pos.checkers();

  assert(pos.checkers());

  // Find all the squares attacked by slider checkers. We will remove them from
  // the king evasions in order to skip known illegal moves, which avoids any
  // useless legality checks later on.
  do
  {
      ++checkersCnt;
      checksq = pop_lsb(&b);

      assert(color_of(pos.piece_on(checksq)) == ~us);

      if (type_of(pos.piece_on(checksq)) > KNIGHT) // A slider
          sliderAttacks |= LineBB[checksq][ksq] ^ checksq;

  } while (b);

  // Generate evasions for king, capture and non capture moves
  b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
  SERIALIZE(b);

  if (checkersCnt > 1)
      return mlist; // Double check, only a king move can save the day

  // Generate blocking evasions or captures of the checking piece
  Bitboard target = between_bb(checksq, ksq) | checksq;

  return us == WHITE ? generate_all<WHITE, EVASIONS>(pos, mlist, target)
                     : generate_all<BLACK, EVASIONS>(pos, mlist, target);
}
MoveStack* generate<MV_QUIET_CHECK>(const Position& pos, MoveStack* mlist) {

  assert(!pos.in_check());

  Color us = pos.side_to_move();
  CheckInfo ci(pos);
  Bitboard dc = ci.dcCandidates;

  while (dc)
  {
     Square from = pop_1st_bit(&dc);
     PieceType pt = type_of(pos.piece_on(from));

     if (pt == PAWN)
         continue; // Will be generated togheter with direct checks

     Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();

     if (pt == KING)
         b &= ~PseudoAttacks[QUEEN][ci.ksq];

     SERIALIZE(b);
  }

  mlist = (us == WHITE ? generate_pawn_moves<WHITE, MV_QUIET_CHECK>(pos, mlist, ci.dcCandidates, ci.ksq)
                       : generate_pawn_moves<BLACK, MV_QUIET_CHECK>(pos, mlist, ci.dcCandidates, ci.ksq));

  mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, ci);
  mlist = generate_direct_checks<BISHOP>(pos, mlist, us, ci);
  mlist = generate_direct_checks<ROOK>(pos, mlist, us, ci);
  mlist = generate_direct_checks<QUEEN>(pos, mlist, us, ci);

  if (pos.can_castle(us))
  {
      mlist = generate_castle<KING_SIDE, true>(pos, mlist, us);
      mlist = generate_castle<QUEEN_SIDE, true>(pos, mlist, us);
  }

  return mlist;
}
	void SerializeObjectsList( ISimpleSerializer *pSerializer )
	{
		TGameObjectIds m_ObjectIds;

		if ( !pSerializer->IsLoading() )
		{
			// Create a collection of ObjectIds that matches m_Objects pointer collection 
		
			size_t count = m_Objects.size();
			m_ObjectIds.resize( count );

			for (size_t i=0; i<count; ++i)
			{
				m_ObjectIds[i] = m_Objects[i]->GetObjectId();
			}
		}

		SERIALIZE(m_ObjectIds);

		if ( pSerializer->IsLoading() )
		{
			// Rebuild m_objects pointer collection

			IEntitySystem* pEntitySystem = PerModuleInterface::GetInstance()->GetSystemTable()->pEntitySystem;
			
			size_t count = m_ObjectIds.size();
			m_Objects.clear();
			m_Objects.resize( count );

			for (size_t i=0; i<count; ++i)
			{
				IGameObject* pGameObject = 0;
				IObjectUtils::GetObject( &pGameObject, m_ObjectIds[i] );

				m_Objects[i] = pGameObject;
			}		
		}	
	}
void simplesample_http_run(void)
{
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        LogInfo("Failed on serializer_init\r\n");
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
        srand((unsigned int)time(NULL));
        int avgWindSpeed = 10.0;

        if (iotHubClientHandle == NULL)
        {
            LogInfo("Failed on IoTHubClient_LL_Create\r\n");
        }
        else
        {
            unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
            {
                LogInfo("failure to set option \"MinimumPollingTime\"\r\n");
            }

#ifdef MBED_BUILD_TIMESTAMP
            // For mbed add the certificate information
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
            {
                LogInfo("failure to set option \"TrustedCerts\"\r\n");
            }
#endif // MBED_BUILD_TIMESTAMP

            ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
            if (myWeather == NULL)
            {
                LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
                {
                    LogInfo("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {
                    myWeather->DeviceId = "myFirstDevice";
                    myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
                    {
                        unsigned char* destination;
                        size_t destinationSize;
                        if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != IOT_AGENT_OK)
                        {
                            LogInfo("Failed to serialize\r\n");
                        }
                        else
                        {
                            IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize);
                            if (messageHandle == NULL)
                            {
                                LogInfo("unable to create a new IoTHubMessage\r\n");
                            }
                            else
                            {
                                if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
                                {
                                    LogInfo("failed to hand over the message to IoTHubClient\r\n");
                                }
                                else
                                {
                                    LogInfo("IoTHubClient accepted the message for delivery\r\n");
                                }

                                IoTHubMessage_Destroy(messageHandle);
                            }
                            free(destination);
                        }
                    }

                    /* wait for commands */
                    while (1)
                    {
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                        ThreadAPI_Sleep(100);
                    }
                }

                DESTROY_MODEL_INSTANCE(myWeather);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
	virtual void Serialize(ISimpleSerializer *pSerializer)
	{
		AU_ASSERT(pSerializer);
		IEntityObject::Serialize(pSerializer);
		SERIALIZE(m_trees);
	}
Example #28
0
int main(void)
{
    pc.baud(115200);

    THREAD_HANDLE ThreadHandle;

    (void)printf("Initializing mbed specific things...\r\n");

    (void)printf("doing a one time EthernetInterface::init();\r\n");
    if (EthernetInterface::init() != 0)
    {
         (void)printf("Failed EthernetInterface::init();\r\n");
         return -1;
    }
    (void)printf("done doing a one time EthernetInterface::init();\r\n");

    if (setupRealTime() != 0)
    {
         (void)printf("Failed setting up real time clock\r\n");
         return -1;
    }

    /* clear the LED light upon startup */
    red_led = 1;
    blue_led = 1;
    green_led = 1;

    alarm_type = ALARM_NONE;
    led_on = 0;

    /* clear the screen */
    lcd.cls();

    if (ThreadAPI_Create(&ThreadHandle, LED_Update_Thread, NULL) != THREADAPI_OK)
    {
        (void)printf("Error spinning LED update thread.\r\n");
        return -1;
    }

    /* initialize the IoTHubClient */
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        (void)printf("Failed on serializer_init\r\n");
    }
    else
    {
        /* Setup IoTHub client configuration */

        IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

        if (iotHubClientHandle == NULL)
        {
            (void)printf("Failed on IoTHubClient_Create\r\n");
        }
        else
        {
            unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/
            if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
            {
                printf("failure to set option \"MinimumPollingTime\"\r\n");
            }

            FrdmDevice* frdmDevice = CREATE_MODEL_INSTANCE(Contoso, FrdmDevice, true);
            if (frdmDevice == NULL)
            {
                (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                IOTHUB_CLIENT_RESULT setMessageResult = IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, frdmDevice);
                if (setMessageResult != IOTHUB_CLIENT_OK)
                {
                    (void)printf("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {
                    STRING_HANDLE commandsMetadata;

                    temp = (sensor.temp() * 9 / 5) + 32;

                    /* send the device info upon startup so that the cloud app knows
                    what commands are available and the fact that the device is up */
                    frdmDevice->ObjectType = "DeviceInfo-HW";
                    frdmDevice->ObjectName = "An ALARM device";
                    frdmDevice->Version = "1.0";
                    frdmDevice->SystemProperties.DeviceID = (char*)deviceId;
                    frdmDevice->SystemProperties.Enabled = true;

                    /* build the description of the commands on the device */
                    commandsMetadata = STRING_new();
                    if (commandsMetadata == NULL)
                    {
                        (void)printf("Failed on creating string for commands metadata\r\n");
                    }
                    else
                    {
                        /* Serialize the commands metadata as a JSON string before sending */
                        if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, FrdmDevice), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                        {
                            (void)printf("Failed serializing commands metadata\r\n");
                        }
                        else
                        {
                            frdmDevice->Commands = (char*)STRING_c_str(commandsMetadata);

                            /* Send the device information and commands metadata to the cloud */
                            {
                                unsigned char* destination;
                                size_t destinationSize;
                                if (SERIALIZE(&destination, &destinationSize, frdmDevice->ObjectName, frdmDevice->ObjectType, frdmDevice->SystemProperties, frdmDevice->Version, frdmDevice->Commands) != IOT_AGENT_OK)
                                {
                                    (void)printf("Failed to serialize\r\n");
                                }
                                else
                                {
                                    sendMessage(iotHubClientHandle, destination, destinationSize);
                                    free(destination);
                                }
                            }
                        }

                        STRING_delete(commandsMetadata);
                    }

                    frdmDevice->ObjectName = (ascii_char_ptr)deviceId;
                    frdmDevice->ObjectType = "SensorTagEvent";
                    frdmDevice->Version = "1.0";
                    frdmDevice->TargetAlarmDevice = (ascii_char_ptr)deviceId;

                    while (1)
                    {
                        unsigned char* destination;
                        size_t destinationSize;

                        (void)printf("Sending %.02f\r\n", temp);
                        frdmDevice->temp = temp;

                        if (SERIALIZE(&destination, &destinationSize, frdmDevice->ObjectName, frdmDevice->ObjectType, frdmDevice->Version, frdmDevice->TargetAlarmDevice, frdmDevice->temp) != IOT_AGENT_OK)
                        {
                            (void)printf("Failed to serialize\r\n");
                        }
                        else
                        {
                            sendMessage(iotHubClientHandle, destination, destinationSize);
                            free(destination);
                        }

                        /* schedule IoTHubClient to send events/receive commands */
                        IoTHubClient_LL_DoWork(iotHubClientHandle);
                    }
                }
                DESTROY_MODEL_INSTANCE(frdmDevice);
            }
            IoTHubClient_LL_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}
static void remote_monitoring_run(void)
{
    if (platform_init() != 0)
    {
        printf("Failed to initialize the platform.\r\n");
    }
    else
    {
        if (serializer_init(NULL) != SERIALIZER_OK)
        {
            printf("Failed on serializer_init\r\n");
        }
        else
        {
            IOTHUB_CLIENT_CONFIG config;
            IOTHUB_CLIENT_HANDLE iotHubClientHandle;

            config.deviceSasToken = NULL;
            config.deviceId = deviceId;
            config.deviceKey = deviceKey;
            config.iotHubName = hubName;
            config.iotHubSuffix = hubSuffix;
#ifndef WINCE
            config.protocol = AMQP_Protocol;
#else
            config.protocol = HTTP_Protocol;
#endif
            iotHubClientHandle = IoTHubClient_Create(&config);
            if (iotHubClientHandle == NULL)
            {
                (void)printf("Failed on IoTHubClient_CreateFromConnectionString\r\n");
            }
            else
            {
#ifdef MBED_BUILD_TIMESTAMP
                // For mbed add the certificate information
                if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
                {
                    printf("failure to set option \"TrustedCerts\"\r\n");
                }
#endif // MBED_BUILD_TIMESTAMP

                Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat);
                if (thermostat == NULL)
                {
                    (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
                }
                else
                {
                    STRING_HANDLE commandsMetadata;

                    if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
                    {
                        printf("unable to IoTHubClient_SetMessageCallback\r\n");
                    }
                    else
                    {

                        /* send the device info upon startup so that the cloud app knows
                        what commands are available and the fact that the device is up */
                        thermostat->ObjectType = "DeviceInfo";
                        thermostat->IsSimulatedDevice = false;
                        thermostat->Version = "1.0";
                        thermostat->DeviceProperties.HubEnabledState = true;
                        thermostat->DeviceProperties.DeviceID = (char*)deviceId;

                        commandsMetadata = STRING_new();
                        if (commandsMetadata == NULL)
                        {
                            (void)printf("Failed on creating string for commands metadata\r\n");
                        }
                        else
                        {
                            /* Serialize the commands metadata as a JSON string before sending */
                            if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                            {
                                (void)printf("Failed serializing commands metadata\r\n");
                            }
                            else
                            {
                                unsigned char* buffer;
                                size_t bufferSize;
                                thermostat->Commands = (char*)STRING_c_str(commandsMetadata);

                                /* Here is the actual send of the Device Info */
                                if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK)
                                {
                                    (void)printf("Failed serializing\r\n");
                                }
                                else
                                {
                                    sendMessage(iotHubClientHandle, buffer, bufferSize);
                                }

                            }

                            STRING_delete(commandsMetadata);
                        }

                        thermostat->Temperature = 50;
                        thermostat->ExternalTemperature = 55;
                        thermostat->Humidity = 50;
                        thermostat->DeviceId = (char*)deviceId;

                        while (1)
                        {
                            unsigned char*buffer;
                            size_t bufferSize;

                            float tempC = -300.0;
                            float pressurePa = -300;
                            float humidityPct = -300;

                            int sensorResult = bme280_read_sensors(&tempC, &pressurePa, &humidityPct);

                            if (sensorResult == 1)
                            {
                                thermostat->Temperature = tempC;
                                thermostat->Humidity = humidityPct;
                                printf("Humidity = %.1f%% Temperature = %.1f*C \n",
                                    humidityPct, tempC);
                                pinMode(Grn_led_pin, OUTPUT);
                            }
                            else
                            {
                                thermostat->Temperature = 404.0;
                                thermostat->Humidity = 404.0;
                                printf("Unable to read BME280 on pin %i\n", Spi_channel);
                                pinMode(Red_led_pin, OUTPUT);
                            }

                            (void)printf("Sending sensor value Temperature = %.1f*C, Humidity = %.1f%%\r\n", thermostat->Temperature, thermostat->Humidity);

                            if (SERIALIZE(&buffer, &bufferSize, thermostat->DeviceId, thermostat->Temperature, thermostat->Humidity, thermostat->ExternalTemperature) != IOT_AGENT_OK)
                            {
                                (void)printf("Failed sending sensor value\r\n");
                            }
                            else
                            {
                                sendMessage(iotHubClientHandle, buffer, bufferSize);
                            }

                            ThreadAPI_Sleep(1000);
                        }
                    }
                    close_lockfile(Lock_fd);
                    DESTROY_MODEL_INSTANCE(thermostat);
                }
                IoTHubClient_Destroy(iotHubClientHandle);
            }
            serializer_deinit();
        }
        platform_deinit();
    }
}
void remote_monitoring_run(void)
{
    if (serializer_init(NULL) != SERIALIZER_OK)
    {
        printf("Failed on serializer_init\r\n");
    }
    else
    {
		IOTHUB_CLIENT_CONFIG config;

		config.deviceId = deviceId;
		config.deviceKey = deviceKey;
		config.iotHubName = hubName;
		config.iotHubSuffix = hubSuffix;
		config.protocol = AMQP_Protocol;

		IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_Create(&config);
        if (iotHubClientHandle == NULL)
        {
            (void)printf("Failed on IoTHubClient_CreateFromConnectionString\r\n");
        }
        else
        {
            unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/
            if (IoTHubClient_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
            {
                printf("failure to set option \"MinimumPollingTime\"\r\n");
            }

#ifdef MBED_BUILD_TIMESTAMP
            // For mbed add the certificate information
            if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
            {
                printf("failure to set option \"TrustedCerts\"\r\n");
            }
#endif // MBED_BUILD_TIMESTAMP

            Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat);
            if (thermostat == NULL)
            {
                (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
            }
            else
            {
                STRING_HANDLE commandsMetadata;

                if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK)
                {
                    printf("unable to IoTHubClient_SetMessageCallback\r\n");
                }
                else
                {

                    /* send the device info upon startup so that the cloud app knows
                    what commands are available and the fact that the device is up */
                    thermostat->ObjectType = "DeviceInfo";
					thermostat->IsSimulatedDevice = false;
					thermostat->Version = "1.0";
					thermostat->DeviceProperties.HubEnabledState = true;
                    thermostat->DeviceProperties.DeviceID = (char*)deviceId;

                    commandsMetadata = STRING_new();
                    if (commandsMetadata == NULL)
                    {
                        (void)printf("Failed on creating string for commands metadata\r\n");
                    }
                    else
                    {
                        /* Serialize the commands metadata as a JSON string before sending */
                        if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK)
                        {
                            (void)printf("Failed serializing commands metadata\r\n");
                        }
                        else
                        {
                            unsigned char* buffer;
                            size_t bufferSize;
                            thermostat->Commands = (char*)STRING_c_str(commandsMetadata);

                            /* Here is the actual send of the Device Info */
                            if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK)
                            {
                                (void)printf("Failed serializing\r\n");
                            }
                            else
                            {
                                sendMessage(iotHubClientHandle, buffer, bufferSize);
                            }

                        }

                        STRING_delete(commandsMetadata);
                    }

					thermostat->Temperature = 50.0;
					thermostat->Humidity = 50.0;
					thermostat->DeviceId = (char*)deviceId;

                    while (1)
                    {
                        unsigned char*buffer;
                        size_t bufferSize;

						(void)printf("Sending sensor value Temperature = %02f, Humidity = %02f\r\n", thermostat->Temperature, thermostat->Humidity);

                        if (SERIALIZE(&buffer, &bufferSize, thermostat->Temperature, thermostat->Humidity, thermostat->DeviceId) != IOT_AGENT_OK)
                        {
                            (void)printf("Failed sending sensor value\r\n");
                        }
                        else
                        {
                            sendMessage(iotHubClientHandle, buffer, bufferSize);
                        }

                        ThreadAPI_Sleep(1000);
                    }
                }

                DESTROY_MODEL_INSTANCE(thermostat);
            }
            IoTHubClient_Destroy(iotHubClientHandle);
        }
        serializer_deinit();
    }
}