<commit_before>#include "DeviceManager.hpp"
#include "OpenCLManager.hpp"

#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif

using namespace fast;

DeviceManager& DeviceManager::getInstance() {
    static DeviceManager instance;
    return instance;
}

std::vector<OpenCLDevice::pointer> getDevices(oul::DeviceCriteria criteria, bool enableVisualization) {
    unsigned long * glContext = NULL;
    if(enableVisualization) {
        // Create GL context
#if defined(__APPLE__) || defined(__MACOSX)
        CGLPixelFormatAttribute attribs[] = {};
        CGLPixelFormatObj pix;
        CGLChoosePixelFormat(attribs, &pix, NULL);
        CGLContextObj appleGLContext;
        CGLCreateContext(pix, NULL, &appleGLContext);
        glContext = (unsigned long *)appleGLContext;
#else
#if _WIN32
        // TODO implement windows OpenGL stuff
        // http://msdn.microsoft.com/en-us/library/windows/desktop/dd374379%28v=vs.85%29.aspx
        HDC    hdc = wglGetCurrentDC();
        HGLRC  hglrc;

        // create a rendering context
        hglrc = wglCreateContext (hdc);
        glContext = (unsigned long *)hglrc;

        // make it the calling thread's current rendering context
        wglMakeCurrent (hdc, hglrc);
#else
        int sngBuf[] = { GLX_RGBA,
                         GLX_DOUBLEBUFFER,
                         GLX_RED_SIZE, 1,
                         GLX_GREEN_SIZE, 1,
                         GLX_BLUE_SIZE, 1,
                         GLX_DEPTH_SIZE, 12,
                         None
        };
        Display * display = XOpenDisplay(0);
        XVisualInfo* vi = glXChooseVisual(display, DefaultScreen(display), sngBuf);
        glContext = (unsigned long *)glXCreateContext(display, vi, 0, GL_TRUE);
#endif
#endif
        criteria.setCapabilityCriteria(oul::DEVICE_CAPABILITY_OPENGL_INTEROP);
    }
    oul::OpenCLManager * manager = oul::OpenCLManager::getInstance();
    std::vector<oul::PlatformDevices> platformDevices = manager->getDevices(criteria);

    std::vector<OpenCLDevice::pointer> executionDevices;
    for(unsigned int i = 0; i < platformDevices.size(); i++) {
    for(unsigned int j = 0; j < platformDevices[i].second.size(); j++) {
        std::vector<cl::Device> deviceVector;
        deviceVector.push_back(platformDevices[i].second[j]);
        OpenCLDevice * device = new OpenCLDevice(deviceVector, glContext);
        executionDevices.push_back(OpenCLDevice::pointer(device));
    }}

    return executionDevices;
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllDevices(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;
    return getDevices(criteria,enableVisualization);
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllGPUDevices(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    return getDevices(criteria,enableVisualization);
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllCPUDevices(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_CPU);
    return getDevices(criteria,enableVisualization);
}

OpenCLDevice::pointer DeviceManager::getOneGPUDevice(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
    return devices[0];
}

OpenCLDevice::pointer DeviceManager::getOneOpenCLDevice(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;

    // Check if a GPU is available first, if not choose any
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
    if(devices.size() > 0) {
        return devices[0];
    } else {
        criteria.setTypeCriteria(oul::DEVICE_TYPE_ANY);
        std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
        return devices[0];
    }
}

OpenCLDevice::pointer DeviceManager::getOneCPUDevice(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_CPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
    return devices[0];
}

Host::pointer DeviceManager::getHostDevice() {
    return Host::New();
}

void DeviceManager::setDefaultDevice(ExecutionDevice::pointer device) {
    mDefaultComputationDevice = device;
    mDefaultVisualizationDevice = device;
}

void DeviceManager::setDefaultComputationDevice(
        ExecutionDevice::pointer device) {
    mDefaultComputationDevice = device;
}

void DeviceManager::setDefaultVisualizationDevice(
        ExecutionDevice::pointer device) {
    mDefaultVisualizationDevice = device;
}

ExecutionDevice::pointer DeviceManager::getDefaultComputationDevice() {
    return mDefaultComputationDevice;
}

ExecutionDevice::pointer DeviceManager::getDefaultVisualizationDevice() {
    return mDefaultVisualizationDevice;
}

DeviceManager::DeviceManager() {
    // Set one random device as default device
    setDefaultDevice(getOneOpenCLDevice());
}
<commit_msg>Throw exception if no OpenCL devices are found<commit_after>#include "DeviceManager.hpp"
#include "OpenCLManager.hpp"
#include "Exception.hpp"

#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif

using namespace fast;

DeviceManager& DeviceManager::getInstance() {
    static DeviceManager instance;
    return instance;
}

std::vector<OpenCLDevice::pointer> getDevices(oul::DeviceCriteria criteria, bool enableVisualization) {
    unsigned long * glContext = NULL;
    if(enableVisualization) {
        // Create GL context
#if defined(__APPLE__) || defined(__MACOSX)
        CGLPixelFormatAttribute attribs[] = {};
        CGLPixelFormatObj pix;
        CGLChoosePixelFormat(attribs, &pix, NULL);
        CGLContextObj appleGLContext;
        CGLCreateContext(pix, NULL, &appleGLContext);
        glContext = (unsigned long *)appleGLContext;
#else
#if _WIN32
        // TODO implement windows OpenGL stuff
        // http://msdn.microsoft.com/en-us/library/windows/desktop/dd374379%28v=vs.85%29.aspx
        HDC    hdc = wglGetCurrentDC();
        HGLRC  hglrc;

        // create a rendering context
        hglrc = wglCreateContext (hdc);
        glContext = (unsigned long *)hglrc;

        // make it the calling thread's current rendering context
        wglMakeCurrent (hdc, hglrc);
#else
        int sngBuf[] = { GLX_RGBA,
                         GLX_DOUBLEBUFFER,
                         GLX_RED_SIZE, 1,
                         GLX_GREEN_SIZE, 1,
                         GLX_BLUE_SIZE, 1,
                         GLX_DEPTH_SIZE, 12,
                         None
        };
        Display * display = XOpenDisplay(0);
        XVisualInfo* vi = glXChooseVisual(display, DefaultScreen(display), sngBuf);
        glContext = (unsigned long *)glXCreateContext(display, vi, 0, GL_TRUE);
#endif
#endif
        criteria.setCapabilityCriteria(oul::DEVICE_CAPABILITY_OPENGL_INTEROP);
    }
    oul::OpenCLManager * manager = oul::OpenCLManager::getInstance();
    std::vector<oul::PlatformDevices> platformDevices = manager->getDevices(criteria);

    std::vector<OpenCLDevice::pointer> executionDevices;
    for(unsigned int i = 0; i < platformDevices.size(); i++) {
    for(unsigned int j = 0; j < platformDevices[i].second.size(); j++) {
        std::vector<cl::Device> deviceVector;
        deviceVector.push_back(platformDevices[i].second[j]);
        OpenCLDevice * device = new OpenCLDevice(deviceVector, glContext);
        executionDevices.push_back(OpenCLDevice::pointer(device));
    }}

    return executionDevices;
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllDevices(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;
    return getDevices(criteria,enableVisualization);
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllGPUDevices(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    return getDevices(criteria,enableVisualization);
}

std::vector<OpenCLDevice::pointer> DeviceManager::getAllCPUDevices(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_CPU);
    return getDevices(criteria,enableVisualization);
}

OpenCLDevice::pointer DeviceManager::getOneGPUDevice(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
	if(devices.size() == 0)
		throw Exception("No compatible OpenCL devices found");
    return devices[0];
}

OpenCLDevice::pointer DeviceManager::getOneOpenCLDevice(
        bool enableVisualization) {

    oul::DeviceCriteria criteria;

    // Check if a GPU is available first, if not choose any
    criteria.setTypeCriteria(oul::DEVICE_TYPE_GPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
    if(devices.size() > 0) {
        return devices[0];
    } else {
        criteria.setTypeCriteria(oul::DEVICE_TYPE_ANY);
        std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
		if(devices.size() == 0)
			throw Exception("No compatible OpenCL devices found");
        return devices[0];
    }
}

OpenCLDevice::pointer DeviceManager::getOneCPUDevice(
        bool enableVisualization) {
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(oul::DEVICE_TYPE_CPU);
    criteria.setDeviceCountCriteria(1);
    std::vector<OpenCLDevice::pointer> devices = getDevices(criteria,enableVisualization);
	if(devices.size() == 0)
		throw Exception("No compatible OpenCL devices found");
    return devices[0];
}

Host::pointer DeviceManager::getHostDevice() {
    return Host::New();
}

void DeviceManager::setDefaultDevice(ExecutionDevice::pointer device) {
    mDefaultComputationDevice = device;
    mDefaultVisualizationDevice = device;
}

void DeviceManager::setDefaultComputationDevice(
        ExecutionDevice::pointer device) {
    mDefaultComputationDevice = device;
}

void DeviceManager::setDefaultVisualizationDevice(
        ExecutionDevice::pointer device) {
    mDefaultVisualizationDevice = device;
}

ExecutionDevice::pointer DeviceManager::getDefaultComputationDevice() {
    return mDefaultComputationDevice;
}

ExecutionDevice::pointer DeviceManager::getDefaultVisualizationDevice() {
    return mDefaultVisualizationDevice;
}

DeviceManager::DeviceManager() {
    // Set one random device as default device
    setDefaultDevice(getOneOpenCLDevice());
}
<|endoftext|>


<commit_before>#include <TBasket.h>
#include <TClass.h>
#include <TLeaf.h>
#include <TTree.h>
#include <boost/concept_check.hpp>
#include "../../TypeHandler.hpp"
#include "../../TypeResolver.hpp"

using namespace scidb::root;

class TTreeHandler: public ITypeHandler
{
public:

    bool isTree(const std::string& typeName)
    {
        TClass* klass = TClass::GetClass(typeName.c_str());
        return klass && klass->InheritsFrom("TTree");
    }

    bool isBranch(const std::string& typeName)
    {
        TClass* klass = TClass::GetClass(typeName.c_str());
        return klass && klass->InheritsFrom("TBranch");
    }

    bool recognize(const std::string& typeName)
    {
        return isTree(typeName) || isBranch(typeName);
    }

    void inspect(const std::string& typeName, bool isPointer,
                 const std::string& name, const void* addr,
                 IVisitor& visitor)
    {
        if (isTree(typeName)) {
            if (visitor.pre(typeName, false, name, addr) && !isPointer) {
                TTree* tree = (TTree*)(addr);
                TObjArray* branches = tree->GetListOfBranches();
                this->iterateBranchArray(branches, visitor);
            }
            visitor.post(typeName, false, name, addr);
        }
        else if (isBranch(typeName)) {
            TBranch* branch = (TBranch*)(addr);
            this->iterateBranch(name, branch, visitor);
        }
    }

    void iterateBranch(const std::string& name, TBranch* branch, IVisitor& visitor)
    {
        TObjArray* subBranches = branch->GetListOfBranches();

        if (subBranches->GetEntries() == 0) {
            this->iterateEntries(branch, visitor);
        }
        else {
            if (visitor.pre("TBranch", false, name, branch))
                this->iterateBranchArray(subBranches, visitor);
            visitor.post("TBranch", false, name, branch);
        }
    }

    void iterateBranchArray(TObjArray* branches, IVisitor& visitor)
    {
        if (!branches)
            return;

        TIterator* iterator = branches->MakeIterator();
        TObject* obj;
        while ((obj = iterator->Next())) {
            TBranch* branch = static_cast<TBranch*>(obj);
            this->iterateBranch(branch->GetName(), branch, visitor);
        }
    }

    void iterateEntries(TBranch* branch, IVisitor& visitor)
    {
        if (!branch)
            return;

        if (visitor.pre("TBrach<Double_t>", true, branch->GetName(), branch)) {
            Long64_t count = branch->GetEntries();
            for (Long64_t i = 0; i < count; ++i) {
                branch->GetEntry(i, 1);
                TObjArray* leaves = branch->GetListOfLeaves();
                this->iterateLeaves(leaves, i, visitor);
            }
        }
        visitor.post("TBrach<Double_t>", true, branch->GetName(), branch);
    }

    void iterateLeaves(TObjArray* leaves, Long64_t i, IVisitor& visitor)
    {
        if (!leaves)
            return;

        TIterator* iterator = leaves->MakeIterator();
        TObject* obj;
        while ((obj = iterator->Next())) {
            TLeaf* leaf = static_cast<TLeaf*>(obj);
            std::string leafType = leaf->GetTypeName();

            Double_t value;
            Int_t len = leaf->GetLen();
            if (len > 1) {
                if (visitor.pre(leafType, true, leaf->GetName(), leaf)) {
                    for (Int_t j = 0; j < len; ++j) {
                        value = leaf->GetValue(j);
                        visitor.leaf(j, Data("Double_t", &value));
                    }
                }
                visitor.post(leafType, true, leaf->GetName(), leaf);
            }
            else {
                value = leaf->GetValue();
                visitor.leaf(i, Data("Double_t", &value));
            }
        }
    }
};

/// This method must register the type handlers
extern "C" void registerTypes(TypeResolver* resolver)
{
    resolver->registerHandler(new TTreeHandler());
}
<commit_msg>TTree: Allow pointing to a 'simple' branch<commit_after>#include <TBasket.h>
#include <TClass.h>
#include <TLeaf.h>
#include <TTree.h>
#include <boost/concept_check.hpp>
#include "../../TypeHandler.hpp"
#include "../../TypeResolver.hpp"

using namespace scidb::root;

class TTreeHandler: public ITypeHandler
{
public:

    bool isTree(const std::string& typeName)
    {
        TClass* klass = TClass::GetClass(typeName.c_str());
        return klass && klass->InheritsFrom("TTree");
    }

    bool isBranch(const std::string& typeName)
    {
        TClass* klass = TClass::GetClass(typeName.c_str());
        return klass && klass->InheritsFrom("TBranch");
    }

    bool isDoubleBranch(const std::string& typeName)
    {
        return typeName == "TBrach<Double_t>";
    }

    bool recognize(const std::string& typeName)
    {
        return isTree(typeName) || isBranch(typeName) || isDoubleBranch(typeName);
    }

    void inspect(const std::string& typeName, bool isPointer,
                 const std::string& name, const void* addr,
                 IVisitor& visitor)
    {
        if (isTree(typeName)) {
            if (visitor.pre(typeName, false, name, addr) && !isPointer) {
                TTree* tree = (TTree*)(addr);
                TObjArray* branches = tree->GetListOfBranches();
                this->iterateBranchArray(branches, visitor);
            }
            visitor.post(typeName, false, name, addr);
        }
        else if (isBranch(typeName)) {
            TBranch* branch = (TBranch*)(addr);
            this->iterateBranch(name, branch, visitor);
        }
        else if (isDoubleBranch(typeName)) {
            TBranch* branch = (TBranch*)(addr);
            this->iterateEntries(name, branch, visitor);
        }
    }

    void iterateBranch(const std::string& name, TBranch* branch, IVisitor& visitor)
    {
        TObjArray* subBranches = branch->GetListOfBranches();

        if (subBranches->GetEntries() == 0) {
            this->iterateEntries(branch->GetName(), branch, visitor);
        }
        else {
            if (visitor.pre("TBranch", false, name, branch))
                this->iterateBranchArray(subBranches, visitor);
            visitor.post("TBranch", false, name, branch);
        }
    }

    void iterateBranchArray(TObjArray* branches, IVisitor& visitor)
    {
        if (!branches)
            return;

        TIterator* iterator = branches->MakeIterator();
        TObject* obj;
        while ((obj = iterator->Next())) {
            TBranch* branch = static_cast<TBranch*>(obj);
            this->iterateBranch(branch->GetName(), branch, visitor);
        }
    }

    void iterateEntries(const std::string& name, TBranch* branch, IVisitor& visitor)
    {
        if (!branch)
            return;

        if (visitor.pre("TBrach<Double_t>", true, name, branch)) {
            Long64_t count = branch->GetEntries();
            for (Long64_t i = 0; i < count; ++i) {
                branch->GetEntry(i, 1);
                TObjArray* leaves = branch->GetListOfLeaves();
                this->iterateLeaves(leaves, i, visitor);
            }
        }
        visitor.post("TBrach<Double_t>", true, name, branch);
    }

    void iterateLeaves(TObjArray* leaves, Long64_t i, IVisitor& visitor)
    {
        if (!leaves)
            return;

        TIterator* iterator = leaves->MakeIterator();
        TObject* obj;
        while ((obj = iterator->Next())) {
            TLeaf* leaf = static_cast<TLeaf*>(obj);
            std::string leafType = leaf->GetTypeName();

            Double_t value;
            Int_t len = leaf->GetLen();
            if (len > 1) {
                if (visitor.pre(leafType, true, leaf->GetName(), leaf)) {
                    for (Int_t j = 0; j < len; ++j) {
                        value = leaf->GetValue(j);
                        visitor.leaf(j, Data("Double_t", &value));
                    }
                }
                visitor.post(leafType, true, leaf->GetName(), leaf);
            }
            else {
                value = leaf->GetValue();
                visitor.leaf(i, Data("Double_t", &value));
            }
        }
    }
};

/// This method must register the type handlers
extern "C" void registerTypes(TypeResolver* resolver)
{
    resolver->registerHandler(new TTreeHandler());
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospray
#include "ospray/ospray.h"
// qt
#include <iostream>
#include <QtGui>
#include <ctype.h>
// viewer
#include "ModelViewer.h"
// embree
#include "ospray/embree/common/sys/filename.h"
// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"

namespace ospray {
  namespace viewer {
    using std::cout;
    using std::endl;

    static const std::string DEFAULT_INTEGRATOR_NAME = "ao2";
    // static const std::string DEFAULT_INTEGRATOR_NAME = "eyeLight_geomID";

    /*! @{ state to be set via commandline params */

    /*! file we're saving the output to. If empty, we'll open a
      interactive viewer; otherwise we'll render to this file and
      exit. */
    std::string outFileName = "";

    /*! size of frame (when rendering offline) resp render widget
      window (when creating viewer) */
    vec2i frameResolution(-1,-1);

    /*! camera as specified on the command line */
    Ref<sg::PerspectiveCamera> cameraFromCommandLine = NULL;
    vec3f upFromCommandLine(0,0,0);

    /*! renderer as specified on the command line */
    std::string integratorFromCommandLine = "";

    /*! whether we will display the frames per second */
    bool showFPS = false;

    /*! number of samples per pixel */
    int spp = 1;

    /*! @} */

    void main(int argc, const char *argv[])
    {
      // init ospray
      ospInit(&argc,argv);
      // init qt
      QApplication *app = new QApplication(argc, (char **)argv);

      Ref<sg::World> world = new sg::World;
      Ref<sg::Renderer> renderer = new sg::Renderer;
      bool fullscreen = false;

      for (int argID=1;argID<argc;argID++) {
        const std::string arg = argv[argID];
        if (arg[0] == '-') {
          if (arg == "-o" || arg == "--render-to-file") {
            outFileName = argv[++argID];
          } else if (arg == "--size") {
            frameResolution.x = atoi(argv[++argID]);
            frameResolution.y = atoi(argv[++argID]);
          } else if (arg == "-spp" || arg == "--spp" || arg == "--samples-per-pixel") {
            spp = atoi(argv[++argID]);
          } else if (arg == "--1k" || arg == "-1k") {
            frameResolution.x = 1024;
            frameResolution.y = 1024;
          } else if (arg == "--test-sphere") {
            world = sg::createTestSphere();
          } else if (arg == "--show-fps" || arg == "-fps" || arg == "--fps") {
            showFPS = true;
          } else if (arg == "--module") {
            sg::loadModule(argv[++argID]);
          } else if (arg == "--renderer") {
            integratorFromCommandLine = argv[++argID];
          } else if (arg == "-vi") {
            if (!cameraFromCommandLine) cameraFromCommandLine = new sg::PerspectiveCamera;
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            cameraFromCommandLine->setAt(vec3f(x,y,z));
          } else if (arg == "-vp") {
            if (!cameraFromCommandLine) cameraFromCommandLine = new sg::PerspectiveCamera;
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            cameraFromCommandLine->setFrom(vec3f(x,y,z));
          } else if (arg == "-vu") {
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            upFromCommandLine = vec3f(x,y,z);
            if (cameraFromCommandLine) cameraFromCommandLine->setUp(vec3f(x,y,z));
          } else if (arg == "--fullscreen" || arg == "-fs"){
            fullscreen = true;
          } else {
            throw std::runtime_error("#osp:qtv: unknown cmdline param '"+arg+"'");
          }
        } else {
          embree::FileName fn = arg;
          if (fn.ext() == "osp" || fn.ext() == "pkd") {
            world = sg::loadOSP(fn.str());
            // } else if (fn.ext() == "atom") {
            //   world = sg::AlphaSpheres::importOspAtomFile(fn.str());
          } else if (fn.ext() == "obj") {
            sg::importOBJ(world,fn);
            // } else if (fn.ext() == "x3d") {
            //   sg::importX3D(world,fn);
          } else if (fn.ext() == "xml") {
            std::cout << "#osp:qtv: reading RIVL file " << arg << std::endl;
            world = sg::importRIVL(arg);
          } else
            sg::importFile(world,fn);

          // throw std::runtime_error("unsupported file format in '"+fn.str()+"'");
          // std::cout << "#osp:qtv: reading RIVL file " << arg << std::endl;
          //world = sg::importRIVL(arg);
        }
      }

      if (!world) {
        std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
        exit(1);
      }
      // set the current world ...
      std::cout << "#osp:qtv: setting world ..." << std::endl;
      renderer->setWorld(world);

      // -------------------------------------------------------
      // initialize renderer's integrator
      // -------------------------------------------------------
      {
        // first, check if one is specified in the scene file.
        Ref<sg::Integrator> integrator = renderer->getLastDefinedIntegrator();
        if (!integrator) {
          std::string integratorName = integratorFromCommandLine;
          if (integratorName == "")
            integratorName = DEFAULT_INTEGRATOR_NAME;
          integrator = new sg::Integrator(integratorName);
        }
        renderer->setIntegrator(integrator);
        integrator->setSPP(spp);
        integrator->commit();
      }

      // -------------------------------------------------------
      // initialize renderer's camera
      // -------------------------------------------------------
      {
        // activate the last camera defined in the scene graph (if set)
        if (cameraFromCommandLine) {
          renderer->setCamera(cameraFromCommandLine.cast<sg::Camera>());
        } else {
          renderer->setCamera(renderer->getLastDefinedCamera());
        }
        if (!renderer->camera) {
          renderer->setCamera(renderer->createDefaultCamera(upFromCommandLine));
        }
      }

      // -------------------------------------------------------
      // determine output method: offline to file, or interactive viewer
      // -------------------------------------------------------
      if (outFileName == "") {
        // create new modelviewer
        cout << "#osp:qtv: setting up to open QT viewer window" << endl;
        ModelViewer *modelViewer = new ModelViewer(renderer, fullscreen);
        // modelViewer->setFixedSize(frameResolution.x,frameResolution.y);
        modelViewer->showFrameRate(showFPS);
        std::cout << "#osp:qtv: Press 'f' to toggle fullscreen rendering mode" << endl;
        if (fullscreen){
          std::cout << "#osp:qtv: opening fullscreen viewer, press 'ESC' to quit" << endl;
          modelViewer->showFullScreen();
        } else {
          modelViewer->show();
        }

        if (frameResolution.x > 0) {
          cout << "#osp:qtv: trying to set render size to " << frameResolution.x << "x" << frameResolution.y << " pixels" << endl;

          float frame_width  = modelViewer->width() - modelViewer->renderWidget->width();
          float frame_height = modelViewer->height() - modelViewer->renderWidget->height();
          modelViewer->resize(frameResolution.x+frame_width,
                              frameResolution.y+frame_height);
          cout << "#osp:qtv: now rendering at " << modelViewer->renderWidget->width()
               << "x" << modelViewer->renderWidget->height() << " pixels." << endl;
        }

        // let qt run...
        app->exec();

        // done, closing down.
        delete modelViewer;
        delete app;
      } else {
        cout << "#osp:qtv: setting up in render-to-file mode" << endl;
        if (!renderer->frameBuffer) {
          cout << "#osp:qtv: creating default framebuffer ("
               << frameResolution.x << "x" << frameResolution.y << ")" << endl;
          renderer->frameBuffer = new sg::FrameBuffer(frameResolution);
        }
        renderer->frameBuffer->commit();
        renderer->frameBuffer->clear();

        // output file specified - render to file
        cout << "#osp:qtv: rendering frame" << endl;
        renderer->renderFrame();

        unsigned char *fbMem = renderer->frameBuffer->map();
        cout << "#osp:qtv: saving image" << endl;
        // PRINT((int*)fbMem);
        // PRINT(*(int**)fbMem);
        QImage image = QImage(fbMem,
                              renderer->frameBuffer->getSize().x,
                              renderer->frameBuffer->getSize().y,
                              QImage::Format_ARGB32).rgbSwapped().mirrored();
        // QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
        image.save(outFileName.c_str());
        renderer->frameBuffer->unmap(fbMem);
        cout << "#osp:qtv: rendered image saved to " << outFileName << endl;
        cout << "#osp:qtv: done... exiting." << endl;
        exit(0);
      }
    }
  }
}

int main(int argc, const char *argv[])
{
  try {
    ospray::viewer::main(argc,argv);
    return 0;
  } catch (std::runtime_error e) {
    std::cerr << "#osp:qtv: fatal error: " << e.what() << std::endl;
    return 1;
  }
}

<commit_msg>Add a default file output resolution and print a warning<commit_after>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospray
#include "ospray/ospray.h"
// qt
#include <iostream>
#include <QtGui>
#include <ctype.h>
// viewer
#include "ModelViewer.h"
// embree
#include "ospray/embree/common/sys/filename.h"
// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"

namespace ospray {
  namespace viewer {
    using std::cout;
    using std::endl;

    static const std::string DEFAULT_INTEGRATOR_NAME = "ao2";
    // static const std::string DEFAULT_INTEGRATOR_NAME = "eyeLight_geomID";

    /*! @{ state to be set via commandline params */

    /*! file we're saving the output to. If empty, we'll open a
      interactive viewer; otherwise we'll render to this file and
      exit. */
    std::string outFileName = "";

    /*! size of frame (when rendering offline) resp render widget
      window (when creating viewer) */
    vec2i frameResolution(-1,-1);

    /*! camera as specified on the command line */
    Ref<sg::PerspectiveCamera> cameraFromCommandLine = NULL;
    vec3f upFromCommandLine(0,0,0);

    /*! renderer as specified on the command line */
    std::string integratorFromCommandLine = "";

    /*! whether we will display the frames per second */
    bool showFPS = false;

    /*! number of samples per pixel */
    int spp = 1;

    /*! @} */

    void main(int argc, const char *argv[])
    {
      // init ospray
      ospInit(&argc,argv);
      // init qt
      QApplication *app = new QApplication(argc, (char **)argv);

      Ref<sg::World> world = new sg::World;
      Ref<sg::Renderer> renderer = new sg::Renderer;
      bool fullscreen = false;

      for (int argID=1;argID<argc;argID++) {
        const std::string arg = argv[argID];
        if (arg[0] == '-') {
          if (arg == "-o" || arg == "--render-to-file") {
            outFileName = argv[++argID];
          } else if (arg == "--size") {
            frameResolution.x = atoi(argv[++argID]);
            frameResolution.y = atoi(argv[++argID]);
          } else if (arg == "-spp" || arg == "--spp" || arg == "--samples-per-pixel") {
            spp = atoi(argv[++argID]);
          } else if (arg == "--1k" || arg == "-1k") {
            frameResolution.x = 1024;
            frameResolution.y = 1024;
          } else if (arg == "--test-sphere") {
            world = sg::createTestSphere();
          } else if (arg == "--show-fps" || arg == "-fps" || arg == "--fps") {
            showFPS = true;
          } else if (arg == "--module") {
            sg::loadModule(argv[++argID]);
          } else if (arg == "--renderer") {
            integratorFromCommandLine = argv[++argID];
          } else if (arg == "-vi") {
            if (!cameraFromCommandLine) cameraFromCommandLine = new sg::PerspectiveCamera;
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            cameraFromCommandLine->setAt(vec3f(x,y,z));
          } else if (arg == "-vp") {
            if (!cameraFromCommandLine) cameraFromCommandLine = new sg::PerspectiveCamera;
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            cameraFromCommandLine->setFrom(vec3f(x,y,z));
          } else if (arg == "-vu") {
            assert(argID+3<argc);
            float x = atof(argv[++argID]);
            float y = atof(argv[++argID]);
            float z = atof(argv[++argID]);
            upFromCommandLine = vec3f(x,y,z);
            if (cameraFromCommandLine) cameraFromCommandLine->setUp(vec3f(x,y,z));
          } else if (arg == "--fullscreen" || arg == "-fs"){
            fullscreen = true;
          } else {
            throw std::runtime_error("#osp:qtv: unknown cmdline param '"+arg+"'");
          }
        } else {
          embree::FileName fn = arg;
          if (fn.ext() == "osp" || fn.ext() == "pkd") {
            world = sg::loadOSP(fn.str());
            // } else if (fn.ext() == "atom") {
            //   world = sg::AlphaSpheres::importOspAtomFile(fn.str());
          } else if (fn.ext() == "obj") {
            sg::importOBJ(world,fn);
            // } else if (fn.ext() == "x3d") {
            //   sg::importX3D(world,fn);
          } else if (fn.ext() == "xml") {
            std::cout << "#osp:qtv: reading RIVL file " << arg << std::endl;
            world = sg::importRIVL(arg);
          } else
            sg::importFile(world,fn);

          // throw std::runtime_error("unsupported file format in '"+fn.str()+"'");
          // std::cout << "#osp:qtv: reading RIVL file " << arg << std::endl;
          //world = sg::importRIVL(arg);
        }
      }

      if (!world) {
        std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
        exit(1);
      }
      // set the current world ...
      std::cout << "#osp:qtv: setting world ..." << std::endl;
      renderer->setWorld(world);

      // -------------------------------------------------------
      // initialize renderer's integrator
      // -------------------------------------------------------
      {
        // first, check if one is specified in the scene file.
        Ref<sg::Integrator> integrator = renderer->getLastDefinedIntegrator();
        if (!integrator) {
          std::string integratorName = integratorFromCommandLine;
          if (integratorName == "")
            integratorName = DEFAULT_INTEGRATOR_NAME;
          integrator = new sg::Integrator(integratorName);
        }
        renderer->setIntegrator(integrator);
        integrator->setSPP(spp);
        integrator->commit();
      }

      // -------------------------------------------------------
      // initialize renderer's camera
      // -------------------------------------------------------
      {
        // activate the last camera defined in the scene graph (if set)
        if (cameraFromCommandLine) {
          renderer->setCamera(cameraFromCommandLine.cast<sg::Camera>());
        } else {
          renderer->setCamera(renderer->getLastDefinedCamera());
        }
        if (!renderer->camera) {
          renderer->setCamera(renderer->createDefaultCamera(upFromCommandLine));
        }
      }

      // -------------------------------------------------------
      // determine output method: offline to file, or interactive viewer
      // -------------------------------------------------------
      if (outFileName == "") {
        // create new modelviewer
        cout << "#osp:qtv: setting up to open QT viewer window" << endl;
        ModelViewer *modelViewer = new ModelViewer(renderer, fullscreen);
        // modelViewer->setFixedSize(frameResolution.x,frameResolution.y);
        modelViewer->showFrameRate(showFPS);
        std::cout << "#osp:qtv: Press 'f' to toggle fullscreen rendering mode" << endl;
        if (fullscreen){
          std::cout << "#osp:qtv: opening fullscreen viewer, press 'ESC' to quit" << endl;
          modelViewer->showFullScreen();
        } else {
          modelViewer->show();
        }

        if (frameResolution.x > 0) {
          cout << "#osp:qtv: trying to set render size to " << frameResolution.x << "x" << frameResolution.y << " pixels" << endl;

          float frame_width  = modelViewer->width() - modelViewer->renderWidget->width();
          float frame_height = modelViewer->height() - modelViewer->renderWidget->height();
          modelViewer->resize(frameResolution.x+frame_width,
                              frameResolution.y+frame_height);
          cout << "#osp:qtv: now rendering at " << modelViewer->renderWidget->width()
               << "x" << modelViewer->renderWidget->height() << " pixels." << endl;
        }

        // let qt run...
        app->exec();

        // done, closing down.
        delete modelViewer;
        delete app;
      } else {
        cout << "#osp:qtv: setting up in render-to-file mode" << endl;
        if (frameResolution == vec2i(-1, -1)) {
          cout << "#osp:qtv: Warning! no resolution specified, defaulting to 1280x720" << endl;
          frameResolution = vec2i(1280, 720);
        }
        if (!renderer->frameBuffer) {
          cout << "#osp:qtv: creating default framebuffer ("
               << frameResolution.x << "x" << frameResolution.y << ")" << endl;
          renderer->frameBuffer = new sg::FrameBuffer(frameResolution);
        }
        renderer->frameBuffer->commit();
        renderer->frameBuffer->clear();

        // output file specified - render to file
        cout << "#osp:qtv: rendering frame" << endl;
        renderer->renderFrame();

        unsigned char *fbMem = renderer->frameBuffer->map();
        cout << "#osp:qtv: saving image" << endl;
        // PRINT((int*)fbMem);
        // PRINT(*(int**)fbMem);
        QImage image = QImage(fbMem,
                              renderer->frameBuffer->getSize().x,
                              renderer->frameBuffer->getSize().y,
                              QImage::Format_ARGB32).rgbSwapped().mirrored();
        // QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
        image.save(outFileName.c_str());
        renderer->frameBuffer->unmap(fbMem);
        cout << "#osp:qtv: rendered image saved to " << outFileName << endl;
        cout << "#osp:qtv: done... exiting." << endl;
        exit(0);
      }
    }
  }
}

int main(int argc, const char *argv[])
{
  try {
    ospray::viewer::main(argc,argv);
    return 0;
  } catch (std::runtime_error e) {
    std::cerr << "#osp:qtv: fatal error: " << e.what() << std::endl;
    return 1;
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CordioBLE.h"
#include "CordioHCIDriver.h"
#include "hci_defs.h"
#include "hci_api.h"
#include "hci_cmd.h"
#include "hci_core.h"
#include "bstream.h"
#include "wsf_buf.h"
#include <stdbool.h>
#include "hci_mbed_os_adaptation.h"
#include "H4TransportDriver.h"
#include "OdinCordioInterface.h"

namespace ble {
namespace vendor {
namespace odin_w2 {

class HCIDriver : public cordio::CordioHCIDriver {
public:
    HCIDriver(cordio::CordioHCITransportDriver &transport_driver, PinName shutdown_name, PinName hci_rts_name) :
        cordio::CordioHCIDriver(transport_driver),
        shutdown(shutdown_name, 0),
        hci_rts(hci_rts_name, 0),
        service_pack_index(0),
        service_pack_transfered(false) {
    };

    virtual cordio::buf_pool_desc_t get_buffer_pool_description();

    virtual void do_initialize();

    virtual void do_terminate();

    virtual void start_reset_sequence();

    virtual void handle_reset_sequence(uint8_t *pMsg);

private:
    void start_service_pack_transfer(void)
    {
        service_pack_index = 0;
        service_pack_transfered = false;
        send_service_pack_command();
    }

    void send_service_pack_command(void)
    {
        uint16_t cmd_len = odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN];
        cmd_opcode_ack_expected = (odin_service_pack[service_pack_index + 2] << 8) | odin_service_pack[service_pack_index + 1];
        uint8_t *pBuf = hciCmdAlloc(cmd_opcode_ack_expected, cmd_len);
        if (pBuf) {
            memcpy(pBuf, odin_service_pack + service_pack_index + 1, cmd_len + HCI_CMD_HDR_LEN);
            hciCmdSend(pBuf);
        } else {
            printf("Error cannot allocate memory for the buffer");
        }
    }

    void ack_service_pack_command(uint16_t opcode, uint8_t *msg)
    {
        /* check if response opcode is same as expected command opcode */
        MBED_ASSERT (cmd_opcode_ack_expected == opcode);

        /* update service pack index */
        service_pack_index += (1 + HCI_CMD_HDR_LEN + odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN]);

        if (service_pack_index < service_pack_size)
            send_service_pack_command();
        else if (opcode == HCID_VS_WRITE_BD_ADDR) {
           /* send an HCI Reset command to start the sequence */
            HciResetCmd();
            service_pack_transfered = true;
        } else {
            /* send BT device hardware address write command */
            send_hci_vs_cmd(HCID_VS_WRITE_BD_ADDR);
            cmd_opcode_ack_expected = HCID_VS_WRITE_BD_ADDR;
        }
    }

    void hci_read_resolving_list_size(void)
    {
        /* if LL Privacy is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_PRIVACY) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_PRIVACY)) {
            /* send next command in sequence */
            HciLeReadResolvingListSize();
        } else {
            hciCoreCb.resListSize = 0;

            /* send next command in sequence */
            hci_read_max_data_len();
        }
    }

    void hci_read_max_data_len(void)
    {
        /* if LE Data Packet Length Extensions is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_DATA_LEN_EXT) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_DATA_LEN_EXT)) {
            /* send next command in sequence */
            HciLeReadMaxDataLen();
        } else {
            /* send next command in sequence */
            HciLeRandCmd();
        }
    }

    DigitalOut      shutdown;                       // power/shutdown pin for bt device
    DigitalOut      hci_rts;                        // request to sent pin
    size_t          service_pack_index;             // Index of command to be recently sent over hci
    bool            service_pack_transfered;        // Flag to notify if service pack is completely transferred or not
    uint16_t        cmd_opcode_ack_expected;        // Command against which acknowledgment is expected
    uint32_t        service_pack_size;              // size of service pack
    char            *odin_service_pack ;            // Service pack needs to be provided by driver
    vs_cmd_send_t   send_hci_vs_cmd ;               // callback function to call vendor specific call handler

};

} // namespace odin_w2
} // namespace vendor
} // namespace ble

ble::vendor::cordio::buf_pool_desc_t ble::vendor::odin_w2::HCIDriver::get_buffer_pool_description()
{
    // Use default buffer pool
    return ble::vendor::cordio::CordioHCIDriver::get_default_buffer_pool_description();
}

void ble::vendor::odin_w2::HCIDriver::do_initialize()
{
    cordio_callback_s    callback;

    hci_rts = 1;            // Flow Control is OFF

    shutdown = 0;           // BT Power is OFF
    wait_ms(20);
    shutdown = 1;           // BT Power is ON
    wait_ms(500);

    hci_rts = 0;            // Flow Control is ON

    /* ODIN ble driver initialization function  */
    cbCordio_Btinit(&callback);

    odin_service_pack = callback.Service_pack;
    send_hci_vs_cmd = callback.vs_command_callback;
    service_pack_size = callback.service_pack_size;
}

void ble::vendor::odin_w2::HCIDriver::do_terminate()
{

}

void ble::vendor::odin_w2::HCIDriver::start_reset_sequence()
{
    /* Update baudrate of ble to speed up setup time */
    send_hci_vs_cmd(HCID_VS_UPDATE_UART_BAUD_RATE);

}

void ble::vendor::odin_w2::HCIDriver::handle_reset_sequence(uint8_t *pMsg)
{
    uint16_t       opcode;
    static uint8_t randCnt;

    /* if event is a command complete event */
    if (*pMsg == HCI_CMD_CMPL_EVT) {
        /* parse parameters */
        pMsg += HCI_EVT_HDR_LEN;
        pMsg++;                   /* skip num packets */
        BSTREAM_TO_UINT16(opcode, pMsg);
        pMsg++;                   /* skip status */

        if (opcode == HCID_VS_UPDATE_UART_BAUD_RATE) {
            update_uart_baud_rate();
            start_service_pack_transfer();
            return;
        }

        if (service_pack_transfered == false) {
            ack_service_pack_command(opcode, pMsg);
            return;
        }

        /* decode opcode */
        switch (opcode) {

            case HCI_OPCODE_RESET:
                /* Send (fast and slow) clock configuration command */
                send_hci_vs_cmd(HCID_VS_FAST_CLOCK_CONFIG_BTIP);
                break;

            case HCID_VS_FAST_CLOCK_CONFIG_BTIP:
                /* Send deep-sleep behavior control command (setting retransmission, inactivity and rts pulse width for Bt) */
                send_hci_vs_cmd(HCID_VS_HCILL_PARS_CFG);
                break;

            case HCID_VS_HCILL_PARS_CFG:
                /* Send sleep mode configuration command */
                send_hci_vs_cmd(HCID_VS_SLEEP_PROTOCOLS_CFG);
                break;

            case HCID_VS_SLEEP_PROTOCOLS_CFG:
                /* initialize rand command count */
                randCnt = 0;

                /* send next command in sequence */
                HciSetEventMaskCmd((uint8_t *)hciEventMask);
                break;

            case HCI_OPCODE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciLeSetEventMaskCmd((uint8_t *)hciLeEventMask);
                break;

            case HCI_OPCODE_LE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciSetEventMaskPage2Cmd((uint8_t *)hciEventMaskPage2);
                break;

            case HCI_OPCODE_SET_EVENT_MASK_PAGE2:
                /* send next command in sequence */
                HciReadBdAddrCmd();
                break;

            case HCI_OPCODE_READ_BD_ADDR:
                /* parse and store event parameters */
                BdaCpy(hciCoreCb.bdAddr, pMsg);

                /* send next command in sequence */
                HciLeReadBufSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_BUF_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.bufSize, pMsg);
                BSTREAM_TO_UINT8(hciCoreCb.numBufs, pMsg);

                /* initialize ACL buffer accounting */
                hciCoreCb.availBufs = hciCoreCb.numBufs;

                /* send next command in sequence */
                HciLeReadSupStatesCmd();
                break;

            case HCI_OPCODE_LE_READ_SUP_STATES:
                /* parse and store event parameters */
                memcpy(hciCoreCb.leStates, pMsg, HCI_LE_STATES_LEN);

                /* send next command in sequence */
                HciLeReadWhiteListSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_WHITE_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.whiteListSize, pMsg);

                /* send next command in sequence */
                HciLeReadLocalSupFeatCmd();
                break;

            case HCI_OPCODE_LE_READ_LOCAL_SUP_FEAT:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.leSupFeat, pMsg);

                /* send next command in sequence */
                hci_read_resolving_list_size();
                break;

            case HCI_OPCODE_LE_READ_RES_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.resListSize, pMsg);

                /* send next command in sequence */
                hci_read_max_data_len();
                break;

            case HCI_OPCODE_LE_READ_MAX_DATA_LEN:
                uint16_t maxTxOctets;
                uint16_t maxTxTime;

                BSTREAM_TO_UINT16(maxTxOctets, pMsg);
                BSTREAM_TO_UINT16(maxTxTime, pMsg);

               /* use Controller's maximum supported payload octets and packet duration times
                * for transmission as Host's suggested values for maximum transmission number
                * of payload octets and maximum packet transmission time for new connections.
                */
                HciLeWriteDefDataLen(maxTxOctets, maxTxTime);
                break;

            case HCI_OPCODE_LE_WRITE_DEF_DATA_LEN:
                if (hciCoreCb.extResetSeq) {
                    /* send first extended command */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                } else {
                    /* initialize extended parameters */
                    hciCoreCb.maxAdvDataLen = 0;
                    hciCoreCb.numSupAdvSets = 0;
                    hciCoreCb.perAdvListSize = 0;

                    /* send next command in sequence */
                    HciLeRandCmd();
                }
                break;

            case HCI_OPCODE_LE_READ_MAX_ADV_DATA_LEN:
            case HCI_OPCODE_LE_READ_NUM_SUP_ADV_SETS:
            case HCI_OPCODE_LE_READ_PER_ADV_LIST_SIZE:
                if (hciCoreCb.extResetSeq) {
                    /* send next extended command in sequence */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                }
                break;

            case HCI_OPCODE_LE_RAND:
                /* check if need to send second rand command */
                if (randCnt < (HCI_RESET_RAND_CNT - 1)) {
                    randCnt++;
                    HciLeRandCmd();
                } else {
                    signal_reset_sequence_done();
                }
                break;

            default:
                break;
        }
    }
}

ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
    static ble::vendor::cordio::H4TransportDriver transport_driver (/* cbCFG_PIO_PIN_BT_HCI_TX */ PG_14,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RX */ PC_7,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_CTS */ PG_15,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12,
                                                                    115200);
    static ble::vendor::odin_w2::HCIDriver hci_driver ( transport_driver,
                                                        /* cbCFG_PIO_PIN_BT_ENABLE  */ PG_7,
                                                        /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12);

    return hci_driver;
}
<commit_msg>Generate BLE Random Static Address on U-blox Odin-W2 platform<commit_after>/*
 * Copyright (c) 2018 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CordioBLE.h"
#include "CordioHCIDriver.h"
#include "hci_defs.h"
#include "hci_api.h"
#include "hci_cmd.h"
#include "hci_core.h"
#include "bstream.h"
#include "wsf_buf.h"
#include <stdbool.h>
#include "hci_mbed_os_adaptation.h"
#include "H4TransportDriver.h"
#include "OdinCordioInterface.h"

namespace ble {
namespace vendor {
namespace odin_w2 {

class HCIDriver : public cordio::CordioHCIDriver {
public:
    HCIDriver(cordio::CordioHCITransportDriver &transport_driver, PinName shutdown_name, PinName hci_rts_name) :
        cordio::CordioHCIDriver(transport_driver),
        shutdown(shutdown_name, 0),
        hci_rts(hci_rts_name, 0),
        service_pack_index(0),
        service_pack_transfered(false) {
    };

    virtual cordio::buf_pool_desc_t get_buffer_pool_description();

    virtual void do_initialize();

    virtual void do_terminate();

    virtual void start_reset_sequence();

    virtual void handle_reset_sequence(uint8_t *pMsg);

private:
    void start_service_pack_transfer(void)
    {
        service_pack_index = 0;
        service_pack_transfered = false;
        send_service_pack_command();
    }

    void send_service_pack_command(void)
    {
        uint16_t cmd_len = odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN];
        cmd_opcode_ack_expected = (odin_service_pack[service_pack_index + 2] << 8) | odin_service_pack[service_pack_index + 1];
        uint8_t *pBuf = hciCmdAlloc(cmd_opcode_ack_expected, cmd_len);
        if (pBuf) {
            memcpy(pBuf, odin_service_pack + service_pack_index + 1, cmd_len + HCI_CMD_HDR_LEN);
            hciCmdSend(pBuf);
        } else {
            printf("Error cannot allocate memory for the buffer");
        }
    }

    void ack_service_pack_command(uint16_t opcode, uint8_t *msg)
    {
        /* check if response opcode is same as expected command opcode */
        MBED_ASSERT (cmd_opcode_ack_expected == opcode);

        /* update service pack index */
        service_pack_index += (1 + HCI_CMD_HDR_LEN + odin_service_pack[service_pack_index + HCI_CMD_HDR_LEN]);

        if (service_pack_index < service_pack_size)
            send_service_pack_command();
        else if (opcode == HCID_VS_WRITE_BD_ADDR) {
           /* send an HCI Reset command to start the sequence */
            HciResetCmd();
            service_pack_transfered = true;
        } else {
            /* send BT device hardware address write command */
            send_hci_vs_cmd(HCID_VS_WRITE_BD_ADDR);
            cmd_opcode_ack_expected = HCID_VS_WRITE_BD_ADDR;
        }
    }

    void hci_read_resolving_list_size(void)
    {
        /* if LL Privacy is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_PRIVACY) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_PRIVACY)) {
            /* send next command in sequence */
            HciLeReadResolvingListSize();
        } else {
            hciCoreCb.resListSize = 0;

            /* send next command in sequence */
            hci_read_max_data_len();
        }
    }

    void hci_read_max_data_len(void)
    {
        /* if LE Data Packet Length Extensions is supported by Controller and included */
        if ((hciCoreCb.leSupFeat & HCI_LE_SUP_FEAT_DATA_LEN_EXT) &&
            (hciLeSupFeatCfg & HCI_LE_SUP_FEAT_DATA_LEN_EXT)) {
            /* send next command in sequence */
            HciLeReadMaxDataLen();
        } else {
            /* send next command in sequence */
            HciLeRandCmd();
        }
    }

    DigitalOut      shutdown;                       // power/shutdown pin for bt device
    DigitalOut      hci_rts;                        // request to sent pin
    size_t          service_pack_index;             // Index of command to be recently sent over hci
    bool            service_pack_transfered;        // Flag to notify if service pack is completely transferred or not
    uint16_t        cmd_opcode_ack_expected;        // Command against which acknowledgment is expected
    uint32_t        service_pack_size;              // size of service pack
    char            *odin_service_pack ;            // Service pack needs to be provided by driver
    vs_cmd_send_t   send_hci_vs_cmd ;               // callback function to call vendor specific call handler

};

} // namespace odin_w2
} // namespace vendor
} // namespace ble

ble::vendor::cordio::buf_pool_desc_t ble::vendor::odin_w2::HCIDriver::get_buffer_pool_description()
{
    // Use default buffer pool
    return ble::vendor::cordio::CordioHCIDriver::get_default_buffer_pool_description();
}

void ble::vendor::odin_w2::HCIDriver::do_initialize()
{
    cordio_callback_s    callback;

    hci_rts = 1;            // Flow Control is OFF

    shutdown = 0;           // BT Power is OFF
    wait_ms(20);
    shutdown = 1;           // BT Power is ON
    wait_ms(500);

    hci_rts = 0;            // Flow Control is ON

    /* ODIN ble driver initialization function  */
    cbCordio_Btinit(&callback);

    odin_service_pack = callback.Service_pack;
    send_hci_vs_cmd = callback.vs_command_callback;
    service_pack_size = callback.service_pack_size;
}

void ble::vendor::odin_w2::HCIDriver::do_terminate()
{

}

void ble::vendor::odin_w2::HCIDriver::start_reset_sequence()
{
    /* Update baudrate of ble to speed up setup time */
    send_hci_vs_cmd(HCID_VS_UPDATE_UART_BAUD_RATE);

}

void ble::vendor::odin_w2::HCIDriver::handle_reset_sequence(uint8_t *pMsg)
{
    uint16_t       opcode;
    static uint8_t randCnt;

    /* if event is a command complete event */
    if (*pMsg == HCI_CMD_CMPL_EVT) {
        /* parse parameters */
        pMsg += HCI_EVT_HDR_LEN;
        pMsg++;                   /* skip num packets */
        BSTREAM_TO_UINT16(opcode, pMsg);
        pMsg++;                   /* skip status */

        if (opcode == HCID_VS_UPDATE_UART_BAUD_RATE) {
            update_uart_baud_rate();
            start_service_pack_transfer();
            return;
        }

        if (service_pack_transfered == false) {
            ack_service_pack_command(opcode, pMsg);
            return;
        }

        /* decode opcode */
        switch (opcode) {

            case HCI_OPCODE_RESET:
                /* Send (fast and slow) clock configuration command */
                send_hci_vs_cmd(HCID_VS_FAST_CLOCK_CONFIG_BTIP);
                break;

            case HCID_VS_FAST_CLOCK_CONFIG_BTIP:
                /* Send deep-sleep behavior control command (setting retransmission, inactivity and rts pulse width for Bt) */
                send_hci_vs_cmd(HCID_VS_HCILL_PARS_CFG);
                break;

            case HCID_VS_HCILL_PARS_CFG:
                /* Send sleep mode configuration command */
                send_hci_vs_cmd(HCID_VS_SLEEP_PROTOCOLS_CFG);
                break;

            case HCID_VS_SLEEP_PROTOCOLS_CFG:
                /* initialize rand command count */
                randCnt = 0;

                /* send next command in sequence */
                HciSetEventMaskCmd((uint8_t *)hciEventMask);
                break;

            case HCI_OPCODE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciLeSetEventMaskCmd((uint8_t *)hciLeEventMask);
                break;

            case HCI_OPCODE_LE_SET_EVENT_MASK:
                /* send next command in sequence */
                HciSetEventMaskPage2Cmd((uint8_t *)hciEventMaskPage2);
                break;

            case HCI_OPCODE_SET_EVENT_MASK_PAGE2:
                /* send next command in sequence */
                HciReadBdAddrCmd();
                break;

            case HCI_OPCODE_READ_BD_ADDR:
                /* parse and store event parameters */
                BdaCpy(hciCoreCb.bdAddr, pMsg);

                /* send next command in sequence */
                HciLeReadBufSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_BUF_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.bufSize, pMsg);
                BSTREAM_TO_UINT8(hciCoreCb.numBufs, pMsg);

                /* initialize ACL buffer accounting */
                hciCoreCb.availBufs = hciCoreCb.numBufs;

                /* send next command in sequence */
                HciLeReadSupStatesCmd();
                break;

            case HCI_OPCODE_LE_READ_SUP_STATES:
                /* parse and store event parameters */
                memcpy(hciCoreCb.leStates, pMsg, HCI_LE_STATES_LEN);

                /* send next command in sequence */
                HciLeReadWhiteListSizeCmd();
                break;

            case HCI_OPCODE_LE_READ_WHITE_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.whiteListSize, pMsg);

                /* send next command in sequence */
                HciLeReadLocalSupFeatCmd();
                break;

            case HCI_OPCODE_LE_READ_LOCAL_SUP_FEAT:
                /* parse and store event parameters */
                BSTREAM_TO_UINT16(hciCoreCb.leSupFeat, pMsg);

                /* send next command in sequence */
                hci_read_resolving_list_size();
                break;

            case HCI_OPCODE_LE_READ_RES_LIST_SIZE:
                /* parse and store event parameters */
                BSTREAM_TO_UINT8(hciCoreCb.resListSize, pMsg);

                /* send next command in sequence */
                hci_read_max_data_len();
                break;

            case HCI_OPCODE_LE_READ_MAX_DATA_LEN:
                uint16_t maxTxOctets;
                uint16_t maxTxTime;

                BSTREAM_TO_UINT16(maxTxOctets, pMsg);
                BSTREAM_TO_UINT16(maxTxTime, pMsg);

               /* use Controller's maximum supported payload octets and packet duration times
                * for transmission as Host's suggested values for maximum transmission number
                * of payload octets and maximum packet transmission time for new connections.
                */
                HciLeWriteDefDataLen(maxTxOctets, maxTxTime);
                break;

            case HCI_OPCODE_LE_WRITE_DEF_DATA_LEN:
                if (hciCoreCb.extResetSeq) {
                    /* send first extended command */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                } else {
                    /* initialize extended parameters */
                    hciCoreCb.maxAdvDataLen = 0;
                    hciCoreCb.numSupAdvSets = 0;
                    hciCoreCb.perAdvListSize = 0;

                    /* send next command in sequence */
                    HciLeRandCmd();
                }
                break;

            case HCI_OPCODE_LE_READ_MAX_ADV_DATA_LEN:
            case HCI_OPCODE_LE_READ_NUM_SUP_ADV_SETS:
            case HCI_OPCODE_LE_READ_PER_ADV_LIST_SIZE:
                if (hciCoreCb.extResetSeq) {
                    /* send next extended command in sequence */
                    (*hciCoreCb.extResetSeq)(pMsg, opcode);
                }
                break;

            case HCI_OPCODE_LE_RAND:
                /* check if need to send second rand command */
                if (randCnt < (HCI_RESET_RAND_CNT - 1)) {
                    randCnt++;
                    HciLeRandCmd();
                } else {
                    uint8_t addr[6] = { 0 };
                    memcpy(addr, pMsg, sizeof(addr));
                    DM_RAND_ADDR_SET(addr, DM_RAND_ADDR_STATIC);
                    // note: will invoke set rand address
                    cordio::BLE::deviceInstance().getGap().setAddress(
                        BLEProtocol::AddressType::RANDOM_STATIC,
                        addr
                    );
                }
                break;

            case HCI_OPCODE_LE_SET_RAND_ADDR:
                /* send next command in sequence */
                signal_reset_sequence_done();
                break;

            default:
                break;
        }
    }
}

ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
    static ble::vendor::cordio::H4TransportDriver transport_driver (/* cbCFG_PIO_PIN_BT_HCI_TX */ PG_14,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RX */ PC_7,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_CTS */ PG_15,
                                                                    /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12,
                                                                    115200);
    static ble::vendor::odin_w2::HCIDriver hci_driver ( transport_driver,
                                                        /* cbCFG_PIO_PIN_BT_ENABLE  */ PG_7,
                                                        /* cbCFG_PIO_PIN_BT_HCI_RTS */ PG_12);

    return hci_driver;
}
<|endoftext|>


<commit_before>/*
 * SessionFind.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionFind.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <core/Exec.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>

using namespace core;

namespace session {
namespace modules {
namespace find {

namespace {

   class GrepOperation : public boost::enable_shared_from_this<GrepOperation>
   {
   public:
      static boost::shared_ptr<GrepOperation> create(const FilePath& tempFile)
      {
         return boost::shared_ptr<GrepOperation>(new GrepOperation(tempFile));
      }

   private:
      GrepOperation(const FilePath& tempFile)
         : stopped_(false), tempFile_(tempFile)
      {
         handle_ = core::system::generateUuid(false);
      }

   public:
      std::string handle() const
      {
         return handle_;
      }

      core::system::ProcessCallbacks createProcessCallbacks()
      {
         core::system::ProcessCallbacks callbacks;
         callbacks.onContinue = boost::bind(&GrepOperation::onContinue,
                                            shared_from_this(),
                                            _1);
         callbacks.onStdout = boost::bind(&GrepOperation::onStdout,
                                          shared_from_this(),
                                          _1, _2);
         callbacks.onStderr = boost::bind(&GrepOperation::onStderr,
                                          shared_from_this(),
                                          _1, _2);
         callbacks.onExit = boost::bind(&GrepOperation::onExit,
                                        shared_from_this(),
                                        _1);
         return callbacks;
      }

      void stop()
      {
         stopped_ = true;
      }

   private:
      bool onContinue(const core::system::ProcessOperations& ops) const
      {
         return !stopped_;
      }

      void onStdout(const core::system::ProcessOperations& ops, const std::string& data)
      {
         json::Array files;
         json::Array lineNums;
         json::Array contents;

         stdOutBuf_.append(data);
         size_t nextLineStart = 0;
         size_t pos = -1;
         while (std::string::npos != (pos = stdOutBuf_.find('\n', pos + 1)))
         {
            std::string line = stdOutBuf_.substr(nextLineStart, pos - nextLineStart);
            nextLineStart = pos + 1;

            boost::smatch match;
            if (boost::regex_match(line, match, boost::regex("^([^:]+):(\\d+):(.*)")))
            {
               std::string file = match[1];
               int lineNum = safe_convert::stringTo<int>(std::string(match[2]), -1);
               std::string lineContents = match[3];
               boost::algorithm::trim(lineContents);

               files.push_back(file);
               lineNums.push_back(lineNum);
               contents.push_back(lineContents);
            }
         }

         if (nextLineStart)
         {
            stdOutBuf_.erase(0, nextLineStart);
         }

         json::Object result;
         result["handle"] = handle();
         json::Object results;
         results["file"] = files;
         results["line"] = lineNums;
         results["lineValue"] = contents;
         result["results"] = results;

         module_context::enqueClientEvent(
               ClientEvent(client_events::kFindResult, result));
      }

      void onStderr(const core::system::ProcessOperations& ops, const std::string& data)
      {
         LOG_ERROR_MESSAGE("grep: " + data);
      }

      void onExit(int exitCode)
      {
         module_context::enqueClientEvent(
               ClientEvent(client_events::kFindOperationEnded, handle()));
         if (!tempFile_.empty())
            tempFile_.removeIfExists();
      }

      bool stopped_;
      FilePath tempFile_;
      std::string stdOutBuf_;
      std::string handle_;
   };

} // namespace

core::Error beginFind(const json::JsonRpcRequest& request,
                      json::JsonRpcResponse* pResponse)
{
   std::string searchString;
   bool asRegex, ignoreCase;
   std::string directory;
   std::string filePattern;

   Error error = json::readParams(request.params,
                                  &searchString,
                                  &asRegex,
                                  &ignoreCase,
                                  &directory,
                                  &filePattern);
   if (error)
      return error;

   core::system::ProcessOptions options;
   options.workingDir = module_context::resolveAliasedPath(directory);

   // TODO: Encode the pattern using the project encoding

   // Put the grep pattern in a file
   FilePath tempFile = module_context::tempFile("rs_grep", "txt");
   boost::shared_ptr<std::ostream> pStream;
   error = tempFile.open_w(&pStream);
   if (error)
      return error;
   *pStream << searchString << std::endl;
   pStream.reset(); // release file handle

   boost::shared_ptr<GrepOperation> ptrGrepOp = GrepOperation::create(tempFile);
   core::system::ProcessCallbacks callbacks =
                                       ptrGrepOp->createProcessCallbacks();

   shell_utils::ShellCommand cmd("grep");
   cmd << "-rHn" << "--binary-files=without-match" << "--devices=skip";

   if (ignoreCase)
      cmd << "-i";

   // Use -f to pass pattern via file, so we don't have to worry about
   // escaping double quotes, etc.
   cmd << "-f";
   cmd << tempFile;
   if (!asRegex)
      cmd << "-F";

   cmd << "--";
   if (filePattern.empty())
      cmd << shell_utils::EscapeFilesOnly << "*" << shell_utils::EscapeAll;
   else
      cmd << filePattern;

   error = module_context::processSupervisor().runCommand(cmd,
                                                          options,
                                                          callbacks);
   if (error)
      return error;

   pResponse->setResult(ptrGrepOp->handle());

   return Success();
}

core::Error stopFind(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string handle;

   return Success();
}

core::Error initialize()
{
   using namespace session::module_context;

   // install handlers
   using boost::bind;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "begin_find", beginFind))
      (bind(registerRpcMethod, "stop_find", stopFind));
   return initBlock.execute();
}

} // namespace find
} // namespace modules
} // namespace session
<commit_msg>Fix indentation<commit_after>/*
 * SessionFind.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionFind.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <core/Exec.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>

using namespace core;

namespace session {
namespace modules {
namespace find {

namespace {

class GrepOperation : public boost::enable_shared_from_this<GrepOperation>
{
public:
   static boost::shared_ptr<GrepOperation> create(const FilePath& tempFile)
   {
      return boost::shared_ptr<GrepOperation>(new GrepOperation(tempFile));
   }

private:
   GrepOperation(const FilePath& tempFile)
      : stopped_(false), tempFile_(tempFile)
   {
      handle_ = core::system::generateUuid(false);
   }

public:
   std::string handle() const
   {
      return handle_;
   }

   core::system::ProcessCallbacks createProcessCallbacks()
   {
      core::system::ProcessCallbacks callbacks;
      callbacks.onContinue = boost::bind(&GrepOperation::onContinue,
                                         shared_from_this(),
                                         _1);
      callbacks.onStdout = boost::bind(&GrepOperation::onStdout,
                                       shared_from_this(),
                                       _1, _2);
      callbacks.onStderr = boost::bind(&GrepOperation::onStderr,
                                       shared_from_this(),
                                       _1, _2);
      callbacks.onExit = boost::bind(&GrepOperation::onExit,
                                     shared_from_this(),
                                     _1);
      return callbacks;
   }

   void stop()
   {
      stopped_ = true;
   }

private:
   bool onContinue(const core::system::ProcessOperations& ops) const
   {
      return !stopped_;
   }

   void onStdout(const core::system::ProcessOperations& ops, const std::string& data)
   {
      json::Array files;
      json::Array lineNums;
      json::Array contents;

      stdOutBuf_.append(data);
      size_t nextLineStart = 0;
      size_t pos = -1;
      while (std::string::npos != (pos = stdOutBuf_.find('\n', pos + 1)))
      {
         std::string line = stdOutBuf_.substr(nextLineStart, pos - nextLineStart);
         nextLineStart = pos + 1;

         boost::smatch match;
         if (boost::regex_match(line, match, boost::regex("^([^:]+):(\\d+):(.*)")))
         {
            std::string file = match[1];
            int lineNum = safe_convert::stringTo<int>(std::string(match[2]), -1);
            std::string lineContents = match[3];
            boost::algorithm::trim(lineContents);

            files.push_back(file);
            lineNums.push_back(lineNum);
            contents.push_back(lineContents);
         }
      }

      if (nextLineStart)
      {
         stdOutBuf_.erase(0, nextLineStart);
      }

      json::Object result;
      result["handle"] = handle();
      json::Object results;
      results["file"] = files;
      results["line"] = lineNums;
      results["lineValue"] = contents;
      result["results"] = results;

      module_context::enqueClientEvent(
            ClientEvent(client_events::kFindResult, result));
   }

   void onStderr(const core::system::ProcessOperations& ops, const std::string& data)
   {
      LOG_ERROR_MESSAGE("grep: " + data);
   }

   void onExit(int exitCode)
   {
      module_context::enqueClientEvent(
            ClientEvent(client_events::kFindOperationEnded, handle()));
      if (!tempFile_.empty())
         tempFile_.removeIfExists();
   }

   bool stopped_;
   FilePath tempFile_;
   std::string stdOutBuf_;
   std::string handle_;
};

} // namespace

core::Error beginFind(const json::JsonRpcRequest& request,
                      json::JsonRpcResponse* pResponse)
{
   std::string searchString;
   bool asRegex, ignoreCase;
   std::string directory;
   std::string filePattern;

   Error error = json::readParams(request.params,
                                  &searchString,
                                  &asRegex,
                                  &ignoreCase,
                                  &directory,
                                  &filePattern);
   if (error)
      return error;

   core::system::ProcessOptions options;
   options.workingDir = module_context::resolveAliasedPath(directory);

   // TODO: Encode the pattern using the project encoding

   // Put the grep pattern in a file
   FilePath tempFile = module_context::tempFile("rs_grep", "txt");
   boost::shared_ptr<std::ostream> pStream;
   error = tempFile.open_w(&pStream);
   if (error)
      return error;
   *pStream << searchString << std::endl;
   pStream.reset(); // release file handle

   boost::shared_ptr<GrepOperation> ptrGrepOp = GrepOperation::create(tempFile);
   core::system::ProcessCallbacks callbacks =
                                       ptrGrepOp->createProcessCallbacks();

   shell_utils::ShellCommand cmd("grep");
   cmd << "-rHn" << "--binary-files=without-match" << "--devices=skip";

   if (ignoreCase)
      cmd << "-i";

   // Use -f to pass pattern via file, so we don't have to worry about
   // escaping double quotes, etc.
   cmd << "-f";
   cmd << tempFile;
   if (!asRegex)
      cmd << "-F";

   cmd << "--";
   if (filePattern.empty())
      cmd << shell_utils::EscapeFilesOnly << "*" << shell_utils::EscapeAll;
   else
      cmd << filePattern;

   error = module_context::processSupervisor().runCommand(cmd,
                                                          options,
                                                          callbacks);
   if (error)
      return error;

   pResponse->setResult(ptrGrepOp->handle());

   return Success();
}

core::Error stopFind(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string handle;

   return Success();
}

core::Error initialize()
{
   using namespace session::module_context;

   // install handlers
   using boost::bind;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "begin_find", beginFind))
      (bind(registerRpcMethod, "stop_find", stopFind));
   return initBlock.execute();
}

} // namespace find
} // namespace modules
} // namespace session
<|endoftext|>


<commit_before>/*
- Designer will publish:
http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html
- Designer will receive: (with root link as 0,0,0)
http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html
*/
#include <cstdlib>
#include <string>
#include <ros/ros.h>
#include <lcm/lcm-cpp.hpp>

#include "lcmtypes/robotiqhand/command_t.hpp"
#include <trajectory_msgs/JointTrajectory.h>
#include <ipab_msgs/PlannerRequest.h>
#include <ipab_msgs/RobotiqCommand.h>
#include <std_srvs/Trigger.h>

using namespace std;

class LCM2ROS {
public:
  LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_);
  ~LCM2ROS() {}

private:
  boost::shared_ptr<lcm::LCM> lcm_;
  ros::NodeHandle nh_;
  ros::NodeHandle* rosnode;

  ros::ServiceClient rosserviceclient_Emergency_Release_;
  ros::ServiceClient rosserviceclient_Recover_;
  ros::ServiceClient rosserviceclient_Tactile_Open_;
  ros::ServiceClient rosserviceclient_Tactile_Close_;

  void handCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const robotiqhand::command_t* msg);
  ros::Publisher hand_command_pub_;
};

LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_): lcm_(lcm_), nh_(nh_) {
  lcm_->subscribe("ROBOTIQ_LEFT_COMMAND", &LCM2ROS::handCommandHandler, this);
  hand_command_pub_ = nh_.advertise<ipab_msgs::RobotiqCommand>("/gripper/ddapp_command", 10);

  rosserviceclient_Emergency_Release_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/emergency_stop");
  rosserviceclient_Recover_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/recover");
  rosserviceclient_Tactile_Open_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/tactile_open");
  rosserviceclient_Tactile_Close_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/tactile_close");

  rosnode = new ros::NodeHandle();
}

void LCM2ROS::handCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const robotiqhand::command_t* msg) {
  ROS_ERROR("LCM2ROS_SDH got hand command");

  // TODO: implement engaging on receiving this flag as true and have an auto-timeout to disengage

  // Check whether to perform an emergency release
  if (msg->emergency_release == 1) {
    std_srvs::Trigger er_trigger;
    if (rosserviceclient_Emergency_Release_.call(er_trigger)) {
      ROS_ERROR("Emergency release activated"); // TODO: use returned information whether successful
    } else {
      ROS_ERROR("Emergency release NOT activated");
    }
    return;
  }

  ipab_msgs::RobotiqCommand m;
  m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6);

  m.activate = (bool) msg->activate;
  m.emergency_release = (bool) msg->emergency_release;
  m.do_move = (bool) msg->do_move;

  m.mode = msg->mode;
  m.position = msg->position;
  m.force = msg->force;
  m.velocity = msg->velocity;

  m.ifc = (bool) msg->ifc;
  m.positionA = msg->positionA;
  m.positionB = msg->positionB;
  m.positionC = msg->positionC;

  m.isc = (bool) msg->isc;
  m.positionS = msg->positionS;

  hand_command_pub_.publish(m);

  // TODO: Implement direct call of driver services
  if (msg->do_move) {
    // Command position, force, and velocity (TODO: only position implemented right now)

    // TODO: implement different modes
    switch (msg->mode) {
    // -1 - ignore (use previous mode)
    //  0 - basic (normal)
    //  1 - pinch
    //  2 - wide
    //  3 - scissor
    case 0: // Basic Position Mode
      if (msg->position == 0) { // Open
        std_srvs::Trigger tactile_open_trigger;
        if (rosserviceclient_Tactile_Open_.call(tactile_open_trigger)) {
          ROS_INFO("Tactile opening commanded"); // TODO: use returned information whether successful
        } else {
          ROS_ERROR("Tactile opening FAILED");
        }
        return;
      } else if (msg->position == 254) { // Close
        std_srvs::Trigger tactile_close_trigger;
        if (rosserviceclient_Tactile_Close_.call(tactile_close_trigger)) {
          ROS_INFO("Tactile closing commanded"); // TODO: use returned information whether successful
        } else {
          ROS_ERROR("Tactile closing FAILED");
        }
        return;
      }
      break;
    }

    // TODO: individual finger control and individual scissor control not yet implemented
    // Individual finger control
    // 1 - active
    // 0 - inactive
    // int8_t ifc;
    // int16_t positionA;
    // int16_t positionB;
    // int16_t positionC;

    // Indiviual scissor control
    // 1 - active
    // 0 - inactive
    // int8_t isc;
    // int16_t positionS;
  } else if (!msg->do_move && msg->activate) {
    // Reset / calibrate
    std_srvs::Trigger recover_trigger;
    if (rosserviceclient_Recover_.call(recover_trigger)) {
      ROS_INFO("Reset hand from emergency stop");
    } else {
      ROS_ERROR("Could not recover");
    }
    return;
  } else {
    ROS_WARN("Setting modes not supported - only basic mode supported!");
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "lcm2ros_sdh", ros::init_options::NoSigintHandler);
  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if (!lcm->good()) {
    std::cerr << "ERROR: lcm is not good()" << std::endl;
  }
  ros::NodeHandle nh;

  LCM2ROS handlerObject(lcm, nh);
  cout << "\nlcm2ros_sdh translator ready\n";
  ROS_ERROR("LCM2ROS_SDH Translator Ready");

  while (0 == lcm->handle());
  return 0;
}
<commit_msg>lcm2ros_sdh activate and deactivate hand<commit_after>/*
- Designer will publish:
http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html
- Designer will receive: (with root link as 0,0,0)
http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html
*/
#include <cstdlib>
#include <string>
#include <ros/ros.h>
#include <lcm/lcm-cpp.hpp>

#include "lcmtypes/robotiqhand/command_t.hpp"
#include <trajectory_msgs/JointTrajectory.h>
#include <ipab_msgs/PlannerRequest.h>
#include <ipab_msgs/RobotiqCommand.h>
#include <std_srvs/Trigger.h>

using namespace std;

class LCM2ROS {
public:
  LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_);
  ~LCM2ROS() {}

private:
  boost::shared_ptr<lcm::LCM> lcm_;
  ros::NodeHandle nh_;
  ros::NodeHandle* rosnode;

  ros::ServiceClient rosserviceclient_Emergency_Release_;
  ros::ServiceClient rosserviceclient_Recover_;
  ros::ServiceClient rosserviceclient_Tactile_Open_;
  ros::ServiceClient rosserviceclient_Tactile_Close_;

  ros::ServiceClient rosserviceclient_Engage_;
  ros::ServiceClient rosserviceclient_Disengage_;

  void handCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const robotiqhand::command_t* msg);
  ros::Publisher hand_command_pub_;
};

LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_): lcm_(lcm_), nh_(nh_) {
  lcm_->subscribe("ROBOTIQ_LEFT_COMMAND", &LCM2ROS::handCommandHandler, this);
  hand_command_pub_ = nh_.advertise<ipab_msgs::RobotiqCommand>("/gripper/ddapp_command", 10);

  rosserviceclient_Emergency_Release_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/emergency_stop");
  rosserviceclient_Recover_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/recover");
  rosserviceclient_Tactile_Open_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/tactile_open");
  rosserviceclient_Tactile_Close_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/tactile_close");

  rosserviceclient_Engage_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/engage");
  rosserviceclient_Disengage_ = nh_.serviceClient<std_srvs::Trigger>("/gripper/sdh_controller/disengage");

  rosnode = new ros::NodeHandle();
}

void LCM2ROS::handCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const robotiqhand::command_t* msg) {
  ROS_ERROR("LCM2ROS_SDH got hand command");

  // TODO: implement engaging on receiving this flag as true and have an auto-timeout to disengage

  // Check whether to perform an emergency release
  if (msg->emergency_release == 1) {
    std_srvs::Trigger er_trigger;
    if (rosserviceclient_Emergency_Release_.call(er_trigger)) {
      ROS_ERROR("Emergency release activated"); // TODO: use returned information whether successful
    } else {
      ROS_ERROR("Emergency release NOT activated");
    }
    return;
  }

  // Check whether to disengage hand (activate = 0)
  if (msg->activate == 0) {
    std_srvs::Trigger disengage_trigger;
    if (rosserviceclient_Disengage_.call(disengage_trigger))
      ROS_DEBUG("Disengaged hand");
    else
      ROS_ERROR("Error disengaging hand");
    return;
  } else if (msg->activate == 0 && msg->do_move == 0) {
    std_srvs::Trigger engage_trigger;
    if (rosserviceclient_Engage_.call(engage_trigger))
      ROS_DEBUG("Engaged hand");
    else
      ROS_ERROR("Error engaging hand");
  }

  ipab_msgs::RobotiqCommand m;
  m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6);

  m.activate = (bool) msg->activate;
  m.emergency_release = (bool) msg->emergency_release;
  m.do_move = (bool) msg->do_move;

  m.mode = msg->mode;
  m.position = msg->position;
  m.force = msg->force;
  m.velocity = msg->velocity;

  m.ifc = (bool) msg->ifc;
  m.positionA = msg->positionA;
  m.positionB = msg->positionB;
  m.positionC = msg->positionC;

  m.isc = (bool) msg->isc;
  m.positionS = msg->positionS;

  hand_command_pub_.publish(m);

  // TODO: Implement direct call of driver services
  if (msg->do_move) {
    // Command position, force, and velocity (TODO: only position implemented right now)

    // TODO: implement different modes
    switch (msg->mode) {
    // -1 - ignore (use previous mode)
    //  0 - basic (normal)
    //  1 - pinch
    //  2 - wide
    //  3 - scissor
    case 0: // Basic Position Mode
      if (msg->position == 0) { // Open
        std_srvs::Trigger tactile_open_trigger;
        if (rosserviceclient_Tactile_Open_.call(tactile_open_trigger)) {
          ROS_INFO("Tactile opening commanded"); // TODO: use returned information whether successful
        } else {
          ROS_ERROR("Tactile opening FAILED");
        }
        return;
      } else if (msg->position == 254) { // Close
        std_srvs::Trigger tactile_close_trigger;
        if (rosserviceclient_Tactile_Close_.call(tactile_close_trigger)) {
          ROS_INFO("Tactile closing commanded"); // TODO: use returned information whether successful
        } else {
          ROS_ERROR("Tactile closing FAILED");
        }
        return;
      }
      break;
    }

    // TODO: individual finger control and individual scissor control not yet implemented
    // Individual finger control
    // 1 - active
    // 0 - inactive
    // int8_t ifc;
    // int16_t positionA;
    // int16_t positionB;
    // int16_t positionC;

    // Indiviual scissor control
    // 1 - active
    // 0 - inactive
    // int8_t isc;
    // int16_t positionS;
  } /*else if (!msg->do_move && msg->activate) {
    // Reset / calibrate
    std_srvs::Trigger recover_trigger;
    if (rosserviceclient_Recover_.call(recover_trigger)) {
      ROS_INFO("Reset hand from emergency stop");
    } else {
      ROS_ERROR("Could not recover");
    }
    return;
  } else {
    ROS_WARN("Setting modes not supported - only basic mode supported!");
  }*/
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "lcm2ros_sdh", ros::init_options::NoSigintHandler);
  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if (!lcm->good()) {
    std::cerr << "ERROR: lcm is not good()" << std::endl;
  }
  ros::NodeHandle nh;

  LCM2ROS handlerObject(lcm, nh);
  cout << "\nlcm2ros_sdh translator ready\n";
  ROS_ERROR("LCM2ROS_SDH Translator Ready");

  while (0 == lcm->handle());
  return 0;
}
<|endoftext|>