<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "ngsi/Request.h"

#include "jsonParse/jsonParse.h"
#include "jsonParse/JsonNode.h"
#include "jsonParse/jsonUpdateContextElementRequest.h"
#include "jsonParse/jsonNullTreat.h"

/* ****************************************************************************
*
* attributeDomainName -
*/
static std::string attributeDomainName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attributeDomainName"));
   reqData->ucer.res.attributeDomainName.set(value);
   return "OK";
}

/* ****************************************************************************
*
* contextAttribute -
*/
static std::string contextAttribute(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute"));
   reqData->ucer.attributeP = new ContextAttribute();
   reqData->ucer.res.contextAttributeVector.push_back(reqData->ucer.attributeP);
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeName -
*/
static std::string contextAttributeName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute name: %s", value.c_str()));
   reqData->ucer.attributeP->name = value;
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeType -
*/
static std::string contextAttributeType(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute type: %s", value.c_str()));
   reqData->ucer.attributeP->type = value;
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeValue -
*/
static std::string contextAttributeValue(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute value: %s", value.c_str()));
   reqData->ucer.attributeP->value = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadata -
*/
static std::string contextMetadata(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata"));
   reqData->ucer.metadataP = new Metadata();
   reqData->ucer.attributeP->metadataVector.push_back(reqData->ucer.metadataP);
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataName -
*/
static std::string contextMetadataName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata name '%s'", value.c_str()));
   reqData->ucer.metadataP->name = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataType -
*/
static std::string contextMetadataType(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata type '%s'", value.c_str()));
   reqData->ucer.metadataP->type = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataValue -
*/
static std::string contextMetadataValue(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata value '%s'", value.c_str()));
   reqData->ucer.metadataP->value = value;
   return "OK";
}

/* ****************************************************************************
*
* ucerParseVector -
*/
JsonNode jsonUcerParseVector[] =
{
  { "/attributeDomainName",                            attributeDomainName   },

  { "/attributes",                                     jsonNullTreat         },
  { "/attributes/attribute",                           contextAttribute      },
  { "/attributes/attribute/name",                      contextAttributeName  },
  { "/attributes/attribute/type",                      contextAttributeType  },
  { "/attributes/attribute/value",              contextAttributeValue },

  { "/attributes/attribute/metadatas",                 jsonNullTreat         },
  { "/attributes/attribute/metadatas/metadata",        contextMetadata       },
  { "/attributes/attribute/metadatas/metadata/name",   contextMetadataName   },
  { "/attributes/attribute/metadatas/metadata/type",   contextMetadataType   },
  { "/attributes/attribute/metadatas/metadata/value",  contextMetadataValue  },

  { "LAST", NULL }
};

/* ****************************************************************************
*
* ucerInit -
*/
void jsonUcerInit(ParseData* reqData)
{
  reqData->ucer.res.attributeDomainName.set("");

  reqData->ucer.attributeP = NULL;
  reqData->ucer.metadataP  = NULL;
}

/* ****************************************************************************
*
* ucerRelease -
*/
void jsonUcerRelease(ParseData* reqData)
{
  reqData->ucer.res.release();
}

/* ****************************************************************************
*
* ucerCheck -
*/
std::string jsonUcerCheck(ParseData* reqData, ConnectionInfo* ciP)
{
  return reqData->ucer.res.check(UpdateContextElement, ciP->outFormat, "", reqData->errorString, 0);
}

/* ****************************************************************************
*
* ucerPresent -
*/
void jsonUcerPresent(ParseData* reqData)
{
  reqData->ucer.res.present("");
}
<commit_msg>Fixed indentation<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "ngsi/Request.h"

#include "jsonParse/jsonParse.h"
#include "jsonParse/JsonNode.h"
#include "jsonParse/jsonUpdateContextElementRequest.h"
#include "jsonParse/jsonNullTreat.h"

/* ****************************************************************************
*
* attributeDomainName -
*/
static std::string attributeDomainName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attributeDomainName"));
   reqData->ucer.res.attributeDomainName.set(value);
   return "OK";
}

/* ****************************************************************************
*
* contextAttribute -
*/
static std::string contextAttribute(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute"));
   reqData->ucer.attributeP = new ContextAttribute();
   reqData->ucer.res.contextAttributeVector.push_back(reqData->ucer.attributeP);
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeName -
*/
static std::string contextAttributeName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute name: %s", value.c_str()));
   reqData->ucer.attributeP->name = value;
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeType -
*/
static std::string contextAttributeType(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute type: %s", value.c_str()));
   reqData->ucer.attributeP->type = value;
   return "OK";
}

/* ****************************************************************************
*
* contextAttributeValue -
*/
static std::string contextAttributeValue(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got an attribute value: %s", value.c_str()));
   reqData->ucer.attributeP->value = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadata -
*/
static std::string contextMetadata(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata"));
   reqData->ucer.metadataP = new Metadata();
   reqData->ucer.attributeP->metadataVector.push_back(reqData->ucer.metadataP);
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataName -
*/
static std::string contextMetadataName(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata name '%s'", value.c_str()));
   reqData->ucer.metadataP->name = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataType -
*/
static std::string contextMetadataType(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata type '%s'", value.c_str()));
   reqData->ucer.metadataP->type = value;
   return "OK";
}

/* ****************************************************************************
*
* contextMetadataValue -
*/
static std::string contextMetadataValue(std::string path, std::string value, ParseData* reqData)
{
   LM_T(LmtParse, ("Got a metadata value '%s'", value.c_str()));
   reqData->ucer.metadataP->value = value;
   return "OK";
}

/* ****************************************************************************
*
* ucerParseVector -
*/
JsonNode jsonUcerParseVector[] =
{
  { "/attributeDomainName",                            attributeDomainName   },

  { "/attributes",                                     jsonNullTreat         },
  { "/attributes/attribute",                           contextAttribute      },
  { "/attributes/attribute/name",                      contextAttributeName  },
  { "/attributes/attribute/type",                      contextAttributeType  },
  { "/attributes/attribute/value",                     contextAttributeValue },

  { "/attributes/attribute/metadatas",                 jsonNullTreat         },
  { "/attributes/attribute/metadatas/metadata",        contextMetadata       },
  { "/attributes/attribute/metadatas/metadata/name",   contextMetadataName   },
  { "/attributes/attribute/metadatas/metadata/type",   contextMetadataType   },
  { "/attributes/attribute/metadatas/metadata/value",  contextMetadataValue  },

  { "LAST", NULL }
};

/* ****************************************************************************
*
* ucerInit -
*/
void jsonUcerInit(ParseData* reqData)
{
  reqData->ucer.res.attributeDomainName.set("");

  reqData->ucer.attributeP = NULL;
  reqData->ucer.metadataP  = NULL;
}

/* ****************************************************************************
*
* ucerRelease -
*/
void jsonUcerRelease(ParseData* reqData)
{
  reqData->ucer.res.release();
}

/* ****************************************************************************
*
* ucerCheck -
*/
std::string jsonUcerCheck(ParseData* reqData, ConnectionInfo* ciP)
{
  return reqData->ucer.res.check(UpdateContextElement, ciP->outFormat, "", reqData->errorString, 0);
}

/* ****************************************************************************
*
* ucerPresent -
*/
void jsonUcerPresent(ParseData* reqData)
{
  reqData->ucer.res.present("");
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Nathan Binkert
 */

#include <iostream>
#include <string>
#include <sstream>

#include "base/cprintf.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/output.hh"
#include "cpu/base.hh"
#include "cpu/cpuevent.hh"
#include "cpu/thread_context.hh"
#include "cpu/profile.hh"
#include "sim/sim_exit.hh"
#include "sim/param.hh"
#include "sim/process.hh"
#include "sim/sim_events.hh"
#include "sim/system.hh"

#include "base/trace.hh"

// Hack
#include "sim/stat_control.hh"

using namespace std;

vector<BaseCPU *> BaseCPU::cpuList;

// This variable reflects the max number of threads in any CPU.  Be
// careful to only use it once all the CPUs that you care about have
// been initialized
int maxThreadsPerCPU = 1;

CPUProgressEvent::CPUProgressEvent(EventQueue *q, Tick ival,
                                   BaseCPU *_cpu)
    : Event(q, Event::Stat_Event_Pri), interval(ival),
      lastNumInst(0), cpu(_cpu)
{
    if (interval)
        schedule(curTick + interval);
}

void
CPUProgressEvent::process()
{
    Counter temp = cpu->totalInstructions();
#ifndef NDEBUG
    double ipc = double(temp - lastNumInst) / (interval / cpu->cycles(1));

    DPRINTFN("%s progress event, instructions committed: %lli, IPC: %0.8d\n",
             cpu->name(), temp - lastNumInst, ipc);
    ipc = 0.0;
#else
    cprintf("%lli: %s progress event, instructions committed: %lli\n",
            curTick, cpu->name(), temp - lastNumInst);
#endif
    lastNumInst = temp;
    schedule(curTick + interval);
}

const char *
CPUProgressEvent::description()
{
    return "CPU Progress event";
}

#if FULL_SYSTEM
BaseCPU::BaseCPU(Params *p)
    : MemObject(p->name), clock(p->clock), instCnt(0),
      params(p), number_of_threads(p->numberOfThreads), system(p->system),
      phase(p->phase)
#else
BaseCPU::BaseCPU(Params *p)
    : MemObject(p->name), clock(p->clock), params(p),
      number_of_threads(p->numberOfThreads), system(p->system),
      phase(p->phase)
#endif
{
//    currentTick = curTick;
    DPRINTF(FullCPU, "BaseCPU: Creating object, mem address %#x.\n", this);

    // add self to global list of CPUs
    cpuList.push_back(this);

    DPRINTF(FullCPU, "BaseCPU: CPU added to cpuList, mem address %#x.\n",
            this);

    if (number_of_threads > maxThreadsPerCPU)
        maxThreadsPerCPU = number_of_threads;

    // allocate per-thread instruction-based event queues
    comInstEventQueue = new EventQueue *[number_of_threads];
    for (int i = 0; i < number_of_threads; ++i)
        comInstEventQueue[i] = new EventQueue("instruction-based event queue");

    //
    // set up instruction-count-based termination events, if any
    //
    if (p->max_insts_any_thread != 0)
        for (int i = 0; i < number_of_threads; ++i)
            schedExitSimLoop("a thread reached the max instruction count",
                             p->max_insts_any_thread, 0,
                             comInstEventQueue[i]);

    if (p->max_insts_all_threads != 0) {
        // allocate & initialize shared downcounter: each event will
        // decrement this when triggered; simulation will terminate
        // when counter reaches 0
        int *counter = new int;
        *counter = number_of_threads;
        for (int i = 0; i < number_of_threads; ++i)
            new CountedExitEvent(comInstEventQueue[i],
                "all threads reached the max instruction count",
                p->max_insts_all_threads, *counter);
    }

    // allocate per-thread load-based event queues
    comLoadEventQueue = new EventQueue *[number_of_threads];
    for (int i = 0; i < number_of_threads; ++i)
        comLoadEventQueue[i] = new EventQueue("load-based event queue");

    //
    // set up instruction-count-based termination events, if any
    //
    if (p->max_loads_any_thread != 0)
        for (int i = 0; i < number_of_threads; ++i)
            schedExitSimLoop("a thread reached the max load count",
                             p->max_loads_any_thread, 0,
                             comLoadEventQueue[i]);

    if (p->max_loads_all_threads != 0) {
        // allocate & initialize shared downcounter: each event will
        // decrement this when triggered; simulation will terminate
        // when counter reaches 0
        int *counter = new int;
        *counter = number_of_threads;
        for (int i = 0; i < number_of_threads; ++i)
            new CountedExitEvent(comLoadEventQueue[i],
                "all threads reached the max load count",
                p->max_loads_all_threads, *counter);
    }

    functionTracingEnabled = false;
    if (p->functionTrace) {
        functionTraceStream = simout.find(csprintf("ftrace.%s", name()));
        currentFunctionStart = currentFunctionEnd = 0;
        functionEntryTick = p->functionTraceStart;

        if (p->functionTraceStart == 0) {
            functionTracingEnabled = true;
        } else {
            Event *e =
                new EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace>(this,
                                                                         true);
            e->schedule(p->functionTraceStart);
        }
    }
#if FULL_SYSTEM
    profileEvent = NULL;
    if (params->profile)
        profileEvent = new ProfileEvent(this, params->profile);
#endif
}

BaseCPU::Params::Params()
{
#if FULL_SYSTEM
    profile = false;
#endif
    checker = NULL;
}

void
BaseCPU::enableFunctionTrace()
{
    functionTracingEnabled = true;
}

BaseCPU::~BaseCPU()
{
}

void
BaseCPU::init()
{
    if (!params->deferRegistration)
        registerThreadContexts();
}

void
BaseCPU::startup()
{
#if FULL_SYSTEM
    if (!params->deferRegistration && profileEvent)
        profileEvent->schedule(curTick);
#endif

    if (params->progress_interval) {
        new CPUProgressEvent(&mainEventQueue, params->progress_interval,
                             this);
    }
}

void
BaseCPU::regStats()
{
    using namespace Stats;

    numCycles
        .name(name() + ".numCycles")
        .desc("number of cpu cycles simulated")
        ;

    int size = threadContexts.size();
    if (size > 1) {
        for (int i = 0; i < size; ++i) {
            stringstream namestr;
            ccprintf(namestr, "%s.ctx%d", name(), i);
            threadContexts[i]->regStats(namestr.str());
        }
    } else if (size == 1)
        threadContexts[0]->regStats(name());

#if FULL_SYSTEM
#endif
}

Tick
BaseCPU::nextCycle()
{
    Tick next_tick = curTick - phase + clock - 1;
    next_tick -= (next_tick % clock);
    next_tick += phase;
    return next_tick;
}

Tick
BaseCPU::nextCycle(Tick begin_tick)
{
    Tick next_tick = begin_tick;
    next_tick -= (next_tick % clock);
    next_tick += phase;

    while (next_tick < curTick)
        next_tick += clock;

    assert(next_tick >= curTick);
    return next_tick;
}

void
BaseCPU::registerThreadContexts()
{
    for (int i = 0; i < threadContexts.size(); ++i) {
        ThreadContext *tc = threadContexts[i];

#if FULL_SYSTEM
        int id = params->cpu_id;
        if (id != -1)
            id += i;

        tc->setCpuId(system->registerThreadContext(tc, id));
#else
        tc->setCpuId(tc->getProcessPtr()->registerThreadContext(tc));
#endif
    }
}

int
BaseCPU::findContext(ThreadContext *tc)
{
    for (int i = 0; i < threadContexts.size(); ++i) {
        if (tc == threadContexts[i])
            return i;
    }
    return 0;
}

void
BaseCPU::switchOut()
{
//    panic("This CPU doesn't support sampling!");
#if FULL_SYSTEM
    if (profileEvent && profileEvent->scheduled())
        profileEvent->deschedule();
#endif
}

void
BaseCPU::takeOverFrom(BaseCPU *oldCPU)
{
    assert(threadContexts.size() == oldCPU->threadContexts.size());

    for (int i = 0; i < threadContexts.size(); ++i) {
        ThreadContext *newTC = threadContexts[i];
        ThreadContext *oldTC = oldCPU->threadContexts[i];

        newTC->takeOverFrom(oldTC);

        CpuEvent::replaceThreadContext(oldTC, newTC);

        assert(newTC->readCpuId() == oldTC->readCpuId());
#if FULL_SYSTEM
        system->replaceThreadContext(newTC, newTC->readCpuId());
#else
        assert(newTC->getProcessPtr() == oldTC->getProcessPtr());
        newTC->getProcessPtr()->replaceThreadContext(newTC, newTC->readCpuId());
#endif

//    TheISA::compareXCs(oldXC, newXC);
    }

#if FULL_SYSTEM
    interrupts = oldCPU->interrupts;

    for (int i = 0; i < threadContexts.size(); ++i)
        threadContexts[i]->profileClear();

    // The Sampler must take care of this!
//    if (profileEvent)
//        profileEvent->schedule(curTick);
#endif
}

#if FULL_SYSTEM
BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, int _interval)
    : Event(&mainEventQueue), cpu(_cpu), interval(_interval)
{ }

void
BaseCPU::ProfileEvent::process()
{
    for (int i = 0, size = cpu->threadContexts.size(); i < size; ++i) {
        ThreadContext *tc = cpu->threadContexts[i];
        tc->profileSample();
    }

    schedule(curTick + interval);
}

void
BaseCPU::post_interrupt(int int_type)
{
    interrupts.post(int_type);
}

void
BaseCPU::post_interrupt(int int_num, int index)
{
    interrupts.post(int_num, index);
}

void
BaseCPU::clear_interrupt(int int_num, int index)
{
    interrupts.clear(int_num, index);
}

void
BaseCPU::clear_interrupts()
{
    interrupts.clear_all();
}

void
BaseCPU::serialize(std::ostream &os)
{
    SERIALIZE_SCALAR(instCnt);
    interrupts.serialize(os);
}

void
BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_SCALAR(instCnt);
    interrupts.unserialize(cp, section);
}

#endif // FULL_SYSTEM

void
BaseCPU::traceFunctionsInternal(Addr pc)
{
    if (!debugSymbolTable)
        return;

    // if pc enters different function, print new function symbol and
    // update saved range.  Otherwise do nothing.
    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
        string sym_str;
        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
                                                         currentFunctionStart,
                                                         currentFunctionEnd);

        if (!found) {
            // no symbol found: use addr as label
            sym_str = csprintf("0x%x", pc);
            currentFunctionStart = pc;
            currentFunctionEnd = pc + 1;
        }

        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
                 curTick - functionEntryTick, curTick, sym_str);
        functionEntryTick = curTick;
    }
}

DEFINE_SIM_OBJECT_CLASS_NAME("BaseCPU", BaseCPU)
<commit_msg>Set progress_interval in terms of CPU cycles.<commit_after>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Nathan Binkert
 */

#include <iostream>
#include <string>
#include <sstream>

#include "base/cprintf.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/output.hh"
#include "cpu/base.hh"
#include "cpu/cpuevent.hh"
#include "cpu/thread_context.hh"
#include "cpu/profile.hh"
#include "sim/sim_exit.hh"
#include "sim/param.hh"
#include "sim/process.hh"
#include "sim/sim_events.hh"
#include "sim/system.hh"

#include "base/trace.hh"

// Hack
#include "sim/stat_control.hh"

using namespace std;

vector<BaseCPU *> BaseCPU::cpuList;

// This variable reflects the max number of threads in any CPU.  Be
// careful to only use it once all the CPUs that you care about have
// been initialized
int maxThreadsPerCPU = 1;

CPUProgressEvent::CPUProgressEvent(EventQueue *q, Tick ival,
                                   BaseCPU *_cpu)
    : Event(q, Event::Stat_Event_Pri), interval(ival),
      lastNumInst(0), cpu(_cpu)
{
    if (interval)
        schedule(curTick + interval);
}

void
CPUProgressEvent::process()
{
    Counter temp = cpu->totalInstructions();
#ifndef NDEBUG
    double ipc = double(temp - lastNumInst) / (interval / cpu->cycles(1));

    DPRINTFN("%s progress event, instructions committed: %lli, IPC: %0.8d\n",
             cpu->name(), temp - lastNumInst, ipc);
    ipc = 0.0;
#else
    cprintf("%lli: %s progress event, instructions committed: %lli\n",
            curTick, cpu->name(), temp - lastNumInst);
#endif
    lastNumInst = temp;
    schedule(curTick + interval);
}

const char *
CPUProgressEvent::description()
{
    return "CPU Progress event";
}

#if FULL_SYSTEM
BaseCPU::BaseCPU(Params *p)
    : MemObject(p->name), clock(p->clock), instCnt(0),
      params(p), number_of_threads(p->numberOfThreads), system(p->system),
      phase(p->phase)
#else
BaseCPU::BaseCPU(Params *p)
    : MemObject(p->name), clock(p->clock), params(p),
      number_of_threads(p->numberOfThreads), system(p->system),
      phase(p->phase)
#endif
{
//    currentTick = curTick;
    DPRINTF(FullCPU, "BaseCPU: Creating object, mem address %#x.\n", this);

    // add self to global list of CPUs
    cpuList.push_back(this);

    DPRINTF(FullCPU, "BaseCPU: CPU added to cpuList, mem address %#x.\n",
            this);

    if (number_of_threads > maxThreadsPerCPU)
        maxThreadsPerCPU = number_of_threads;

    // allocate per-thread instruction-based event queues
    comInstEventQueue = new EventQueue *[number_of_threads];
    for (int i = 0; i < number_of_threads; ++i)
        comInstEventQueue[i] = new EventQueue("instruction-based event queue");

    //
    // set up instruction-count-based termination events, if any
    //
    if (p->max_insts_any_thread != 0)
        for (int i = 0; i < number_of_threads; ++i)
            schedExitSimLoop("a thread reached the max instruction count",
                             p->max_insts_any_thread, 0,
                             comInstEventQueue[i]);

    if (p->max_insts_all_threads != 0) {
        // allocate & initialize shared downcounter: each event will
        // decrement this when triggered; simulation will terminate
        // when counter reaches 0
        int *counter = new int;
        *counter = number_of_threads;
        for (int i = 0; i < number_of_threads; ++i)
            new CountedExitEvent(comInstEventQueue[i],
                "all threads reached the max instruction count",
                p->max_insts_all_threads, *counter);
    }

    // allocate per-thread load-based event queues
    comLoadEventQueue = new EventQueue *[number_of_threads];
    for (int i = 0; i < number_of_threads; ++i)
        comLoadEventQueue[i] = new EventQueue("load-based event queue");

    //
    // set up instruction-count-based termination events, if any
    //
    if (p->max_loads_any_thread != 0)
        for (int i = 0; i < number_of_threads; ++i)
            schedExitSimLoop("a thread reached the max load count",
                             p->max_loads_any_thread, 0,
                             comLoadEventQueue[i]);

    if (p->max_loads_all_threads != 0) {
        // allocate & initialize shared downcounter: each event will
        // decrement this when triggered; simulation will terminate
        // when counter reaches 0
        int *counter = new int;
        *counter = number_of_threads;
        for (int i = 0; i < number_of_threads; ++i)
            new CountedExitEvent(comLoadEventQueue[i],
                "all threads reached the max load count",
                p->max_loads_all_threads, *counter);
    }

    functionTracingEnabled = false;
    if (p->functionTrace) {
        functionTraceStream = simout.find(csprintf("ftrace.%s", name()));
        currentFunctionStart = currentFunctionEnd = 0;
        functionEntryTick = p->functionTraceStart;

        if (p->functionTraceStart == 0) {
            functionTracingEnabled = true;
        } else {
            Event *e =
                new EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace>(this,
                                                                         true);
            e->schedule(p->functionTraceStart);
        }
    }
#if FULL_SYSTEM
    profileEvent = NULL;
    if (params->profile)
        profileEvent = new ProfileEvent(this, params->profile);
#endif
}

BaseCPU::Params::Params()
{
#if FULL_SYSTEM
    profile = false;
#endif
    checker = NULL;
}

void
BaseCPU::enableFunctionTrace()
{
    functionTracingEnabled = true;
}

BaseCPU::~BaseCPU()
{
}

void
BaseCPU::init()
{
    if (!params->deferRegistration)
        registerThreadContexts();
}

void
BaseCPU::startup()
{
#if FULL_SYSTEM
    if (!params->deferRegistration && profileEvent)
        profileEvent->schedule(curTick);
#endif

    if (params->progress_interval) {
        new CPUProgressEvent(&mainEventQueue,
                             cycles(params->progress_interval),
                             this);
    }
}

void
BaseCPU::regStats()
{
    using namespace Stats;

    numCycles
        .name(name() + ".numCycles")
        .desc("number of cpu cycles simulated")
        ;

    int size = threadContexts.size();
    if (size > 1) {
        for (int i = 0; i < size; ++i) {
            stringstream namestr;
            ccprintf(namestr, "%s.ctx%d", name(), i);
            threadContexts[i]->regStats(namestr.str());
        }
    } else if (size == 1)
        threadContexts[0]->regStats(name());

#if FULL_SYSTEM
#endif
}

Tick
BaseCPU::nextCycle()
{
    Tick next_tick = curTick - phase + clock - 1;
    next_tick -= (next_tick % clock);
    next_tick += phase;
    return next_tick;
}

Tick
BaseCPU::nextCycle(Tick begin_tick)
{
    Tick next_tick = begin_tick;
    next_tick -= (next_tick % clock);
    next_tick += phase;

    while (next_tick < curTick)
        next_tick += clock;

    assert(next_tick >= curTick);
    return next_tick;
}

void
BaseCPU::registerThreadContexts()
{
    for (int i = 0; i < threadContexts.size(); ++i) {
        ThreadContext *tc = threadContexts[i];

#if FULL_SYSTEM
        int id = params->cpu_id;
        if (id != -1)
            id += i;

        tc->setCpuId(system->registerThreadContext(tc, id));
#else
        tc->setCpuId(tc->getProcessPtr()->registerThreadContext(tc));
#endif
    }
}

int
BaseCPU::findContext(ThreadContext *tc)
{
    for (int i = 0; i < threadContexts.size(); ++i) {
        if (tc == threadContexts[i])
            return i;
    }
    return 0;
}

void
BaseCPU::switchOut()
{
//    panic("This CPU doesn't support sampling!");
#if FULL_SYSTEM
    if (profileEvent && profileEvent->scheduled())
        profileEvent->deschedule();
#endif
}

void
BaseCPU::takeOverFrom(BaseCPU *oldCPU)
{
    assert(threadContexts.size() == oldCPU->threadContexts.size());

    for (int i = 0; i < threadContexts.size(); ++i) {
        ThreadContext *newTC = threadContexts[i];
        ThreadContext *oldTC = oldCPU->threadContexts[i];

        newTC->takeOverFrom(oldTC);

        CpuEvent::replaceThreadContext(oldTC, newTC);

        assert(newTC->readCpuId() == oldTC->readCpuId());
#if FULL_SYSTEM
        system->replaceThreadContext(newTC, newTC->readCpuId());
#else
        assert(newTC->getProcessPtr() == oldTC->getProcessPtr());
        newTC->getProcessPtr()->replaceThreadContext(newTC, newTC->readCpuId());
#endif

//    TheISA::compareXCs(oldXC, newXC);
    }

#if FULL_SYSTEM
    interrupts = oldCPU->interrupts;

    for (int i = 0; i < threadContexts.size(); ++i)
        threadContexts[i]->profileClear();

    // The Sampler must take care of this!
//    if (profileEvent)
//        profileEvent->schedule(curTick);
#endif
}

#if FULL_SYSTEM
BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, int _interval)
    : Event(&mainEventQueue), cpu(_cpu), interval(_interval)
{ }

void
BaseCPU::ProfileEvent::process()
{
    for (int i = 0, size = cpu->threadContexts.size(); i < size; ++i) {
        ThreadContext *tc = cpu->threadContexts[i];
        tc->profileSample();
    }

    schedule(curTick + interval);
}

void
BaseCPU::post_interrupt(int int_type)
{
    interrupts.post(int_type);
}

void
BaseCPU::post_interrupt(int int_num, int index)
{
    interrupts.post(int_num, index);
}

void
BaseCPU::clear_interrupt(int int_num, int index)
{
    interrupts.clear(int_num, index);
}

void
BaseCPU::clear_interrupts()
{
    interrupts.clear_all();
}

void
BaseCPU::serialize(std::ostream &os)
{
    SERIALIZE_SCALAR(instCnt);
    interrupts.serialize(os);
}

void
BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_SCALAR(instCnt);
    interrupts.unserialize(cp, section);
}

#endif // FULL_SYSTEM

void
BaseCPU::traceFunctionsInternal(Addr pc)
{
    if (!debugSymbolTable)
        return;

    // if pc enters different function, print new function symbol and
    // update saved range.  Otherwise do nothing.
    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
        string sym_str;
        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
                                                         currentFunctionStart,
                                                         currentFunctionEnd);

        if (!found) {
            // no symbol found: use addr as label
            sym_str = csprintf("0x%x", pc);
            currentFunctionStart = pc;
            currentFunctionEnd = pc + 1;
        }

        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
                 curTick - functionEntryTick, curTick, sym_str);
        functionEntryTick = curTick;
    }
}

DEFINE_SIM_OBJECT_CLASS_NAME("BaseCPU", BaseCPU)
<|endoftext|>


<commit_before>#pragma once

#include "table_base.hpp"

#include <vector>
#include <string>
#include <sstream>

namespace TableCesdl
{
    template <typename StreamT, typename ForeignKeyDesc>
    struct foreignKeyEx
    {
        static bool op(StreamT& stream, std::string const& name)
        {
            stream << "FOREIGN KEY(" << name << ") REFERENCES " << ForeignKeyDesc::table::c_str << "(" << ForeignKeyDesc::key::c_str << ")";
            return true;
        }
    };

    template <typename StreamT>
    struct foreignKeyEx <StreamT, TableCesdl::NotForeignKey>
    {
        static bool op(StreamT& stream, ...)
        {
            return false;
        }
    };

    template <typename TableT, typename StreamT>
    void createTableQuery(StreamT& stream, bool ignoreExisting = true, bool ignoreTableAttributes = false)
    {
        using range = boost::mpl::range_c <int, 0, boost::fusion::result_of::size <TableT>::type::value>;

        stream << "CREATE TABLE ";
        if (ignoreExisting)
            stream << "IF NOT EXISTS ";

        stream << TableT::__name;

        stream << " (\n";

        boost::mpl::for_each <range> ([&](auto index) {
            using attribute = typename std::tuple_element <decltype(index)::value, typename TableT::attributes>::type;
            std::string name = boost::fusion::extension::struct_member_name<TableT, decltype(index)::value>::call();

            stream << "\t" << name << " " << attribute::type::getName();
            if (attribute::size != 0) {
                stream << "(" << attribute::size << ")";
            }

            if (attribute::notNull)
                stream << " NOT NULL";

            if (attribute::autoIncrement)
                stream << " AUTO_INCREMENT";

            if (attribute::primaryKey)
                stream << " PRIMARY KEY";

            foreignKeyEx <StreamT, typename attribute::references>::op(stream, name);

            if (decltype(index)::value < boost::fusion::result_of::size <TableT>::type::value - 1)
                stream << ",";

            stream << "\n";
        });

        stream << ")";

        if (TableT::tableAttributes::charsetSpecified && !ignoreTableAttributes)
            stream << " CHARACTER SET " << TableT::tableAttributes::charset;

        if (TableT::tableAttributes::collateSpecified && !ignoreTableAttributes)
            stream << " COLLATE " << TableT::tableAttributes::collate;
    }

    template <typename T>
    std::string createTableQuery(bool ignoreExisting = true, bool ignoreTableAttributes = false)
    {
        std::stringstream sstr;
        createTableQuery <T>(sstr, ignoreExisting, ignoreTableAttributes);
        return sstr.str();
    }

} // namespace TableCesdl
<commit_msg>Fixed bug.<commit_after>#pragma once

#include "table_base.hpp"

#include <vector>
#include <string>
#include <sstream>

namespace TableCesdl
{
    template <typename StreamT, typename ForeignKeyDesc>
    struct foreignKeyEx
    {
        static bool op(StreamT& stream, std::string const& name)
        {
            stream << ",\n\tFOREIGN KEY(" << name << ") REFERENCES " << ForeignKeyDesc::table::c_str << ForeignKeyDesc::key::c_str;
            return true;
        }
    };

    template <typename StreamT>
    struct foreignKeyEx <StreamT, TableCesdl::NotForeignKey>
    {
        static bool op(StreamT& stream, ...)
        {
            return false;
        }
    };

    template <typename TableT, typename StreamT>
    void createTableQuery(StreamT& stream, bool ignoreExisting = true, bool ignoreTableAttributes = false)
    {
        using range = boost::mpl::range_c <int, 0, boost::fusion::result_of::size <TableT>::type::value>;

        stream << "CREATE TABLE ";
        if (ignoreExisting)
            stream << "IF NOT EXISTS ";

        stream << TableT::__name;

        stream << " (\n";

        boost::mpl::for_each <range> ([&](auto index) {
            using attribute = typename std::tuple_element <decltype(index)::value, typename TableT::attributes>::type;
            std::string name = boost::fusion::extension::struct_member_name<TableT, decltype(index)::value>::call();

            stream << "\t" << name << " " << attribute::type::getName();
            if (attribute::size != 0) {
                stream << "(" << attribute::size << ")";
            }

            if (attribute::notNull)
                stream << " NOT NULL";

            if (attribute::autoIncrement)
                stream << " AUTO_INCREMENT";

            if (attribute::primaryKey)
                stream << " PRIMARY KEY";

            if (decltype(index)::value < boost::fusion::result_of::size <TableT>::type::value - 1)
            {
                stream << ",";
                stream << "\n";
            }
        });

        boost::mpl::for_each <range> ([&](auto index) {
            using attribute = typename std::tuple_element <decltype(index)::value, typename TableT::attributes>::type;
            std::string name = boost::fusion::extension::struct_member_name<TableT, decltype(index)::value>::call();

            if (foreignKeyEx <StreamT, typename attribute::references>::op(stream, name))
                stream << "\n";
        });

        stream << ")";

        if (TableT::tableAttributes::charsetSpecified && !ignoreTableAttributes)
            stream << " CHARACTER SET " << TableT::tableAttributes::charset;

        if (TableT::tableAttributes::collateSpecified && !ignoreTableAttributes)
            stream << " COLLATE " << TableT::tableAttributes::collate;
    }

    template <typename T>
    std::string createTableQuery(bool ignoreExisting = true, bool ignoreTableAttributes = false)
    {
        std::stringstream sstr;
        createTableQuery <T>(sstr, ignoreExisting, ignoreTableAttributes);
        return sstr.str();
    }

} // namespace TableCesdl
<|endoftext|>


<commit_before>#include <boost/pool/object_pool.hpp>
#include <boost/optional.hpp>
#include "../incl/search.hpp"
#include "../structs/htable.hpp"
#include "../structs/intpq.hpp"
#include "../structs/binheap.hpp"

template <class D, class Cost> struct Node {
	typename D::State state;
	typename D::Oper pop;
	Cost g, f;
	Node *htblnxt, *parent;
	int openind;

	Node(void) : openind(-1) {}
};

template <class D, class Cost> class OpenList {
public:
	const char *kind(void) { return "binary heap"; }
	void push(Node<D, Cost> *n) { heap.push(n); }
	Node<D, Cost> *pop(void) {
		boost::optional< Node<D, Cost>* > p = heap.pop();
		if (!p)
			return NULL;
		return *p;
	}
	void pre_update(Node<D, Cost> *n) { }
	void post_update(Node<D, Cost> *n) { heap.update(n->openind); }
	bool empty(void) { return heap.empty(); }
	bool mem(Node<D, Cost> *n) { return n->openind != -1; }
private:
	struct Ops {
 			static bool pred(Node<D, Cost> *a, Node<D, Cost> *b) {
			if (a->f == b->f)
				return a->g > b->g;
			return a->f < b->f;
		}
		static void setind(Node<D, Cost> *n, int i) { n->openind = i; }
	};
	Binheap< Ops, Node<D, Cost>* > heap;
};

template <class D> struct Node <D, char> {
	typename D::State state;
	typename D::Oper pop;
	typename D::Cost g, f;
	Node *htblnxt, *parent;
	Node *nxt, *prev;

	Node(void) : nxt(NULL), prev(NULL) {}
};

template <class D> class OpenList <D, char> {
private:
	typedef typename D::Cost Cost;
public:
	static const char *kind(void) { return "bucketed"; }
	void push(Node<D, Cost> *n) { pq.push(n, n->f); }
	Node<D, Cost> *pop(void) { return pq.pop(); }
	void pre_update(Node<D, Cost> *n) { pq.rm(n); }
	void post_update(Node<D, Cost> *n) { push(n); }
	bool empty(void) { return pq.empty(); }
	bool mem(Node<D, Cost> *n) { return pq.mem(n); }
private:
	struct Ops {
		static Node<D, Cost> **nxt(Node<D, Cost> *n) { return &n->nxt; }
		static Node<D, Cost> **prev(Node<D, Cost> *n) { return &n->prev; }
	};
	Intpq< Ops, Node<D, Cost> > pq;
};

template <class D> class Astar : public Search<D> {
public:

	Result<D> search(D &d, typename D::State &s0) {
		res = Result<D>(true);

		Node<D, Cost> *n0 = init(d, s0);
		closed.add(n0);
		open.push(n0);

		while (!open.empty()) {
			Node<D, Cost> *n = open.pop();

			if (d.isgoal(n->state)) {
				handlesol(n);
				break;
			}

			expand(d, n);
		}

		res.finish();
		closed.prstats(stdout, "closed ");
		dfpair(stdout, "open list type", "%s", open.kind());

		return res;
	}

	Astar(void) : closed(30000001) {}

private:

	typedef typename D::State State;
	typedef typename D::Undo Undo;
	typedef typename D::Cost Cost;
	typedef typename D::Oper Oper;

	void expand(D &d, Node<D, Cost> *n) {
		res.expd++;
		for (unsigned int i = 0; i < d.nops(n->state); i++) {
			Oper op = d.nthop(n->state, i);
			if (op == n->pop)
				continue;
			Node<D, Cost> *k = kid(d, n, op);
			res.gend++;
			considerkid(d, k);
		}
	}

	void considerkid(D &d, Node<D, Cost> *k) {
		unsigned long h = k->state.hash();
		Node<D, Cost> *dup = closed.find(&k->state, h);
		if (dup) {
			res.dups++;
			if (k->g >= dup->g) {
				nodes.free(k);
				return;
			}
			if (!open.mem(dup))
				open.pre_update(dup);

			dup->f = dup->f - dup->g + k->g;
			dup->g = k->g;
			dup->pop = k->pop;
			dup->parent = k->parent;

			if (!open.mem(dup))
				open.push(dup);
			else
				open.post_update(dup);
			nodes.free(k);
		} else {
			closed.add(k, h);
			open.push(k);
		}
	}

	Node<D, Cost> *kid(D &d, Node<D, Cost> *parent, Oper op) {
		Node<D, Cost> *kid = nodes.construct();
		d.applyinto(kid->state, parent->state, op);
		kid->g = parent->g + d.opcost(parent->state, op);
		kid->f = kid->g + d.h(kid->state);
		kid->pop = d.revop(parent->state, op);
		kid->parent = parent;
		return kid;
	}

	Node<D, Cost> *init(D &d, State &s0) {
		Node<D, Cost> *n0 = nodes.construct();
		n0->state = s0;
		n0->g = 0;
		n0->f = d.h(s0);
		n0->pop = D::Nop;
		n0->parent = NULL;
		return n0;
	}

	void handlesol(Node<D, Cost> *n) {
		res.cost = n->g;

		for ( ; n; n = n->parent)
			res.path.push_back(n->state);
	}

	struct Closedops {
		static State *key(Node<D, Cost> *n) { return &n->state; }
		static unsigned long hash(State *s) { return s->hash(); }
		static bool eq(State *a, State *b) { return a->eq(*b); }
		static Node<D, Cost> **nxt(Node<D, Cost> *n) { return &n->htblnxt; }
	};

	Result<D> res;
	OpenList<D, Cost> open;
 	Htable< Closedops, State*, Node<D, Cost> > closed;
	boost::object_pool< Node<D, Cost> > nodes;
};<commit_msg>Remove a tab.<commit_after>#include <boost/pool/object_pool.hpp>
#include <boost/optional.hpp>
#include "../incl/search.hpp"
#include "../structs/htable.hpp"
#include "../structs/intpq.hpp"
#include "../structs/binheap.hpp"

template <class D, class Cost> struct Node {
	typename D::State state;
	typename D::Oper pop;
	Cost g, f;
	Node *htblnxt, *parent;
	int openind;

	Node(void) : openind(-1) {}
};

template <class D, class Cost> class OpenList {
public:
	const char *kind(void) { return "binary heap"; }
	void push(Node<D, Cost> *n) { heap.push(n); }
	Node<D, Cost> *pop(void) {
		boost::optional< Node<D, Cost>* > p = heap.pop();
		if (!p)
			return NULL;
		return *p;
	}
	void pre_update(Node<D, Cost> *n) { }
	void post_update(Node<D, Cost> *n) { heap.update(n->openind); }
	bool empty(void) { return heap.empty(); }
	bool mem(Node<D, Cost> *n) { return n->openind != -1; }
private:
	struct Ops {
 		static bool pred(Node<D, Cost> *a, Node<D, Cost> *b) {
			if (a->f == b->f)
				return a->g > b->g;
			return a->f < b->f;
		}
		static void setind(Node<D, Cost> *n, int i) { n->openind = i; }
	};
	Binheap< Ops, Node<D, Cost>* > heap;
};

template <class D> struct Node <D, char> {
	typename D::State state;
	typename D::Oper pop;
	typename D::Cost g, f;
	Node *htblnxt, *parent;
	Node *nxt, *prev;

	Node(void) : nxt(NULL), prev(NULL) {}
};

template <class D> class OpenList <D, char> {
private:
	typedef typename D::Cost Cost;
public:
	static const char *kind(void) { return "bucketed"; }
	void push(Node<D, Cost> *n) { pq.push(n, n->f); }
	Node<D, Cost> *pop(void) { return pq.pop(); }
	void pre_update(Node<D, Cost> *n) { pq.rm(n); }
	void post_update(Node<D, Cost> *n) { push(n); }
	bool empty(void) { return pq.empty(); }
	bool mem(Node<D, Cost> *n) { return pq.mem(n); }
private:
	struct Ops {
		static Node<D, Cost> **nxt(Node<D, Cost> *n) { return &n->nxt; }
		static Node<D, Cost> **prev(Node<D, Cost> *n) { return &n->prev; }
	};
	Intpq< Ops, Node<D, Cost> > pq;
};

template <class D> class Astar : public Search<D> {
public:

	Result<D> search(D &d, typename D::State &s0) {
		res = Result<D>(true);

		Node<D, Cost> *n0 = init(d, s0);
		closed.add(n0);
		open.push(n0);

		while (!open.empty()) {
			Node<D, Cost> *n = open.pop();

			if (d.isgoal(n->state)) {
				handlesol(n);
				break;
			}

			expand(d, n);
		}

		res.finish();
		closed.prstats(stdout, "closed ");
		dfpair(stdout, "open list type", "%s", open.kind());

		return res;
	}

	Astar(void) : closed(30000001) {}

private:

	typedef typename D::State State;
	typedef typename D::Undo Undo;
	typedef typename D::Cost Cost;
	typedef typename D::Oper Oper;

	void expand(D &d, Node<D, Cost> *n) {
		res.expd++;
		for (unsigned int i = 0; i < d.nops(n->state); i++) {
			Oper op = d.nthop(n->state, i);
			if (op == n->pop)
				continue;
			Node<D, Cost> *k = kid(d, n, op);
			res.gend++;
			considerkid(d, k);
		}
	}

	void considerkid(D &d, Node<D, Cost> *k) {
		unsigned long h = k->state.hash();
		Node<D, Cost> *dup = closed.find(&k->state, h);
		if (dup) {
			res.dups++;
			if (k->g >= dup->g) {
				nodes.free(k);
				return;
			}
			if (!open.mem(dup))
				open.pre_update(dup);

			dup->f = dup->f - dup->g + k->g;
			dup->g = k->g;
			dup->pop = k->pop;
			dup->parent = k->parent;

			if (!open.mem(dup))
				open.push(dup);
			else
				open.post_update(dup);
			nodes.free(k);
		} else {
			closed.add(k, h);
			open.push(k);
		}
	}

	Node<D, Cost> *kid(D &d, Node<D, Cost> *parent, Oper op) {
		Node<D, Cost> *kid = nodes.construct();
		d.applyinto(kid->state, parent->state, op);
		kid->g = parent->g + d.opcost(parent->state, op);
		kid->f = kid->g + d.h(kid->state);
		kid->pop = d.revop(parent->state, op);
		kid->parent = parent;
		return kid;
	}

	Node<D, Cost> *init(D &d, State &s0) {
		Node<D, Cost> *n0 = nodes.construct();
		n0->state = s0;
		n0->g = 0;
		n0->f = d.h(s0);
		n0->pop = D::Nop;
		n0->parent = NULL;
		return n0;
	}

	void handlesol(Node<D, Cost> *n) {
		res.cost = n->g;

		for ( ; n; n = n->parent)
			res.path.push_back(n->state);
	}

	struct Closedops {
		static State *key(Node<D, Cost> *n) { return &n->state; }
		static unsigned long hash(State *s) { return s->hash(); }
		static bool eq(State *a, State *b) { return a->eq(*b); }
		static Node<D, Cost> **nxt(Node<D, Cost> *n) { return &n->htblnxt; }
	};

	Result<D> res;
	OpenList<D, Cost> open;
 	Htable< Closedops, State*, Node<D, Cost> > closed;
	boost::object_pool< Node<D, Cost> > nodes;
};<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Foundation.h"
#include "OgreRenderingModule.h"
#include "RexLogicModule.h"
#include "Sky.h"

#include "../OgreRenderingModule/OgreTextureResource.h"

namespace RexLogic
{

Sky::Sky(RexLogicModule *owner) : owner_(owner), skyEnabled_(false), skyBoxImageCount_(0)
{
}

Sky::~Sky()
{
}

bool Sky::HandleRexGM_RexSky(OpenSimProtocol::NetworkEventInboundData* data)
{
    NetInMessage &msg = *data->message;
    msg.ResetReading();
    msg.SkipToFirstVariableByName("Parameter");

    // Variable block begins, should have currently (at least) 4 instances.
    size_t instance_count = msg.ReadCurrentBlockInstanceCount();
    if (instance_count < 4)
    {
        RexLogicModule::LogWarning("Generic message \"RexSky\" did not contain all the necessary data.");
        return false;
    }

    // 1st instance contains the sky type.
    OgreRenderer::SkyType type = OgreRenderer::SKYTYPE_NONE;
    type = (OgreRenderer::SkyType)boost::lexical_cast<int>(msg.ReadString());

    // 2nd instance contains the texture uuid's
    std::string image_string = msg.ReadString();
    Core::StringVector images = Ogre::StringUtil::split(image_string);

    // 3rd instance contains the curvature parameter.
    float curvature = boost::lexical_cast<float>(msg.ReadString());

    // 4th instance contains the tiling parameter.
    float tiling = boost::lexical_cast<float>(msg.ReadString());

    UpdateSky(type, images, curvature, tiling);

    return false;
}

void Sky::UpdateSky(OgreRenderer::SkyType type, const std::vector<std::string> &images, float curvature, float tiling)
{
    type_ = type;
    if (type_ == OgreRenderer::SKYTYPE_NONE)
    {
        Scene::EntityPtr sky = GetSkyEntity().lock();
        if (sky)
        {
            OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
            sky_component->CreateSky();
            return;
        }
    }

    // Suffixes are used to identify different texture positions on the skybox.
    std::map<std::string, int> indexMap;
    std::map<std::string, int>::const_iterator suffixIter;
    indexMap["_fr"] = 0; // front
    indexMap["_bk"] = 1; // back
    indexMap["_lf"] = 2; // left
    indexMap["_rt"] = 3; // right
    indexMap["_up"] = 4; // up
    indexMap["_dn"] = 5; // down

    currentSkyBoxImageCount_ = 0;
    skyBoxImageCount_ = 0;
    skyBoxImages_.clear();
    skyBoxImages_.reserve(skyBoxTextureCount);

    size_t max = std::min(images.size(), (size_t)skyBoxTextureCount);
    for(size_t n = 0; n < max; ++n)
    {
        std::string image_str = images[n];
        size_t index = n;
        if (image_str.size() < 4)
            break;

        switch(type_)
        {
        case OgreRenderer::SKYTYPE_BOX:
        {
            std::string suffix = image_str.substr(image_str.size() - 3);
            suffixIter = indexMap.find(suffix);
            if (suffixIter == indexMap.end())
                break;

            index = suffixIter->second;
            image_str = image_str.substr(0, image_str.size() - 3);

            RexUUID image_id(image_str);
            if (image_id.IsNull())
                break;

            ++skyBoxImageCount_;
            skyBoxTextures_[index] = image_id;
            break;
        }
        case OgreRenderer::SKYTYPE_DOME:
        {
            RexUUID image_id(image_str);
            skyDomeTexture_ = image_id;
            break;
        }
        case OgreRenderer::SKYTYPE_PLANE:
        {
            RexUUID image_id(image_str);
            skyPlaneTexture_ = image_id;
            break;
        }
        }
    }

    RequestSkyTextures();

    /*OgreRenderer::SkyImageData *imageData = new OgreRenderer::SkyImageData;
    imageData->index = index;
    imageData->type = type;
    imageData->curvature = curvature;
    imageData->tiling = tiling;*/
}

void Sky::CreateDefaultSky(bool show)
{
    Scene::EntityPtr sky = GetSkyEntity().lock();
    if (sky)
    {
        OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
        assert(sky_component);

        ///\todo change to CreateDefaultSky()
        sky_component->CreateSky();
    }
}

void Sky::RequestSkyTextures()
{
    boost::weak_ptr<OgreRenderer::Renderer> w_renderer = owner_->GetFramework()->GetServiceManager()->GetService
        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer);
    boost::shared_ptr<OgreRenderer::Renderer> renderer = w_renderer.lock();

    switch(type_)
    {
    case OgreRenderer::SKYTYPE_BOX:
        for(int i = 0; i < skyBoxTextureCount; ++i)
            skyBoxTextureRequests_[i] = renderer->RequestResource(skyBoxTextures_[i].ToString(),
                OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_DOME:
        skyDomeTextureRequest_ = renderer->RequestResource(skyDomeTexture_.ToString(),
            OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        skyPlaneTextureRequest_ = renderer->RequestResource(skyPlaneTexture_.ToString(),
            OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_NONE:
    default:
        break;
    }
}

void Sky::OnTextureReadyEvent(Resource::Events::ResourceReady *tex)
{
    assert(tex);

    Scene::EntityPtr sky = GetSkyEntity().lock();
    if (!sky)
    {
        RexLogicModule::LogError("Could not get SkyEntityPtr!");
        return;
    }

    OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
    assert(sky_component);

    switch(type_)
    {
    case OgreRenderer::SKYTYPE_BOX:
        for(int i = 0; i < skyBoxTextureCount; ++i)
        {
            if (tex->tag_ == skyBoxTextureRequests_[i])
                sky_component->SetSkyBoxMaterialTexture(i, tex->id_.c_str(), skyBoxImageCount_);
        }
        break;
    case OgreRenderer::SKYTYPE_DOME:
        if (tex->tag_ == skyDomeTextureRequest_)
            sky_component->SetSkyDomeMaterialTexture(tex->id_.c_str(), 0);
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        if (tex->tag_ == skyPlaneTextureRequest_)
            sky_component->SetSkyPlaneMaterialTexture(tex->id_.c_str());
        break;
    case OgreRenderer::SKYTYPE_NONE:
        sky_component->DisableSky();
        break;
    default:
        break;
    }
}

void Sky::SetSkyTexture(const RexUUID texture_id)
{
    switch(type_)
    {
    case OgreRenderer::SKYTYPE_DOME:
        skyDomeTexture_ = texture_id;
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        skyPlaneTexture_ = texture_id;
        break;
    default:
        RexLogicModule::LogError("SetSkyTexture can be used only for SkyDome and SkyPlane!");
        break;
    }
}

void Sky::SetSkyBoxTextures(const RexUUID textures[skyBoxTextureCount])
{
    if (type_ != OgreRenderer::SKYTYPE_DOME)
    {
        RexLogicModule::LogError("SetSkyBoxTextures can be used only for SkyBox!");
        return;
    }

    for(int i = 0; i < skyBoxTextureCount; ++i)
        skyBoxTextures_[i] = textures[i];
}

void Sky::FindCurrentlyActiveSky()
{
    Scene::ScenePtr scene = owner_->GetCurrentActiveScene();
    for(Scene::SceneManagerInterface::EntityIterator iter = scene->begin();
        iter != scene->end(); ++iter)
    {
        Scene::EntityInterface &entity = *iter;
        Foundation::ComponentInterfacePtr sky_component = entity.GetComponent("EC_OgreSky");
        if (sky_component.get())
        {
            cachedSkyEntity_ = scene->GetEntity(entity.GetId());
        }
    }
}

Scene::EntityWeakPtr Sky::GetSkyEntity()
{
    return cachedSkyEntity_;
}

} // namespace RexLogic
<commit_msg>Fix possible sky disappearance bug.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Foundation.h"
#include "OgreRenderingModule.h"
#include "RexLogicModule.h"
#include "Sky.h"

#include "../OgreRenderingModule/OgreTextureResource.h"

namespace RexLogic
{

Sky::Sky(RexLogicModule *owner) : owner_(owner), skyEnabled_(false), type_(OgreRenderer::SKYTYPE_NONE), skyBoxImageCount_(0)
{
}

Sky::~Sky()
{
}

bool Sky::HandleRexGM_RexSky(OpenSimProtocol::NetworkEventInboundData* data)
{
    NetInMessage &msg = *data->message;
    msg.ResetReading();
    msg.SkipToFirstVariableByName("Parameter");

    // Variable block begins, should have currently (at least) 4 instances.
    size_t instance_count = msg.ReadCurrentBlockInstanceCount();
    if (instance_count < 4)
    {
        RexLogicModule::LogWarning("Generic message \"RexSky\" did not contain all the necessary data.");
        return false;
    }

    // 1st instance contains the sky type.
    OgreRenderer::SkyType type = OgreRenderer::SKYTYPE_NONE;
    type = (OgreRenderer::SkyType)boost::lexical_cast<int>(msg.ReadString());

    // 2nd instance contains the texture uuid's
    std::string image_string = msg.ReadString();
    Core::StringVector images = Ogre::StringUtil::split(image_string);

    // 3rd instance contains the curvature parameter.
    float curvature = boost::lexical_cast<float>(msg.ReadString());

    // 4th instance contains the tiling parameter.
    float tiling = boost::lexical_cast<float>(msg.ReadString());

    UpdateSky(type, images, curvature, tiling);

    return false;
}

void Sky::UpdateSky(OgreRenderer::SkyType type, const std::vector<std::string> &images, float curvature, float tiling)
{
    type_ = type;
    if (type_ == OgreRenderer::SKYTYPE_NONE)
    {
        Scene::EntityPtr sky = GetSkyEntity().lock();
        if (sky)
        {
            OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
            sky_component->CreateSky();
            return;
        }
    }

    // Suffixes are used to identify different texture positions on the skybox.
    std::map<std::string, int> indexMap;
    std::map<std::string, int>::const_iterator suffixIter;
    indexMap["_fr"] = 0; // front
    indexMap["_bk"] = 1; // back
    indexMap["_lf"] = 2; // left
    indexMap["_rt"] = 3; // right
    indexMap["_up"] = 4; // up
    indexMap["_dn"] = 5; // down

    currentSkyBoxImageCount_ = 0;
    skyBoxImageCount_ = 0;
    skyBoxImages_.clear();
    skyBoxImages_.reserve(skyBoxTextureCount);

    size_t max = std::min(images.size(), (size_t)skyBoxTextureCount);
    for(size_t n = 0; n < max; ++n)
    {
        std::string image_str = images[n];
        size_t index = n;
        if (image_str.size() < 4)
            break;

        switch(type_)
        {
        case OgreRenderer::SKYTYPE_BOX:
        {
            std::string suffix = image_str.substr(image_str.size() - 3);
            suffixIter = indexMap.find(suffix);
            if (suffixIter == indexMap.end())
                break;

            index = suffixIter->second;
            image_str = image_str.substr(0, image_str.size() - 3);

            RexUUID image_id(image_str);
            if (image_id.IsNull())
                break;

            ++skyBoxImageCount_;
            skyBoxTextures_[index] = image_id;
            break;
        }
        case OgreRenderer::SKYTYPE_DOME:
        {
            RexUUID image_id(image_str);
            skyDomeTexture_ = image_id;
            break;
        }
        case OgreRenderer::SKYTYPE_PLANE:
        {
            RexUUID image_id(image_str);
            skyPlaneTexture_ = image_id;
            break;
        }
        }
    }

    RequestSkyTextures();

    /*OgreRenderer::SkyImageData *imageData = new OgreRenderer::SkyImageData;
    imageData->index = index;
    imageData->type = type;
    imageData->curvature = curvature;
    imageData->tiling = tiling;*/
}

void Sky::CreateDefaultSky(bool show)
{
    type_ = OgreRenderer::SKYTYPE_BOX;
    Scene::EntityPtr sky = GetSkyEntity().lock();
    if (sky)
    {
        OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
        assert(sky_component);

        ///\todo change to CreateDefaultSky()
        sky_component->CreateSky();
    }
}

void Sky::RequestSkyTextures()
{
    boost::weak_ptr<OgreRenderer::Renderer> w_renderer = owner_->GetFramework()->GetServiceManager()->GetService
        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer);
    boost::shared_ptr<OgreRenderer::Renderer> renderer = w_renderer.lock();

    switch(type_)
    {
    case OgreRenderer::SKYTYPE_BOX:
        for(int i = 0; i < skyBoxTextureCount; ++i)
            skyBoxTextureRequests_[i] = renderer->RequestResource(skyBoxTextures_[i].ToString(),
                OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_DOME:
        skyDomeTextureRequest_ = renderer->RequestResource(skyDomeTexture_.ToString(),
            OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        skyPlaneTextureRequest_ = renderer->RequestResource(skyPlaneTexture_.ToString(),
            OgreRenderer::OgreTextureResource::GetTypeStatic());
        break;
    case OgreRenderer::SKYTYPE_NONE:
    default:
        break;
    }
}

void Sky::OnTextureReadyEvent(Resource::Events::ResourceReady *tex)
{
    assert(tex);

    Scene::EntityPtr sky = GetSkyEntity().lock();
    if (!sky)
    {
        RexLogicModule::LogError("Could not get SkyEntityPtr!");
        return;
    }

    OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get());
    assert(sky_component);

    switch(type_)
    {
    case OgreRenderer::SKYTYPE_BOX:
        for(int i = 0; i < skyBoxTextureCount; ++i)
        {
            if (tex->tag_ == skyBoxTextureRequests_[i])
                sky_component->SetSkyBoxMaterialTexture(i, tex->id_.c_str(), skyBoxImageCount_);
        }
        break;
    case OgreRenderer::SKYTYPE_DOME:
        if (tex->tag_ == skyDomeTextureRequest_)
            sky_component->SetSkyDomeMaterialTexture(tex->id_.c_str(), 0);
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        if (tex->tag_ == skyPlaneTextureRequest_)
            sky_component->SetSkyPlaneMaterialTexture(tex->id_.c_str());
        break;
    default:
        break;
    }
}

void Sky::SetSkyTexture(const RexUUID texture_id)
{
    switch(type_)
    {
    case OgreRenderer::SKYTYPE_DOME:
        skyDomeTexture_ = texture_id;
        break;
    case OgreRenderer::SKYTYPE_PLANE:
        skyPlaneTexture_ = texture_id;
        break;
    default:
        RexLogicModule::LogError("SetSkyTexture can be used only for SkyDome and SkyPlane!");
        break;
    }
}

void Sky::SetSkyBoxTextures(const RexUUID textures[skyBoxTextureCount])
{
    if (type_ != OgreRenderer::SKYTYPE_DOME)
    {
        RexLogicModule::LogError("SetSkyBoxTextures can be used only for SkyBox!");
        return;
    }

    for(int i = 0; i < skyBoxTextureCount; ++i)
        skyBoxTextures_[i] = textures[i];
}

void Sky::FindCurrentlyActiveSky()
{
    Scene::ScenePtr scene = owner_->GetCurrentActiveScene();
    for(Scene::SceneManagerInterface::EntityIterator iter = scene->begin();
        iter != scene->end(); ++iter)
    {
        Scene::EntityInterface &entity = *iter;
        Foundation::ComponentInterfacePtr sky_component = entity.GetComponent("EC_OgreSky");
        if (sky_component.get())
        {
            cachedSkyEntity_ = scene->GetEntity(entity.GetId());
        }
    }
}

Scene::EntityWeakPtr Sky::GetSkyEntity()
{
    return cachedSkyEntity_;
}

} // namespace RexLogic
<|endoftext|>


<commit_before>/* CatenaStm32L0_LoRaWAN_begin.cpp	Wed Dec 05 2018 14:27:41 chwon */

/*

Module:  CatenaStm32L0_LoRaWAN_begin.cpp

Function:
	CatenaStm32L0::LoRaWAN::begin()

Version:
	V0.12.0	Wed Dec 05 2018 14:27:41 chwon	Edit level 4

Copyright notice:
	This file copyright (C) 2017-2018 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation.

Author:
	ChaeHee Won, MCCI Corporation	October 2017

Revision history:
   0.6.0  Fri Oct 13 2017 15:19:30  chwon
	Module created.

   0.10.0  Wed May 09 2018 12:15:37  chwon
	Use PIN_SX1276_ANT_SWITCH_TX_BOOST and PIN_SX1276_ANT_SWITCH_TX_RFO.

   0.12.0  Mon Nov 26 2018 15:48:10  chwon
	Remvoe PIN_SX1276_ANT_SWITCH_TX_BOOST and PIN_SX1276_ANT_SWITCH_TX_RFO
	pin initialization.

   0.12.0  Wed Dec 05 2018 14:27:41  chwon
	Use Catena addLoRaWanCommands().

*/

#ifdef ARDUINO_ARCH_STM32

#include <CatenaStm32L0.h>

#include <Catena_Log.h>
#include <mcciadk_baselib.h>

using namespace McciCatena;

/****************************************************************************\
|
|		Manifest constants & typedefs.
|
|	This is strictly for private types and constants which will not
|	be exported.
|
\****************************************************************************/

/****************************************************************************\
|
|	Read-only data.
|
|	If program is to be ROM-able, these must all be tagged read-only
|	using the ROM storage class; they may be global.
|
\****************************************************************************/

/****************************************************************************\
|
|	VARIABLES:
|
|	If program is to be ROM-able, these must be initialized
|	using the BSS keyword.  (This allows for compilers that require
|	every variable to have an initializer.)  Note that only those
|	variables owned by this module should be declared here, using the BSS
|	keyword; this allows for linkers that dislike multiple declarations
|	of objects.
|
\****************************************************************************/

bool CatenaStm32L0::LoRaWAN::begin(
	CatenaStm32L0 *pParent
	)
	{
	gLog.printf(gLog.kTrace, "+CatenaStm32L0::LoRaWAN::begin()\n");

	this->m_pCatena = pParent;
	this->m_ulDebugMask |= LOG_VERBOSE | LOG_ERRORS | LOG_BASIC;

	/* first call the base begin */
	if (! this->Arduino_LoRaWAN::begin())
		{
		gLog.printf(
			gLog.kError,
			"?CatenaStm32L0::LoRaWAN::begin:"
			" Arduino_LoRaWAN:begin failed\n"
			);
		return false;
		}

        /* set up command processor */
        pParent->addLoRaWanCommands();

	/* indicate success to the client */
	return true;
	}

#endif // ARDUINO_ARCH_STM32

/**** end of CatenaStm32L0_LoRaWAN_begin.cpp ****/
<commit_msg>Need to set up LoRaWan command before call Arduino_LoRaWAN::begin().<commit_after>/* CatenaStm32L0_LoRaWAN_begin.cpp	Mon Jan 07 2019 11:36:38 chwon */

/*

Module:  CatenaStm32L0_LoRaWAN_begin.cpp

Function:
	CatenaStm32L0::LoRaWAN::begin()

Version:
	V0.13.0	Mon Jan 07 2019 11:36:38 chwon	Edit level 5

Copyright notice:
	This file copyright (C) 2017-2018 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation.

Author:
	ChaeHee Won, MCCI Corporation	October 2017

Revision history:
   0.6.0  Fri Oct 13 2017 15:19:30  chwon
	Module created.

   0.10.0  Wed May 09 2018 12:15:37  chwon
	Use PIN_SX1276_ANT_SWITCH_TX_BOOST and PIN_SX1276_ANT_SWITCH_TX_RFO.

   0.12.0  Mon Nov 26 2018 15:48:10  chwon
	Remvoe PIN_SX1276_ANT_SWITCH_TX_BOOST and PIN_SX1276_ANT_SWITCH_TX_RFO
	pin initialization.

   0.12.0  Wed Dec 05 2018 14:27:41  chwon
	Use Catena addLoRaWanCommands().

   0.13.0  Mon Jan 07 2019 11:36:39  chwon
	Need to set up LoRaWan command before call Arduino_LoRaWAN::begin().

*/

#ifdef ARDUINO_ARCH_STM32

#include <CatenaStm32L0.h>

#include <Catena_Log.h>
#include <mcciadk_baselib.h>

using namespace McciCatena;

/****************************************************************************\
|
|		Manifest constants & typedefs.
|
|	This is strictly for private types and constants which will not
|	be exported.
|
\****************************************************************************/

/****************************************************************************\
|
|	Read-only data.
|
|	If program is to be ROM-able, these must all be tagged read-only
|	using the ROM storage class; they may be global.
|
\****************************************************************************/

/****************************************************************************\
|
|	VARIABLES:
|
|	If program is to be ROM-able, these must be initialized
|	using the BSS keyword.  (This allows for compilers that require
|	every variable to have an initializer.)  Note that only those
|	variables owned by this module should be declared here, using the BSS
|	keyword; this allows for linkers that dislike multiple declarations
|	of objects.
|
\****************************************************************************/

bool CatenaStm32L0::LoRaWAN::begin(
	CatenaStm32L0 *pParent
	)
	{
	gLog.printf(gLog.kTrace, "+CatenaStm32L0::LoRaWAN::begin()\n");

	this->m_pCatena = pParent;
	this->m_ulDebugMask |= LOG_VERBOSE | LOG_ERRORS | LOG_BASIC;

        /* first set up command processor -- just in case begin() failed */
        pParent->addLoRaWanCommands();

	/* call the base begin */
	if (! this->Arduino_LoRaWAN::begin())
		{
		gLog.printf(
			gLog.kError,
			"?CatenaStm32L0::LoRaWAN::begin:"
			" Arduino_LoRaWAN:begin failed\n"
			);
		return false;
		}

	/* indicate success to the client */
	return true;
	}

#endif // ARDUINO_ARCH_STM32

/**** end of CatenaStm32L0_LoRaWAN_begin.cpp ****/
<|endoftext|>