<commit_before>/*************************************************************************
 *
 *  $RCSfile: SharedConnection.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: oj $ $Date: 2002-08-12 09:21:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBA_CORE_SHARED_CONNECTION_HXX
#define DBA_CORE_SHARED_CONNECTION_HXX

#ifndef _CONNECTIVITY_CONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMMANDPREPARATION_HPP_
#include <com/sun/star/sdb/XCommandPreparation.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaccess
{
    //=======================================================================================
    //= OSharedConnection: This class implements a simple forwarding of connection calls.
    //= All methods will be forwarded with exception of the set methods, which are not allowed
    //= to be called on shared connections. Instances of this class will be created when the
    //= datasource is asked for not isolated connection.
    //=======================================================================================
    typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
                                            > OSharedConnection_BASE;
    typedef ::connectivity::OConnectionWrapper  OSharedConnection_BASE2;

    class OSharedConnection :   public ::comphelper::OBaseMutex
                              , public OSharedConnection_BASE
                              , public OSharedConnection_BASE2
    {
    protected:
        virtual void SAL_CALL disposing(void)
        {
            OSharedConnection_BASE::disposing();
        }
    public:
        OSharedConnection(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _rxProxyConnection)
            : OSharedConnection_BASE(m_aMutex)
        {
            setDelegation(_rxProxyConnection,m_refCount);
        }

        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL acquire() throw() { OSharedConnection_BASE::acquire(); }
        virtual void SAL_CALL release() throw() { OSharedConnection_BASE::release(); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw (::com::sun::star::uno::RuntimeException)
        {
            return ::comphelper::concatSequences(
                OSharedConnection_BASE::getTypes(),
                OSharedConnection_BASE2::getTypes()
            );
        }

        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException)
        {
            ::com::sun::star::uno::Any aReturn = OSharedConnection_BASE::queryInterface(_rType);
            if ( !aReturn.hasValue() )
                aReturn = OSharedConnection_BASE2::queryInterface(_rType);
            return aReturn;
        }
        // --------------------------------------------------------------------------------
        // XCloseable
        virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            {
                ::osl::MutexGuard aGuard( m_aMutex );
                ::connectivity::checkDisposed(rBHelper.bDisposed);

            }
            dispose();
        }

        // XConnection
        virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        // XConnection
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    };

    IMPLEMENT_GET_IMPLEMENTATION_ID( OSharedConnection );
//........................................................................
}   // namespace dbaccess
//........................................................................
#endif // DBA_CORE_SHARED_CONNECTION_HXX

<commit_msg>INTEGRATION: CWS ooo20031110 (1.2.148); FILE MERGED 2003/11/07 10:50:34 waratah 1.2.148.1: #i21906# bracket an undefined macro so that non permissive build will compile<commit_after>/*************************************************************************
 *
 *  $RCSfile: SharedConnection.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 18:01:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBA_CORE_SHARED_CONNECTION_HXX
#define DBA_CORE_SHARED_CONNECTION_HXX

#ifndef _CONNECTIVITY_CONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif
#ifndef _CPPUHELPER_COMPONENT_HXX_
#include <cppuhelper/component.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMMANDPREPARATION_HPP_
#include <com/sun/star/sdb/XCommandPreparation.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaccess
{
    //=======================================================================================
    //= OSharedConnection: This class implements a simple forwarding of connection calls.
    //= All methods will be forwarded with exception of the set methods, which are not allowed
    //= to be called on shared connections. Instances of this class will be created when the
    //= datasource is asked for not isolated connection.
    //=======================================================================================
    typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection
                                            > OSharedConnection_BASE;
    typedef ::connectivity::OConnectionWrapper  OSharedConnection_BASE2;

    class OSharedConnection :   public ::comphelper::OBaseMutex
                              , public OSharedConnection_BASE
                              , public OSharedConnection_BASE2
    {
    protected:
        virtual void SAL_CALL disposing(void)
        {
            OSharedConnection_BASE::disposing();
        }
    public:
        OSharedConnection(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _rxProxyConnection)
            : OSharedConnection_BASE(m_aMutex)
        {
            setDelegation(_rxProxyConnection,m_refCount);
        }

        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL acquire() throw() { OSharedConnection_BASE::acquire(); }
        virtual void SAL_CALL release() throw() { OSharedConnection_BASE::release(); }
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw (::com::sun::star::uno::RuntimeException)
        {
            return ::comphelper::concatSequences(
                OSharedConnection_BASE::getTypes(),
                OSharedConnection_BASE2::getTypes()
            );
        }

        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException)
        {
            ::com::sun::star::uno::Any aReturn = OSharedConnection_BASE::queryInterface(_rType);
            if ( !aReturn.hasValue() )
                aReturn = OSharedConnection_BASE2::queryInterface(_rType);
            return aReturn;
        }
        // --------------------------------------------------------------------------------
        // XCloseable
        virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            {
                ::osl::MutexGuard aGuard( m_aMutex );
                ::connectivity::checkDisposed(rBHelper.bDisposed);

            }
            dispose();
        }

        // XConnection
        virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
        {
            throw ::com::sun::star::sdbc::SQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("This call is not allowed when sharing connections.")),*this,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("S10000")),0,::com::sun::star::uno::Any());
        }
        // XConnection
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    };

#ifdef IMPLEMENT_GET_IMPLEMENTATION_ID
    IMPLEMENT_GET_IMPLEMENTATION_ID( OSharedConnection );
#endif
//........................................................................
}   // namespace dbaccess
//........................................................................
#endif // DBA_CORE_SHARED_CONNECTION_HXX

<|endoftext|>


<commit_before>#ifndef _app_hpp_INCLUDED
#define _app_hpp_INCLUDED

namespace CaDiCaL {

class Solver;
class File;

// A wrapper app which makes up the CaDiCaL stand alone solver.  It in
// essence only consists of the 'App::main' function.  So this class
// contains code, which is not required if only the library interface in
// 'Solver' is used.  It further uses static data structures in order to
// have a signal handler catch signals. It should not be used in a
// multithreaded application.  If you want to use multiple instances of the
// solver use the 'Solver' interface directly.

class App {

  // Global solver.

  static Solver * solver;

  // Printing.

  static void usage ();
  static void witness ();
  static void banner ();

  // Option handling.

  static bool set (const char*);

public:

  static int main (int arg, char ** argv);
};

};

#endif
<commit_msg>issue<commit_after>#ifndef _app_hpp_INCLUDED
#define _app_hpp_INCLUDED

namespace CaDiCaL {

class Solver;
class File;

// A wrapper app which makes up the CaDiCaL stand alone solver.  It in
// essence only consists of the 'App::main' function.  So this class
// contains code, which is not required if only the library interface in
// 'Solver' is used.  It further uses static data structures in order to
// have a signal handler catch signals. It is thus not reentrant and should
// not be used in a multithreaded application.  If you want to use multiple
// instances of the solver use the 'Solver' interface directly.

class App {

  // Global solver.

  static Solver * solver;

  // Printing.

  static void usage ();
  static void witness ();
  static void banner ();

  // Option handling.

  static bool set (const char*);

public:

  static int main (int arg, char ** argv);
};

};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basicmigration.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:40:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

//.........................................................................
namespace migration
{
//.........................................................................

    static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
    static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );

    // =============================================================================
    // component operations
    // =============================================================================

    ::rtl::OUString BasicMigration_getImplementationName()
    {
        static ::rtl::OUString* pImplName = 0;
        if ( !pImplName )
        {
            ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
            if ( !pImplName )
            {
                static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
                pImplName = &aImplName;
            }
        }
        return *pImplName;
    }

    // -----------------------------------------------------------------------------

    Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
    {
        static Sequence< ::rtl::OUString >* pNames = 0;
        if ( !pNames )
        {
            ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
            if ( !pNames )
            {
                static Sequence< ::rtl::OUString > aNames(1);
                aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
                pNames = &aNames;
            }
        }
        return *pNames;
    }

    // =============================================================================
    // BasicMigration
    // =============================================================================

    BasicMigration::BasicMigration()
    {
    }

    // -----------------------------------------------------------------------------

    BasicMigration::~BasicMigration()
    {
    }

    // -----------------------------------------------------------------------------

    TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
    {
        TStringVectorPtr aResult( new TStringVector );
        ::osl::Directory aDir( rBaseURL);

        if ( aDir.open() == ::osl::FileBase::E_None )
        {
            // iterate over directory content
            TStringVector aSubDirs;
            ::osl::DirectoryItem aItem;
            while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
            {
                ::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL );
                if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
                {
                    if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
                        aSubDirs.push_back( aFileStatus.getFileURL() );
                    else
                        aResult->push_back( aFileStatus.getFileURL() );
                }
            }

            // iterate recursive over subfolders
            TStringVector::const_iterator aI = aSubDirs.begin();
            while ( aI != aSubDirs.end() )
            {
                TStringVectorPtr aSubResult = getFiles( *aI );
                aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
                ++aI;
            }
        }

        return aResult;
    }

    // -----------------------------------------------------------------------------

    ::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
    {
        ::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
        if ( aResult == ::osl::FileBase::E_NOENT )
        {
            INetURLObject aBaseURL( rDirURL );
            aBaseURL.removeSegment();
            checkAndCreateDirectory( aBaseURL );
            return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
        }
        else
        {
            return aResult;
        }
    }

    // -----------------------------------------------------------------------------

    void BasicMigration::copyFiles()
    {
        ::rtl::OUString sTargetDir;
        ::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
        if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
        {
            sTargetDir += sTargetUserBasic;
            TStringVectorPtr aFileList = getFiles( m_sSourceDir );
            TStringVector::const_iterator aI = aFileList->begin();
            while ( aI != aFileList->end() )
            {
                ::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
                ::rtl::OUString sTargetName = sTargetDir + sLocalName;
                INetURLObject aURL( sTargetName );
                aURL.removeSegment();
                checkAndCreateDirectory( aURL );
                ::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
                if ( aResult != ::osl::FileBase::E_None )
                {
                    ::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
                    aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
                         +  ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
                    OSL_ENSURE( sal_False, aMsg.getStr() );
                }
                ++aI;
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
        }
    }

    // -----------------------------------------------------------------------------
    // XServiceInfo
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
    {
        return BasicMigration_getImplementationName();
    }

    // -----------------------------------------------------------------------------

    sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
    {
        Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
        const ::rtl::OUString* pNames = aNames.getConstArray();
        const ::rtl::OUString* pEnd = pNames + aNames.getLength();
        for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
            ;

        return pNames != pEnd;
    }

    // -----------------------------------------------------------------------------

    Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
    {
        return BasicMigration_getSupportedServiceNames();
    }

    // -----------------------------------------------------------------------------
    // XInitialization
    // -----------------------------------------------------------------------------

    void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        const Any* pIter = aArguments.getConstArray();
        const Any* pEnd = pIter + aArguments.getLength();
        for ( ; pIter != pEnd ; ++pIter )
        {
            beans::NamedValue aValue;
            *pIter >>= aValue;
            if ( aValue.Name.equalsAscii( "UserData" ) )
            {
                sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
                OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
                m_sSourceDir += sSourceUserBasic;
                break;
            }
        }
    }

    // -----------------------------------------------------------------------------
    // XJob
    // -----------------------------------------------------------------------------

    Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
        throw (lang::IllegalArgumentException, Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        copyFiles();

        return Any();
    }

    // =============================================================================
    // component operations
    // =============================================================================

    Reference< XInterface > SAL_CALL BasicMigration_create(
        Reference< XComponentContext > const & xContext )
        SAL_THROW( () )
    {
        return static_cast< lang::XTypeProvider * >( new BasicMigration() );
    }

    // -----------------------------------------------------------------------------

//.........................................................................
}   // namespace migration
//.........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.222); FILE MERGED 2006/09/01 17:25:16 kaib 1.4.222.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basicmigration.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:46:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#ifndef _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

//.........................................................................
namespace migration
{
//.........................................................................

    static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
    static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );

    // =============================================================================
    // component operations
    // =============================================================================

    ::rtl::OUString BasicMigration_getImplementationName()
    {
        static ::rtl::OUString* pImplName = 0;
        if ( !pImplName )
        {
            ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
            if ( !pImplName )
            {
                static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
                pImplName = &aImplName;
            }
        }
        return *pImplName;
    }

    // -----------------------------------------------------------------------------

    Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
    {
        static Sequence< ::rtl::OUString >* pNames = 0;
        if ( !pNames )
        {
            ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
            if ( !pNames )
            {
                static Sequence< ::rtl::OUString > aNames(1);
                aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
                pNames = &aNames;
            }
        }
        return *pNames;
    }

    // =============================================================================
    // BasicMigration
    // =============================================================================

    BasicMigration::BasicMigration()
    {
    }

    // -----------------------------------------------------------------------------

    BasicMigration::~BasicMigration()
    {
    }

    // -----------------------------------------------------------------------------

    TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
    {
        TStringVectorPtr aResult( new TStringVector );
        ::osl::Directory aDir( rBaseURL);

        if ( aDir.open() == ::osl::FileBase::E_None )
        {
            // iterate over directory content
            TStringVector aSubDirs;
            ::osl::DirectoryItem aItem;
            while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
            {
                ::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL );
                if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
                {
                    if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
                        aSubDirs.push_back( aFileStatus.getFileURL() );
                    else
                        aResult->push_back( aFileStatus.getFileURL() );
                }
            }

            // iterate recursive over subfolders
            TStringVector::const_iterator aI = aSubDirs.begin();
            while ( aI != aSubDirs.end() )
            {
                TStringVectorPtr aSubResult = getFiles( *aI );
                aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
                ++aI;
            }
        }

        return aResult;
    }

    // -----------------------------------------------------------------------------

    ::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
    {
        ::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
        if ( aResult == ::osl::FileBase::E_NOENT )
        {
            INetURLObject aBaseURL( rDirURL );
            aBaseURL.removeSegment();
            checkAndCreateDirectory( aBaseURL );
            return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
        }
        else
        {
            return aResult;
        }
    }

    // -----------------------------------------------------------------------------

    void BasicMigration::copyFiles()
    {
        ::rtl::OUString sTargetDir;
        ::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
        if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
        {
            sTargetDir += sTargetUserBasic;
            TStringVectorPtr aFileList = getFiles( m_sSourceDir );
            TStringVector::const_iterator aI = aFileList->begin();
            while ( aI != aFileList->end() )
            {
                ::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
                ::rtl::OUString sTargetName = sTargetDir + sLocalName;
                INetURLObject aURL( sTargetName );
                aURL.removeSegment();
                checkAndCreateDirectory( aURL );
                ::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
                if ( aResult != ::osl::FileBase::E_None )
                {
                    ::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
                    aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
                         +  ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
                    OSL_ENSURE( sal_False, aMsg.getStr() );
                }
                ++aI;
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
        }
    }

    // -----------------------------------------------------------------------------
    // XServiceInfo
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
    {
        return BasicMigration_getImplementationName();
    }

    // -----------------------------------------------------------------------------

    sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
    {
        Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
        const ::rtl::OUString* pNames = aNames.getConstArray();
        const ::rtl::OUString* pEnd = pNames + aNames.getLength();
        for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
            ;

        return pNames != pEnd;
    }

    // -----------------------------------------------------------------------------

    Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
    {
        return BasicMigration_getSupportedServiceNames();
    }

    // -----------------------------------------------------------------------------
    // XInitialization
    // -----------------------------------------------------------------------------

    void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        const Any* pIter = aArguments.getConstArray();
        const Any* pEnd = pIter + aArguments.getLength();
        for ( ; pIter != pEnd ; ++pIter )
        {
            beans::NamedValue aValue;
            *pIter >>= aValue;
            if ( aValue.Name.equalsAscii( "UserData" ) )
            {
                sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
                OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
                m_sSourceDir += sSourceUserBasic;
                break;
            }
        }
    }

    // -----------------------------------------------------------------------------
    // XJob
    // -----------------------------------------------------------------------------

    Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
        throw (lang::IllegalArgumentException, Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        copyFiles();

        return Any();
    }

    // =============================================================================
    // component operations
    // =============================================================================

    Reference< XInterface > SAL_CALL BasicMigration_create(
        Reference< XComponentContext > const & xContext )
        SAL_THROW( () )
    {
        return static_cast< lang::XTypeProvider * >( new BasicMigration() );
    }

    // -----------------------------------------------------------------------------

//.........................................................................
}   // namespace migration
//.........................................................................
<|endoftext|>


<commit_before>/*
    SWARM

    Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

uint64_t arch_get_memused()
{
#ifdef _WIN32

  PROCESS_MEMORY_COUNTERS pmc;
  GetProcessMemoryInfo(GetCurrentProcess(),
                       &pmc,
                       sizeof(PROCESS_MEMORY_COUNTERS));
  return pmc.PeakWorkingSetSize;

#else

  struct rusage r_usage;
  getrusage(RUSAGE_SELF, & r_usage);

# ifdef __APPLE__
  /* Mac: ru_maxrss gives the size in bytes */
  return static_cast<uint64_t>(r_usage.ru_maxrss);
# else
  /* Linux: ru_maxrss gives the size in kilobytes  */
  return static_cast<uint64_t>(r_usage.ru_maxrss * 1024);
# endif

#endif
}

uint64_t arch_get_memtotal()
{
#ifdef _WIN32

  MEMORYSTATUSEX ms;
  ms.dwLength = sizeof(MEMORYSTATUSEX);
  GlobalMemoryStatusEx(&ms);
  return ms.ullTotalPhys;

#elif defined(__APPLE__)

  int mib [] = { CTL_HW, HW_MEMSIZE };
  int64_t ram = 0;
  size_t length = sizeof(ram);
  if(sysctl(mib, 2, &ram, &length, nullptr, 0) == -1)
    fatal("Cannot determine amount of RAM");
  return static_cast<uint64_t>(ram);

#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)

  int64_t phys_pages = sysconf(_SC_PHYS_PAGES);
  int64_t pagesize = sysconf(_SC_PAGESIZE);
  if ((phys_pages == -1) || (pagesize == -1))
    fatal("Cannot determine amount of RAM");
  return static_cast<uint64_t>(pagesize * phys_pages);

#else

  struct sysinfo si;
  if (sysinfo(&si))
    fatal("Cannot determine amount of RAM");
  return si.totalram * si.mem_unit;

#endif
}

void arch_srandom(unsigned int seed)
{
  /* initialize pseudo-random number generator */
  if (seed == 0)
    {
#ifdef _WIN32
      srand(GetTickCount());
#else
      int fd = open("/dev/urandom", O_RDONLY);
      if (fd < 0)
        fatal("Unable to open /dev/urandom");
      if (read(fd, & seed, sizeof(seed)) < 0)
        fatal("Unable to read from /dev/urandom");
      close(fd);
      srandom(seed);
#endif
    }
  else
    {
#ifdef _WIN32
      srand(seed);
#else
      srandom(seed);
#endif
    }
}

uint64_t arch_random()
{
#ifdef _WIN32
  return static_cast<uint64_t>(rand());
#else
  return static_cast<uint64_t>(random());
#endif
}
<commit_msg>Remove unused code for random seed init<commit_after>/*
    SWARM

    Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
    Department of Informatics, University of Oslo,
    PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/

#include "swarm.h"

uint64_t arch_get_memused()
{
#ifdef _WIN32

  PROCESS_MEMORY_COUNTERS pmc;
  GetProcessMemoryInfo(GetCurrentProcess(),
                       &pmc,
                       sizeof(PROCESS_MEMORY_COUNTERS));
  return pmc.PeakWorkingSetSize;

#else

  struct rusage r_usage;
  getrusage(RUSAGE_SELF, & r_usage);

# ifdef __APPLE__
  /* Mac: ru_maxrss gives the size in bytes */
  return static_cast<uint64_t>(r_usage.ru_maxrss);
# else
  /* Linux: ru_maxrss gives the size in kilobytes  */
  return static_cast<uint64_t>(r_usage.ru_maxrss * 1024);
# endif

#endif
}

uint64_t arch_get_memtotal()
{
#ifdef _WIN32

  MEMORYSTATUSEX ms;
  ms.dwLength = sizeof(MEMORYSTATUSEX);
  GlobalMemoryStatusEx(&ms);
  return ms.ullTotalPhys;

#elif defined(__APPLE__)

  int mib [] = { CTL_HW, HW_MEMSIZE };
  int64_t ram = 0;
  size_t length = sizeof(ram);
  if(sysctl(mib, 2, &ram, &length, nullptr, 0) == -1)
    fatal("Cannot determine amount of RAM");
  return static_cast<uint64_t>(ram);

#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)

  int64_t phys_pages = sysconf(_SC_PHYS_PAGES);
  int64_t pagesize = sysconf(_SC_PAGESIZE);
  if ((phys_pages == -1) || (pagesize == -1))
    fatal("Cannot determine amount of RAM");
  return static_cast<uint64_t>(pagesize * phys_pages);

#else

  struct sysinfo si;
  if (sysinfo(&si))
    fatal("Cannot determine amount of RAM");
  return si.totalram * si.mem_unit;

#endif
}

void arch_srandom(unsigned int seed)
{
  /* initialize pseudo-random number generator */

#ifdef _WIN32
  srand(seed);
#else
  srandom(seed);
#endif
}

uint64_t arch_random()
{
#ifdef _WIN32
  return static_cast<uint64_t>(rand());
#else
  return static_cast<uint64_t>(random());
#endif
}
<|endoftext|>


<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.

Author(s) / Copyright (s): Damon Hart-Davis 2016
*/

/*
 * Driver for PseudoSensorOccupancyTracker tests.
 */

#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
#include "OTV0P2BASE_SensorAmbientLightOccupancy.h"

// Basic operation (duration of occupancy from trigger), etc.
TEST(PseudoSensorOccupancyTracker,basics)
{
    // Set up default occupancy tracker.
    OTV0P2BASE::PseudoSensorOccupancyTracker o1;
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    o1.markAsOccupied();
    ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());
    // Run for half the nominal time and ensure still marked as occupied.
    for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2; ++i) { o1.read(); ASSERT_TRUE(o1.isLikelyOccupied()); }
    // Run again for about half the nominal time and ensure now not occupied.
    for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2 + 1; ++i) { o1.read(); }
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsOccupied() brings status back to occupied.
    o1.markAsOccupied();
    ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsPossiblyOccupied() brings status back to occupied.
    o1.markAsPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsJustPossiblyOccupied() DOES NOT move status to occupied.
    o1.markAsJustPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());

    // Show that markAsJustPossiblyOccupied() does indicate occupancy when system not very torpid.
    o1.reset();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    o1.markAsJustPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());
}
<commit_msg>TODO-1070: WIP<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.

Author(s) / Copyright (s): Damon Hart-Davis 2016
*/

/*
 * Driver for PseudoSensorOccupancyTracker tests.
 */

#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
#include "OTV0P2BASE_SensorAmbientLightOccupancy.h"

// Basic operation (duration of occupancy from trigger), etc.
TEST(PseudoSensorOccupancyTracker,basics)
{
    // Set up default occupancy tracker.
    OTV0P2BASE::PseudoSensorOccupancyTracker o1;
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    o1.markAsOccupied();
    ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());
    // Run for half the nominal time and ensure still marked as occupied.
    for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2; ++i) { o1.read(); ASSERT_TRUE(o1.isLikelyOccupied()); }
    // Run again for about half the nominal time and ensure now not occupied.
    for(int i = 0; i < o1.OCCUPATION_TIMEOUT_M/2 + 1; ++i) { o1.read(); }
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsOccupied() brings status back to occupied.
    o1.markAsOccupied();
    ASSERT_TRUE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsPossiblyOccupied() brings status back to occupied.
    o1.markAsPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());

    // Put in holiday mode; show marked very vacant.
    o1.setHolidayMode();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    // Show that markAsJustPossiblyOccupied() DOES NOT move status to occupied.
    o1.markAsJustPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());

    // Show that markAsJustPossiblyOccupied() does indicate some occupancy when system not very torpid.
    o1.reset();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_FALSE(o1.isLikelyOccupied());
    ASSERT_TRUE(o1.isLikelyUnoccupied());
    o1.markAsJustPossiblyOccupied();
    ASSERT_FALSE(o1.isLikelyRecentlyOccupied());
    ASSERT_TRUE(o1.isLikelyOccupied());
    ASSERT_FALSE(o1.isLikelyUnoccupied());
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <servo_controller/servo_control.h>
#include <servo_controller/servo_status.h>
#include <servo_controller/servo_array_status.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h>   // time calls
#include <ros/console.h>

using namespace std;
using namespace ros::console::levels;

class ServoControllerCls
{
public:
	ServoControllerCls();
	void SetServoPosition(int channel_no, int target_position);
	void InitializeSerialPort();
	void InitializePubSub();
	void InitializeServoProperties();
	servo_controller::servo_array_status servo_array_status;
private:
	void servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command);

	ros::NodeHandle nh_;

	ros::Publisher servo_array_status_pub_;
	ros::Subscriber servo_0_control_sub_;
	ros::Subscriber servo_1_control_sub_;
	ros::Subscriber servo_2_control_sub_;
	ros::Subscriber servo_3_control_sub_;
	ros::Subscriber servo_4_control_sub_;
	ros::Subscriber servo_5_control_sub_;

	int serial_port;
};

void ServoControllerCls::InitializeSerialPort() {
	serial_port = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
	if (serial_port < 0)
	{
		ROS_WARN("Cannot open servo controller serial port on /dev/ttyACM0. Make sure you have correct permissions. Port no: %d", serial_port);
	}
	else
	{
		ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Opened servo controller serial port on /dev/ttyACM0. Port no: %d", serial_port);
		//printf("Opened ACM0: %d\r\n", (int) (serial_port));
	}
}

void ServoControllerCls::InitializePubSub() {

	//nh_.param("axis_linear", linear_, linear_);
	//nh_.param("axis_angular", angular_, angular_);
	//nh_.param("scale_angular", a_scale_, a_scale_);
	//nh_.param("scale_linear", l_scale_, l_scale_);

	// Publish status for all servos
	// Set latch to true, so the last message published on
    // this topic will be saved and sent to new subscribers when they
    // connect
	servo_array_status_pub_ = nh_.advertise < servo_controller::servo_array_status
			> ("servo_controller/servo_array_status", 1, true);

	// Separate messages for independent control of each servo
	servo_0_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_0_control", 10, &ServoControllerCls::servoControlCallback, this);
	servo_1_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_1_control", 10, &ServoControllerCls::servoControlCallback, this);
	servo_2_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_2_control", 10, &ServoControllerCls::servoControlCallback, this);
	servo_3_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_3_control", 10, &ServoControllerCls::servoControlCallback, this);
	servo_4_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_4_control", 10, &ServoControllerCls::servoControlCallback, this);
	servo_5_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_5_control", 10, &ServoControllerCls::servoControlCallback, this);

	// Publish initial, make sure values are initialized
	servo_array_status_pub_.publish(servo_array_status);
}

void ServoControllerCls::InitializeServoProperties() {
	const uint center = 6000;
	const uint max_value = 8000;
	const uint min_value = 4000;
	const uint velocity_limit = 100;
	const uint acceleration_limit = 20;

	servo_array_status.servo[3].enabled = false;
	servo_array_status.servo[4].enabled = false;
	servo_array_status.servo[5].enabled = false;
	servo_array_status.servo[3].enabled = false;
	servo_array_status.servo[4].enabled = false;
	servo_array_status.servo[5].enabled = false;

	servo_array_status.servo[0].servo_no = 0;
	servo_array_status.servo[1].servo_no = 1;
	servo_array_status.servo[2].servo_no = 2;
	servo_array_status.servo[3].servo_no = 3;
	servo_array_status.servo[4].servo_no = 4;
	servo_array_status.servo[5].servo_no = 5;

	servo_array_status.servo[0].name = "";
	servo_array_status.servo[1].name = "Right Wheel Encoder";
	servo_array_status.servo[2].name = "Left Wheel Encoder";
	servo_array_status.servo[3].name = "Right Steering Servo";
	servo_array_status.servo[4].name = "Left Steering Servo";
	servo_array_status.servo[5].name = "Main Motor";

	servo_array_status.servo[0].mode = 0; // Not defined
	servo_array_status.servo[1].mode = 2; // Digital input - wheel encoder
	servo_array_status.servo[2].mode = 2; // Digital input - wheel encoder
	servo_array_status.servo[3].mode = 1; // Servo control signal output - servo
	servo_array_status.servo[4].mode = 1; // Servo control signal output - servo
	servo_array_status.servo[5].mode = 1; // Servo control signal output - motor

	servo_array_status.servo[3].target = center;
	servo_array_status.servo[4].target = center;
	servo_array_status.servo[5].target = center;

	servo_array_status.servo[3].actual = center;
	servo_array_status.servo[4].actual = center;
	servo_array_status.servo[5].actual = center;

	servo_array_status.servo[3].center = center;
	servo_array_status.servo[4].center = center;
	servo_array_status.servo[5].center = center;

	servo_array_status.servo[3].max = max_value;
	servo_array_status.servo[4].max = max_value;
	servo_array_status.servo[5].max = max_value;

	servo_array_status.servo[3].min = min_value;
	servo_array_status.servo[4].min = min_value;
	servo_array_status.servo[5].min = min_value;

	servo_array_status.servo[3].velocity_limit = velocity_limit;
	servo_array_status.servo[4].velocity_limit = velocity_limit;
	servo_array_status.servo[5].velocity_limit = velocity_limit;

	servo_array_status.servo[3].acceleration_limit = acceleration_limit;
	servo_array_status.servo[4].acceleration_limit = acceleration_limit;
	servo_array_status.servo[5].acceleration_limit = acceleration_limit;

	servo_array_status.servo[3].enabled = true;
	servo_array_status.servo[4].enabled = true;
	servo_array_status.servo[5].enabled = true;
}

ServoControllerCls::ServoControllerCls()
{
	InitializeSerialPort();
	InitializeServoProperties();
	InitializePubSub();
}

void ServoControllerCls::SetServoPosition(int channel_no, int target_position) {
	char command_bytes[4] = { 0x84, channel_no, (char) ((target_position & 0x7F)),
			(char) ((target_position >> 7 & 0x7F)) };
	int n = write(serial_port, command_bytes, 4);
	if (n < 0)
	{
		ROS_WARN("Could not write bytes to servo controller serial port for servo no: %d, target: %d", channel_no, target_position);
	}
	else
	{
		ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Set servo no: %d, target: %d", channel_no, target_position);
	}
}

void ServoControllerCls::servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command)
{
	int servo_no = control_command->servo_no;
	if (servo_no < 0 || servo_no >= 6)
	{
		ROS_WARN("Wrong servo number passed: %d", servo_no);
		return;
	}
	if (!servo_array_status.servo[servo_no].enabled)
	{
		ROS_WARN("Trying to control a not enabled servo: %d", servo_no);
		return;
	}
	if (servo_array_status.servo[servo_no].mode != 1)
	{
		ROS_WARN("Trying to control servo: %d, in mode: %d. Mode has to be 1 for servos", servo_no, servo_array_status.servo[servo_no].mode);
		return;
	}

	uint target = control_command->target;
	const uint max_value = servo_array_status.servo[servo_no].max;
	const uint min_value = servo_array_status.servo[servo_no].min;
	if (target > max_value)
	{
		ROS_WARN("Trying to set servo: %d to target: %d more than maximum value: %d. Setting to maximum value", servo_no, target, max_value);
		target = max_value;
	}

	if (target < min_value)
	{
		ROS_WARN("Trying to set servo: %d to target: %d less than minimum value: %d. Setting to maximum value", servo_no, target, min_value);
		target = min_value;
	}
	SetServoPosition(servo_no, target);

	// Publish update
	servo_array_status.servo[servo_no].target = target;
	servo_array_status_pub_.publish(servo_array_status);
}

int main(int argc, char** argv)
{
	ros::init(argc, argv, "ServoController");
	ServoControllerCls servo_controller;
	ros::spin();
}
<commit_msg>Enable Head servo<commit_after>#include <ros/ros.h>
#include <servo_controller/servo_control.h>
#include <servo_controller/servo_status.h>
#include <servo_controller/servo_array_status.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h>   // time calls
#include <ros/console.h>

using namespace std;
using namespace ros::console::levels;

class ServoControllerCls
{
public:
	ServoControllerCls();
	void SetServoPosition(int channel_no, int target_position);
	void InitializeSerialPort();
	void InitializePubSub();
	void InitializeServoProperties();
	servo_controller::servo_array_status servo_array_status;
private:
	void servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command);

	ros::NodeHandle nh_;

	ros::Publisher servo_array_status_pub_;
	ros::Subscriber servo_0_control_sub_;
	ros::Subscriber servo_1_control_sub_;
	ros::Subscriber servo_2_control_sub_;
	ros::Subscriber servo_3_control_sub_;
	ros::Subscriber servo_4_control_sub_;
	ros::Subscriber servo_5_control_sub_;

	int serial_port;
};

void ServoControllerCls::InitializeSerialPort() {
	serial_port = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
	if (serial_port < 0)
	{
		ROS_WARN("Cannot open servo controller serial port on /dev/ttyACM0. Make sure you have correct permissions. Port no: %d", serial_port);
	}
	else
	{
		ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Opened servo controller serial port on /dev/ttyACM0. Port no: %d", serial_port);
		//printf("Opened ACM0: %d\r\n", (int) (serial_port));
	}
}

void ServoControllerCls::InitializePubSub() {

	//nh_.param("axis_linear", linear_, linear_);
	//nh_.param("axis_angular", angular_, angular_);
	//nh_.param("scale_angular", a_scale_, a_scale_);
	//nh_.param("scale_linear", l_scale_, l_scale_);

	// Publish status for all servos
	// Set latch to true, so the last message published on
    // this topic will be saved and sent to new subscribers when they
    // connect
	servo_array_status_pub_ = nh_.advertise < servo_controller::servo_array_status
			> ("servo_controller/servo_array_status", 1, true);

	// Separate messages for independent control of each servo
	servo_0_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_0_control", 4, &ServoControllerCls::servoControlCallback, this);
	servo_1_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_1_control", 4, &ServoControllerCls::servoControlCallback, this);
	servo_2_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_2_control", 4, &ServoControllerCls::servoControlCallback, this);
	servo_3_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_3_control", 4, &ServoControllerCls::servoControlCallback, this);
	servo_4_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_4_control", 4, &ServoControllerCls::servoControlCallback, this);
	servo_5_control_sub_ =
			nh_.subscribe < servo_controller::servo_control
					> ("servo_controller/servo_5_control", 4, &ServoControllerCls::servoControlCallback, this);

	// Publish initial, make sure values are initialized
	servo_array_status_pub_.publish(servo_array_status);
}

void ServoControllerCls::InitializeServoProperties() {
	const uint center = 6000;
	const uint max_value = 8000;
	const uint min_value = 4000;
	const uint velocity_limit = 100;
	const uint acceleration_limit = 20;

	servo_array_status.servo[0].enabled = false;
	servo_array_status.servo[1].enabled = false;
	servo_array_status.servo[2].enabled = false;
	servo_array_status.servo[3].enabled = false;
	servo_array_status.servo[4].enabled = false;
	servo_array_status.servo[5].enabled = false;

	servo_array_status.servo[0].servo_no = 0;
	servo_array_status.servo[1].servo_no = 1;
	servo_array_status.servo[2].servo_no = 2;
	servo_array_status.servo[3].servo_no = 3;
	servo_array_status.servo[4].servo_no = 4;
	servo_array_status.servo[5].servo_no = 5;

	servo_array_status.servo[0].name = "";
	servo_array_status.servo[1].name = "--Right Wheel Encoder";
	servo_array_status.servo[2].name = "Head Servo";
	servo_array_status.servo[3].name = "Right Steering Servo";
	servo_array_status.servo[4].name = "Left Steering Servo";
	servo_array_status.servo[5].name = "Main Motor";

	servo_array_status.servo[0].mode = 0; // Not defined
	servo_array_status.servo[1].mode = 2; // Digital input - wheel encoder
	servo_array_status.servo[2].mode = 1; // Servo control signal output - servo
	servo_array_status.servo[3].mode = 1; // Servo control signal output - servo
	servo_array_status.servo[4].mode = 1; // Servo control signal output - servo
	servo_array_status.servo[5].mode = 1; // Servo control signal output - motor

	servo_array_status.servo[2].target = center;
	servo_array_status.servo[3].target = center;
	servo_array_status.servo[4].target = center;
	servo_array_status.servo[5].target = center;

	servo_array_status.servo[2].actual = center;
	servo_array_status.servo[3].actual = center;
	servo_array_status.servo[4].actual = center;
	servo_array_status.servo[5].actual = center;

	servo_array_status.servo[2].center = center;
	servo_array_status.servo[3].center = center;
	servo_array_status.servo[4].center = center;
	servo_array_status.servo[5].center = center;

	servo_array_status.servo[2].max = max_value;
	servo_array_status.servo[3].max = max_value;
	servo_array_status.servo[4].max = max_value;
	servo_array_status.servo[5].max = max_value;

	servo_array_status.servo[2].min = min_value;
	servo_array_status.servo[3].min = min_value;
	servo_array_status.servo[4].min = min_value;
	servo_array_status.servo[5].min = min_value;

	servo_array_status.servo[2].velocity_limit = velocity_limit;
	servo_array_status.servo[3].velocity_limit = velocity_limit;
	servo_array_status.servo[4].velocity_limit = velocity_limit;
	servo_array_status.servo[5].velocity_limit = velocity_limit;

	servo_array_status.servo[2].acceleration_limit = acceleration_limit;
	servo_array_status.servo[3].acceleration_limit = acceleration_limit;
	servo_array_status.servo[4].acceleration_limit = acceleration_limit;
	servo_array_status.servo[5].acceleration_limit = acceleration_limit;

	servo_array_status.servo[0].enabled = false;
	servo_array_status.servo[1].enabled = false;
	servo_array_status.servo[2].enabled = true;
	servo_array_status.servo[3].enabled = true;
	servo_array_status.servo[4].enabled = true;
	servo_array_status.servo[5].enabled = true;
}

ServoControllerCls::ServoControllerCls()
{
	InitializeSerialPort();
	InitializeServoProperties();
	InitializePubSub();
}

void ServoControllerCls::SetServoPosition(int channel_no, int target_position) {
	char command_bytes[4] = { 0x84, channel_no, (char) ((target_position & 0x7F)),
			(char) ((target_position >> 7 & 0x7F)) };
	int n = write(serial_port, command_bytes, 4);
	if (n < 0)
	{
		ROS_WARN("Could not write bytes to servo controller serial port for servo no: %d, target: %d", channel_no, target_position);
	}
	else
	{
		ROS_LOG(Info, ROSCONSOLE_DEFAULT_NAME, "Set servo no: %d, target: %d", channel_no, target_position);
	}
}

void ServoControllerCls::servoControlCallback(const servo_controller::servo_control::ConstPtr& control_command)
{
	int servo_no = control_command->servo_no;
	if (servo_no < 0 || servo_no >= 6)
	{
		ROS_WARN("Wrong servo number passed: %d", servo_no);
		return;
	}
	if (!servo_array_status.servo[servo_no].enabled)
	{
		ROS_WARN("Trying to control a not enabled servo: %d", servo_no);
		return;
	}
	if (servo_array_status.servo[servo_no].mode != 1)
	{
		ROS_WARN("Trying to control servo: %d, in mode: %d. Mode has to be 1 for servos", servo_no, servo_array_status.servo[servo_no].mode);
		return;
	}

	uint target = control_command->target;
	const uint max_value = servo_array_status.servo[servo_no].max;
	const uint min_value = servo_array_status.servo[servo_no].min;
	if (target > max_value)
	{
		ROS_WARN("Trying to set servo: %d to target: %d more than maximum value: %d. Setting to maximum value", servo_no, target, max_value);
		target = max_value;
	}

	if (target < min_value)
	{
		ROS_WARN("Trying to set servo: %d to target: %d less than minimum value: %d. Setting to maximum value", servo_no, target, min_value);
		target = min_value;
	}
	SetServoPosition(servo_no, target);

	// Publish update
	servo_array_status.servo[servo_no].target = target;
	servo_array_status_pub_.publish(servo_array_status);
}

int main(int argc, char** argv)
{
	ros::init(argc, argv, "ServoController");
	ServoControllerCls servo_controller;
	ros::spin();
}
<|endoftext|>


<commit_before>/**
 * \file SD1OverdriveFilter.cpp
 */

#include "SD1OverdriveFilter.h"

#include <boost/math/special_functions/sign.hpp>

#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"

namespace ATK
{
  template<typename DataType_>
  class SD1OverdriveFunction
  {
  public:
    typedef DataType_ DataType;
  protected:
    DataType A;
    DataType B;
    DataType R1;
    DataType Q;
    DataType drive;
    DataType is;
    DataType vt;

    DataType oldy0;
    DataType oldexpy0;
    DataType oldinvexpy0;
    DataType oldy1;
    DataType oldexpy1;
    DataType oldinvexpy1;

    Exp<DataType> exp;

  public:
    SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
    :R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
    {
      A = dt / (2 * C) + R;
      B = dt / (2 * C) - R;
      oldy0 = oldy1 = 0;
      oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
    }

    void set_drive(DataType drive)
    {
      this->drive = (R1 + drive * Q);
    }

    std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
    {
      y0 -= x0;
      y1 -= x1;
      DataType expdiode_y1_p = exp(y1 / vt);
      DataType expdiode_y1_m = 1 / expdiode_y1_p;

      DataType expdiode_y0_p;
      DataType expdiode_y0_m;

	    if(y0 == oldy0)
	    {
	      expdiode_y0_p = oldexpy0;
	      expdiode_y0_m = oldinvexpy0;
	    }
	    else if(y0 == oldy1)
	    {
	      expdiode_y0_p = oldexpy1;
	      expdiode_y0_m = oldinvexpy1;
	    }
	    else
	    {
	      expdiode_y0_p = exp(y0 / vt);
	      expdiode_y0_m = 1 / expdiode_y0_p;
	    }

      oldy0 = y0;
      oldexpy0 = expdiode_y0_p;
      oldinvexpy0 = expdiode_y0_m;

      oldy1 = y1;
      oldexpy1 = expdiode_y1_p;
      oldinvexpy1 = expdiode_y1_m;

      std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
      DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
      return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
    }
  };

  template <typename DataType>
  SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
  :TypedBaseFilter<DataType>(nb_channels, nb_channels)
  {
    optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
  }

  template <typename DataType>
  SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
  {
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::setup()
  {
    Parent::setup();
    function.reset(new SD1OverdriveFunction<DataType>(static_cast<DataType>(1./input_sampling_rate), 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
    function->set_drive(drive);
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
  {
    this->drive = drive;
    function->set_drive(drive);
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
  {
    assert(nb_input_ports == nb_output_ports);

    for(int channel = 0; channel < nb_input_ports; ++channel)
    {
      for(std::int64_t i = 0; i < size; ++i)
      {
        outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
      }
    }
  }

  template class SD1OverdriveFilter<float>;
  template class SD1OverdriveFilter<double>;
}
<commit_msg>Init drive value (because you have to!)<commit_after>/**
 * \file SD1OverdriveFilter.cpp
 */

#include "SD1OverdriveFilter.h"

#include <boost/math/special_functions/sign.hpp>

#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"

namespace ATK
{
  template<typename DataType_>
  class SD1OverdriveFunction
  {
  public:
    typedef DataType_ DataType;
  protected:
    DataType A;
    DataType B;
    DataType R1;
    DataType Q;
    DataType drive;
    DataType is;
    DataType vt;

    DataType oldy0;
    DataType oldexpy0;
    DataType oldinvexpy0;
    DataType oldy1;
    DataType oldexpy1;
    DataType oldinvexpy1;

    Exp<DataType> exp;

  public:
    SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
    :R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
    {
      A = dt / (2 * C) + R;
      B = dt / (2 * C) - R;
      oldy0 = oldy1 = 0;
      oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
    }

    void set_drive(DataType drive)
    {
      this->drive = (R1 + drive * Q);
    }

    std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
    {
      y0 -= x0;
      y1 -= x1;
      DataType expdiode_y1_p = exp(y1 / vt);
      DataType expdiode_y1_m = 1 / expdiode_y1_p;

      DataType expdiode_y0_p;
      DataType expdiode_y0_m;

	    if(y0 == oldy0)
	    {
	      expdiode_y0_p = oldexpy0;
	      expdiode_y0_m = oldinvexpy0;
	    }
	    else if(y0 == oldy1)
	    {
	      expdiode_y0_p = oldexpy1;
	      expdiode_y0_m = oldinvexpy1;
	    }
	    else
	    {
	      expdiode_y0_p = exp(y0 / vt);
	      expdiode_y0_m = 1 / expdiode_y0_p;
	    }

      oldy0 = y0;
      oldexpy0 = expdiode_y0_p;
      oldinvexpy0 = expdiode_y0_m;

      oldy1 = y1;
      oldexpy1 = expdiode_y1_p;
      oldinvexpy1 = expdiode_y1_m;

      std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
      DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
      return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
    }
  };

  template <typename DataType>
  SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
    :TypedBaseFilter<DataType>(nb_channels, nb_channels), drive(0)
  {
    optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
  }

  template <typename DataType>
  SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
  {
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::setup()
  {
    Parent::setup();
    function.reset(new SD1OverdriveFunction<DataType>(static_cast<DataType>(1./input_sampling_rate), 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
    function->set_drive(drive);
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
  {
    this->drive = drive;
    function->set_drive(drive);
  }

  template <typename DataType>
  void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
  {
    assert(nb_input_ports == nb_output_ports);

    for(int channel = 0; channel < nb_input_ports; ++channel)
    {
      for(std::int64_t i = 0; i < size; ++i)
      {
        outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
      }
    }
  }

  template class SD1OverdriveFilter<float>;
  template class SD1OverdriveFilter<double>;
}
<|endoftext|>