repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
stvnrhodes/CNCAirbrush | mbed/StepperMotors/LinearMotion.h | <filename>mbed/StepperMotors/LinearMotion.h
/* mbed Stepper Library
* Copyright (c) 2012 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef LINEARMOTION_H
#define LINEARMOTION_H
#include "mbed.h"
#include "Stepper.h"
#include "Bitmap.h"
typedef struct {
long x;
long y;
long z;
} Vector;
typedef struct {
Vector one;
Vector two;
} TwoVectors;
class LinearMotion {
public:
/** Interpolate to point specified by the vector (relative to current position)
*
* @param Stepper * s1 The x stepper motor
* @param Stepper * s2 The y stepper motor
* @param Stepper * s3 The z stepper motor
* @param DigitalOut * solenoid The solenoid
* @param bool * pause The variable for pausing
* @param bool * stop The variable for stopping
*/
void setStepMotors(Stepper * s1, Stepper * s2, Stepper * s3, DigitalOut * solenoid, bool * pause, bool * stop);
/** Interpolate to point specified by the vector (relative to current position)
*
* @param Vector length The vector specifying where to go
* @param int maxSpeed Max speed used to get to position
* @param bool solenoidOn Whether to have the solenoid on
*/
void interpolate(Vector length, int maxSpeed, bool solenoidOn);
void interpolate(Vector length, int maxSpeed);
/** Interpolate to square specified by the vector (relative to current position)
*
* @param Vector basePos Position defining the base of the square
* @param Vector heightPos Position defining the height of the square
* @param int maxSpeed Max speed used to get to position
* @param bool solenoidOn Whether to have the solenoid on
*/
void interpolateSquare(Vector basePos, Vector heightPos, int maxSpeed, bool solenoidOn);
/** Set various settings for how we do linear motion
*
* @param long steps_per_pixel The number of steps to go per pixel
* @param long initial_delay The initial speed for linear acceleration
* @param long step_buffer steps_per_pixel/step_buffer is the size of the gap on either side of a pixel
*/
void updateSettings(long steps_per_pixel, long initial_delay, long step_buffer);
private:
void doLinearSideways(Vector delta, Vector nextRow, Stepper ** stepMotor, int maxSpeed, bool solenoidOn);
void doLinear(Vector delta, Stepper** stepMotor, int maxSpeed, bool solenoidOn);
void enableSteppers(bool en);
int delayTime (int oldDelay, int stepNumber);
Stepper * StepMotor[3];
DigitalOut * _sol;
Bitmap _bmp;
bool reversing;
volatile bool * _paused;
volatile bool * _stopped;
bool _z, _z_slantways;
long _steps_per_pixel;
long _z_steps_per_pixel;
long _step_buffer; // Make a gap of _steps_per_pixel/_step_buffer between each pixel
long _initial_delay; // in us
};
#endif |
vitorgt/OpenMP-tests | hello.c | <filename>hello.c
#include<stdio.h>
#include<omp.h>
int main(){
#pragma omp parallel
{
printf("Hello, World from thread #%0X.\n", omp_get_thread_num());
}
return 0;
}
|
vitorgt/OpenMP-tests | sum.c | #include<stdio.h>
#include<omp.h>
int main(int argc, char *argv[]){
int nThreads = 4;
omp_set_num_threads(nThreads);
int n = 0;
scanf("%d", &n);
double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;
double sum1P[nThreads];
double sum2P[nThreads];
for(int i = 0; i < nThreads+1; i++)
sum1P[i] = sum2P[i] = 0;
/*
* PARALLEL
* if(expression)
* num_threads(int|expression)
* private(list)
* firstprivate(list)
* shared(list)
* default(shared|none)
* copyin(list)
* reduction(operator: list) //basic operators only
*/
#pragma omp parallel
{
int at = omp_get_thread_num();
int end = (at+1)*(n/nThreads);
for(int i = at*(n/nThreads); i < end; i++)
sum1P[at] += i;
}
if(n%4 == 0)
sum1 += n*((n%4)+1)-(n%4);
else if(n%4 == 1)
sum1 += n*((n%4)+1)-(n%4);
else if(n%4 == 2)
sum1 += n*((n%4)+1)-(n%4-1)-2;
else
sum1 += n*((n%4)+1)-2*(n%4);
for(int i = 0; i < nThreads; i++){
sum1 += sum1P[i];
}
#pragma omp parallel for
for(int i = 0; i <= n; i++){
sum2P[omp_get_thread_num()] += i;
}
for(int i = 0; i < nThreads; i++){
sum2 += sum2P[i];
}
#pragma omp parallel for reduction(+: sum3)
for(int i = 0; i <= n; i++){
//printf("Hello from thread #%d iteration #%d\n", omp_get_thread_num(), i);
sum3 += i;
}
#pragma omp parallel sections
{
#pragma omp section
{
double sumP = 0;
#pragma omp parallel for
for(int i = 0; i <= n; i += 2){
sumP += i;
}
#pragma omp atomic
sum4 += sumP;
}
#pragma omp section
{
double sumP = 0;
#pragma omp parallel for
for(int i = 1; i <= n; i += 2){
sumP += i;
}
#pragma omp atomic
sum4 += sumP;
}
}
printf("Sum1 from 0 to %d = %.0lf\n", n, sum1);
printf("Sum2 from 0 to %d = %.0lf\n", n, sum2);
printf("Sum3 from 0 to %d = %.0lf\n", n, sum3);
printf("Sum4 from 0 to %d = %.0lf\n", n, sum4);
return 0;
}
|
vitorgt/OpenMP-tests | pi.c | #include<stdio.h>
#include<omp.h>
int main(int argc, char *argv[]){
int nThreads = 4;
omp_set_num_threads(nThreads);
unsigned long long n = 100000000;
//scanf("%ld", &n);
double sum = 0, step = 1.0/((double)n);
/*
* FOR
* schedule(type, [chunk])
* shared(list)
* private(list)
* firstprivate(list)
* lastprivate(list)
* reduction(operator: list)
* nowait
* ordered
*/
#pragma omp parallel for reduction(+: sum)
for(unsigned long long i = 0; i < n; i++){
sum += 4.0/(1.0 + ((i + 0.5) * step)*((i + 0.5) * step));
}
printf("Pi = %.20lf\n", step*sum);
return 0;
}
|
vitorgt/OpenMP-tests | nest.c | <gh_stars>0
#include<stdio.h>
#include<omp.h>
// DOESN'T WORK!!
int main(int argc, char *argv[]){
int nThreads = 4;
omp_set_num_threads(nThreads);
omp_set_nested(1);
int n = 0;
scanf("%d", &n);
#pragma omp parallel
{
#pragma omp for
for(int i = 0; i < n; i++){
#pragma omp for
for(int j = 0; j < n; j++){
printf("Hello from thread #%d iteration i#%d j#%d\n", omp_get_thread_num(), i, j);
}
}
}
return 0;
}
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Identity/DSBlockchainIdentity+Protected.h | //
// Created by <NAME>
// Copyright © 2020 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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.
//
#import "DSBlockchainIdentity.h"
NS_ASSUME_NONNULL_BEGIN
@class DSBlockchainIdentityEntity;
@interface DSBlockchainIdentity ()
@property (nonatomic, readonly) DSBlockchainIdentityEntity *blockchainIdentityEntity;
@property (nullable, nonatomic, strong) DSTransientDashpayUser *transientDashpayUser;
@property (nonatomic, weak) DSBlockchainInvitation *associatedInvitation;
@property (nonatomic, readonly) DSECDSAKey *registrationFundingPrivateKey;
@property (nonatomic, assign) BOOL isLocal;
@property (nonatomic, strong) DSCreditFundingTransaction *registrationCreditFundingTransaction;
- (DSBlockchainIdentityEntity *)blockchainIdentityEntityInContext:(NSManagedObjectContext *)context;
- (instancetype)initWithBlockchainIdentityEntity:(DSBlockchainIdentityEntity *)blockchainIdentityEntity;
//This one is called for a local identity that is being recreated from the network
- (instancetype)initAtIndex:(uint32_t)index withUniqueId:(UInt256)uniqueId inWallet:(DSWallet *)wallet withBlockchainIdentityEntity:(DSBlockchainIdentityEntity *)blockchainIdentityEntity;
//This one is called from an identity that was created locally by creating a credit funding transaction
- (instancetype)initAtIndex:(uint32_t)index withLockedOutpoint:(DSUTXO)lockedOutpoint inWallet:(DSWallet *)wallet withBlockchainIdentityEntity:(DSBlockchainIdentityEntity *)blockchainIdentityEntity;
- (instancetype)initAtIndex:(uint32_t)index withLockedOutpoint:(DSUTXO)lockedOutpoint inWallet:(DSWallet *)wallet withBlockchainIdentityEntity:(DSBlockchainIdentityEntity *)blockchainIdentityEntity associatedToInvitation:(DSBlockchainInvitation *)invitation;
- (instancetype)initWithUniqueId:(UInt256)uniqueId isTransient:(BOOL)isTransient onChain:(DSChain *)chain;
- (instancetype)initAtIndex:(uint32_t)index inWallet:(DSWallet *)wallet;
- (instancetype)initAtIndex:(uint32_t)index withLockedOutpoint:(DSUTXO)lockedOutpoint inWallet:(DSWallet *)wallet;
- (instancetype)initAtIndex:(uint32_t)index withUniqueId:(UInt256)uniqueId inWallet:(DSWallet *)wallet;
- (instancetype)initAtIndex:(uint32_t)index withIdentityDictionary:(NSDictionary *)identityDictionary inWallet:(DSWallet *)wallet;
- (instancetype)initAtIndex:(uint32_t)index withFundingTransaction:(DSCreditFundingTransaction *)transaction withUsernameDictionary:(NSDictionary<NSString *, NSDictionary *> *_Nullable)usernameDictionary inWallet:(DSWallet *)wallet;
- (instancetype)initAtIndex:(uint32_t)index withFundingTransaction:(DSCreditFundingTransaction *)transaction withUsernameDictionary:(NSDictionary<NSString *, NSDictionary *> *_Nullable)usernameDictionary havingCredits:(uint64_t)credits registrationStatus:(DSBlockchainIdentityRegistrationStatus)registrationStatus inWallet:(DSWallet *)wallet;
- (void)addUsername:(NSString *)username inDomain:(NSString *)domain status:(DSBlockchainIdentityUsernameStatus)status save:(BOOL)save registerOnNetwork:(BOOL)registerOnNetwork;
- (void)addKey:(DSKey *)key atIndex:(uint32_t)index ofType:(DSKeyType)type withStatus:(DSBlockchainIdentityKeyStatus)status save:(BOOL)save;
- (void)addKey:(DSKey *)key atIndexPath:(NSIndexPath *)indexPath ofType:(DSKeyType)type withStatus:(DSBlockchainIdentityKeyStatus)status save:(BOOL)save;
- (BOOL)registerKeyWithStatus:(DSBlockchainIdentityKeyStatus)status atIndexPath:(NSIndexPath *)indexPath ofType:(DSKeyType)type;
- (DSKey *_Nullable)privateKeyAtIndex:(uint32_t)index ofType:(DSKeyType)type;
- (void)deletePersistentObjectAndSave:(BOOL)save inContext:(NSManagedObjectContext *)context;
- (void)saveInitial;
- (void)saveInitialInContext:(NSManagedObjectContext *)context;
- (void)registerInWalletForBlockchainIdentityUniqueId:(UInt256)blockchainIdentityUniqueId;
- (void)registrationTransitionWithCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationTransition *_Nullable blockchainIdentityRegistrationTransition, NSError *_Nullable error))completion;
- (void)createFundingPrivateKeyWithSeed:(NSData *)seed isForInvitation:(BOOL)isForInvitation completion:(void (^_Nullable)(BOOL success))completion;
- (void)applyProfileChanges:(DSTransientDashpayUser *)transientDashpayUser inContext:(NSManagedObjectContext *)context saveContext:(BOOL)saveContext completion:(void (^_Nullable)(BOOL success, NSError *_Nullable error))completion onCompletionQueue:(dispatch_queue_t)completionQueue;
- (void)setInvitationUniqueId:(UInt256)uniqueId;
- (void)setInvitationRegistrationCreditFundingTransaction:(DSCreditFundingTransaction *)creditFundingTransaction;
//-(void)topupTransitionForForFundingTransaction:(DSTransaction*)fundingTransaction completion:(void (^ _Nullable)(DSBlockchainIdentityTopupTransition * blockchainIdentityTopupTransition))completion;
//
//-(void)updateTransitionUsingNewIndex:(uint32_t)index completion:(void (^ _Nullable)(DSBlockchainIdentityUpdateTransition * blockchainIdentityUpdateTransition))completion;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Identity/DSBlockchainIdentity.h | <gh_stars>10-100
//
// DSBlockchainIdentity.h
// DashSync
//
// Created by <NAME> on 7/26/18.
//
#import "BigIntTypes.h"
#import "DSDAPIClient.h"
#import "DSDerivationPath.h"
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class DSWallet, DSBlockchainIdentityRegistrationTransition, DSBlockchainIdentityTopupTransition, DSBlockchainIdentityUpdateTransition, DSBlockchainIdentityCloseTransition, DSAccount, DSChain, DSTransition, DSDashpayUserEntity, DSPotentialOneWayFriendship, DSTransaction, DSFriendRequestEntity, DSPotentialContact, DSCreditFundingTransaction, DSDocumentTransition, DSKey, DPDocumentFactory, DSTransientDashpayUser, DSBlockchainInvitation, DSAuthenticationKeysDerivationPath;
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityRegistrationStep)
{
DSBlockchainIdentityRegistrationStep_None = 0,
DSBlockchainIdentityRegistrationStep_FundingTransactionCreation = 1,
DSBlockchainIdentityRegistrationStep_FundingTransactionAccepted = 2,
DSBlockchainIdentityRegistrationStep_LocalInWalletPersistence = 4,
DSBlockchainIdentityRegistrationStep_ProofAvailable = 8,
DSBlockchainIdentityRegistrationStep_L1Steps = DSBlockchainIdentityRegistrationStep_FundingTransactionCreation | DSBlockchainIdentityRegistrationStep_FundingTransactionAccepted | DSBlockchainIdentityRegistrationStep_LocalInWalletPersistence | DSBlockchainIdentityRegistrationStep_ProofAvailable,
DSBlockchainIdentityRegistrationStep_Identity = 16,
DSBlockchainIdentityRegistrationStep_RegistrationSteps = DSBlockchainIdentityRegistrationStep_L1Steps | DSBlockchainIdentityRegistrationStep_Identity,
DSBlockchainIdentityRegistrationStep_Username = 32,
DSBlockchainIdentityRegistrationStep_RegistrationStepsWithUsername = DSBlockchainIdentityRegistrationStep_RegistrationSteps | DSBlockchainIdentityRegistrationStep_Username,
DSBlockchainIdentityRegistrationStep_Profile = 64,
DSBlockchainIdentityRegistrationStep_RegistrationStepsWithUsernameAndDashpayProfile = DSBlockchainIdentityRegistrationStep_RegistrationStepsWithUsername | DSBlockchainIdentityRegistrationStep_Profile,
DSBlockchainIdentityRegistrationStep_All = DSBlockchainIdentityRegistrationStep_RegistrationStepsWithUsernameAndDashpayProfile,
DSBlockchainIdentityRegistrationStep_Cancelled = 1 << 30
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityMonitorOptions)
{
DSBlockchainIdentityMonitorOptions_None = 0,
DSBlockchainIdentityMonitorOptions_AcceptNotFoundAsNotAnError = 1,
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityQueryStep)
{
DSBlockchainIdentityQueryStep_None = DSBlockchainIdentityRegistrationStep_None, //0
DSBlockchainIdentityQueryStep_Identity = DSBlockchainIdentityRegistrationStep_Identity,
DSBlockchainIdentityQueryStep_Username = DSBlockchainIdentityRegistrationStep_Username,
DSBlockchainIdentityQueryStep_Profile = DSBlockchainIdentityRegistrationStep_Profile,
DSBlockchainIdentityQueryStep_IncomingContactRequests = 64,
DSBlockchainIdentityQueryStep_OutgoingContactRequests = 128,
DSBlockchainIdentityQueryStep_ContactRequests = DSBlockchainIdentityQueryStep_IncomingContactRequests | DSBlockchainIdentityQueryStep_OutgoingContactRequests,
DSBlockchainIdentityQueryStep_AllForForeignBlockchainIdentity = DSBlockchainIdentityQueryStep_Identity | DSBlockchainIdentityQueryStep_Username | DSBlockchainIdentityQueryStep_Profile,
DSBlockchainIdentityQueryStep_AllForLocalBlockchainIdentity = DSBlockchainIdentityQueryStep_Identity | DSBlockchainIdentityQueryStep_Username | DSBlockchainIdentityQueryStep_Profile | DSBlockchainIdentityQueryStep_ContactRequests,
DSBlockchainIdentityQueryStep_NoIdentity = 1 << 28,
DSBlockchainIdentityQueryStep_BadQuery = 1 << 29,
DSBlockchainIdentityQueryStep_Cancelled = 1 << 30
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityRegistrationStatus)
{
DSBlockchainIdentityRegistrationStatus_Unknown = 0,
DSBlockchainIdentityRegistrationStatus_Registered = 1,
DSBlockchainIdentityRegistrationStatus_Registering = 2,
DSBlockchainIdentityRegistrationStatus_NotRegistered = 3, //sent to DAPI, not yet confirmed
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityUsernameStatus)
{
DSBlockchainIdentityUsernameStatus_NotPresent = 0,
DSBlockchainIdentityUsernameStatus_Initial = 1,
DSBlockchainIdentityUsernameStatus_PreorderRegistrationPending = 2,
DSBlockchainIdentityUsernameStatus_Preordered = 3,
DSBlockchainIdentityUsernameStatus_RegistrationPending = 4, //sent to DAPI, not yet confirmed
DSBlockchainIdentityUsernameStatus_Confirmed = 5,
DSBlockchainIdentityUsernameStatus_TakenOnNetwork = 6,
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityFriendshipStatus)
{
DSBlockchainIdentityFriendshipStatus_Unknown = NSUIntegerMax,
DSBlockchainIdentityFriendshipStatus_None = 0,
DSBlockchainIdentityFriendshipStatus_Outgoing = 1,
DSBlockchainIdentityFriendshipStatus_Incoming = 2,
DSBlockchainIdentityFriendshipStatus_Friends = DSBlockchainIdentityFriendshipStatus_Outgoing | DSBlockchainIdentityFriendshipStatus_Incoming,
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityRetryDelayType)
{
DSBlockchainIdentityRetryDelayType_Linear = 0,
DSBlockchainIdentityRetryDelayType_SlowingDown20Percent = 1,
DSBlockchainIdentityRetryDelayType_SlowingDown50Percent = 2,
};
typedef NS_ENUM(NSUInteger, DSBlockchainIdentityKeyStatus)
{
DSBlockchainIdentityKeyStatus_Unknown = 0,
DSBlockchainIdentityKeyStatus_Registered = 1,
DSBlockchainIdentityKeyStatus_Registering = 2,
DSBlockchainIdentityKeyStatus_NotRegistered = 3,
DSBlockchainIdentityKeyStatus_Revoked = 4,
};
#define BLOCKCHAIN_USERNAME_STATUS @"BLOCKCHAIN_USERNAME_STATUS"
#define BLOCKCHAIN_USERNAME_PROPER @"BLOCKCHAIN_USERNAME_PROPER"
#define BLOCKCHAIN_USERNAME_DOMAIN @"BLOCKCHAIN_USERNAME_DOMAIN"
#define BLOCKCHAIN_USERNAME_SALT @"BLOCKCHAIN_USERNAME_SALT"
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityDidUpdateNotification;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityDidUpdateUsernameStatusNotification;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityKey;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUsernameKey;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUsernameDomainKey;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEvents;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventKeyUpdate;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventRegistration;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventCreditBalance;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventType;
FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventDashpaySyncronizationBlockHash;
@interface DSBlockchainIdentity : NSObject
/*! @brief This is the unique identifier representing the blockchain identity. It is derived from the credit funding transaction credit burn UTXO (as of dpp v10). Returned as a 256 bit number */
@property (nonatomic, readonly) UInt256 uniqueID;
/*! @brief This is the unique identifier representing the blockchain identity. It is derived from the credit funding transaction credit burn UTXO (as of dpp v10). Returned as a base 58 string of a 256 bit number */
@property (nonatomic, readonly) NSString *uniqueIdString;
/*! @brief This is the unique identifier representing the blockchain identity. It is derived from the credit funding transaction credit burn UTXO (as of dpp v10). Returned as a NSData of a 256 bit number */
@property (nonatomic, readonly) NSData *uniqueIDData;
/*! @brief This is the outpoint of the registration credit funding transaction. It is used to determine the unique ID by double SHA256 its value. Returned as a UTXO { .hash , .n } */
@property (nonatomic, readonly) DSUTXO lockedOutpoint;
/*! @brief This is the outpoint of the registration credit funding transaction. It is used to determine the unique ID by double SHA256 its value. Returned as an NSData of a UTXO { .hash , .n } */
@property (nonatomic, readonly) NSData *lockedOutpointData;
/*! @brief This is if the blockchain identity is present in wallets or not. If this is false then the blockchain identity is known for example from being a dashpay friend. */
@property (nonatomic, readonly) BOOL isLocal;
/*! @brief This is if the blockchain identity is made for being an invitation. All invitations should be marked as non local as well. */
@property (nonatomic, readonly) BOOL isOutgoingInvitation;
/*! @brief This is if the blockchain identity is made from an invitation we received. */
@property (nonatomic, readonly) BOOL isFromIncomingInvitation;
/*! @brief This is TRUE if the blockchain identity is an effemeral identity returned when searching. */
@property (nonatomic, readonly) BOOL isTransient;
/*! @brief This is TRUE only if the blockchain identity is contained within a wallet. It could be in a cleanup phase where it was removed from the wallet but still being help in memory by callbacks. */
@property (nonatomic, readonly) BOOL isActive;
/*! @brief This references transient Dashpay user info if on a transient blockchain identity. */
@property (nonatomic, readonly) DSTransientDashpayUser *transientDashpayUser;
/*! @brief This is the bitwise steps that the identity has already performed in registration. */
@property (nonatomic, readonly) DSBlockchainIdentityRegistrationStep stepsCompleted;
/*! @brief This is the wallet holding the blockchain identity. There should always be a wallet associated to a blockchain identity if the blockchain identity is local, but never if it is not. */
@property (nonatomic, weak, readonly) DSWallet *wallet;
/*! @brief This is invitation that is identity originated from. */
@property (nonatomic, weak, readonly) DSBlockchainInvitation *associatedInvitation;
/*! @brief This is the index of the blockchain identity in the wallet. The index is the top derivation used to derive an extended set of keys for the identity. No two local blockchain identities should be allowed to have the same index in a wallet. For example m/.../.../.../index/key */
@property (nonatomic, readonly) uint32_t index;
/*! @brief Related to DPNS. This is the list of usernames that are associated to the identity in the domain "dash". These usernames however might not yet be registered or might be invalid. This can be used in tandem with the statusOfUsername: method */
@property (nonatomic, readonly) NSArray<NSString *> *dashpayUsernames;
/*! @brief Related to DPNS. This is the list of usernames with their .dash domain that are associated to the identity in the domain "dash". These usernames however might not yet be registered or might be invalid. This can be used in tandem with the statusOfUsername: method */
@property (nonatomic, readonly) NSArray<NSString *> *dashpayUsernameFullPaths;
/*! @brief Related to DPNS. This is current and most likely username associated to the identity. It is not necessarily registered yet on L2 however so its state should be determined with the statusOfUsername: method
@discussion There are situations where this is nil as it is not yet known or if no username has yet been set. */
@property (nullable, nonatomic, readonly) NSString *currentDashpayUsername;
/*! @brief Related to registering the identity. This is the address used to fund the registration of the identity. Dash sent to this address in the special credit funding transaction will be converted to L2 credits */
@property (nonatomic, readonly) NSString *registrationFundingAddress;
/*! @brief The known balance in credits of the identity */
@property (nonatomic, readonly) uint64_t creditBalance;
/*! @brief The number of registered active keys that the blockchain identity has */
@property (nonatomic, readonly) uint32_t activeKeyCount;
/*! @brief The number of all keys that the blockchain identity has, registered, in registration, or inactive */
@property (nonatomic, readonly) uint32_t totalKeyCount;
/*! @brief This is the transaction on L1 that has an output that is used to fund the creation of this blockchain identity.
@discussion There are situations where this is nil as it is not yet known ; if the blockchain identity is being retrieved from L2 or if we are resyncing the chain. */
@property (nullable, nonatomic, readonly) DSCreditFundingTransaction *registrationCreditFundingTransaction;
/*! @brief In our system a contact is a vue on a blockchain identity for Dashpay. A blockchain identity is therefore represented by a contact that will have relationships in the system. This is in the default backgroundContext. */
@property (nonatomic, readonly) DSDashpayUserEntity *matchingDashpayUserInViewContext;
/*! @brief This is the status of the registration of the identity. It starts off in an initial status, and ends in a confirmed status */
@property (nonatomic, readonly) DSBlockchainIdentityRegistrationStatus registrationStatus;
/*! @brief This is the localized status of the registration of the identity returned as a string. It starts off in an initial status, and ends in a confirmed status */
@property (nonatomic, readonly) NSString *localizedRegistrationStatusString;
/*! @brief This is a convenience method that checks to see if registrationStatus is confirmed */
@property (nonatomic, readonly, getter=isRegistered) BOOL registered;
/*! @brief This is a convenience factory to quickly make dashpay documents */
@property (nonatomic, readonly) DPDocumentFactory *dashpayDocumentFactory;
/*! @brief This is a convenience factory to quickly make dpns documents */
@property (nonatomic, readonly) DPDocumentFactory *dpnsDocumentFactory;
/*! @brief DashpaySyncronizationBlock represents the last L1 block height for which Dashpay would be synchronized, if this isn't at the end of the chain then we need to query L2 to make sure we don't need to update our bloom filter */
@property (nonatomic, readonly) uint32_t dashpaySyncronizationBlockHeight;
/*! @brief DashpaySyncronizationBlock represents the last L1 block hash for which Dashpay would be synchronized */
@property (nonatomic, readonly) UInt256 dashpaySyncronizationBlockHash;
// MARK: - Contracts
- (void)fetchAndUpdateContract:(DPContract *)contract;
// MARK: - Helpers
- (DSDashpayUserEntity *)matchingDashpayUserInContext:(NSManagedObjectContext *)context;
// MARK: - Identity
- (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)account forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion;
- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion;
- (void)continueRegisteringIdentityOnNetwork:(DSBlockchainIdentityRegistrationStep)steps stepsCompleted:(DSBlockchainIdentityRegistrationStep)stepsAlreadyCompleted stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion;
- (void)fundingTransactionForTopupAmount:(uint64_t)topupAmount toAddress:(NSString *)address fundedByAccount:(DSAccount *)fundingAccount completion:(void (^_Nullable)(DSCreditFundingTransaction *fundingTransaction))completion;
- (void)fetchIdentityNetworkStateInformationWithCompletion:(void (^)(BOOL success, BOOL found, NSError *error))completion;
- (void)fetchAllNetworkStateInformationWithCompletion:(void (^)(DSBlockchainIdentityQueryStep failureStep, NSArray<NSError *> *errors))completion;
- (void)fetchNeededNetworkStateInformationWithCompletion:(void (^)(DSBlockchainIdentityQueryStep failureStep, NSArray<NSError *> *errors))completion;
- (void)signStateTransition:(DSTransition *)transition completion:(void (^_Nullable)(BOOL success))completion;
- (void)signStateTransition:(DSTransition *)transition forKeyIndex:(uint32_t)keyIndex ofType:(DSKeyType)signingAlgorithm completion:(void (^_Nullable)(BOOL success))completion;
- (BOOL)verifySignature:(NSData *)signature forKeyIndex:(uint32_t)keyIndex ofType:(DSKeyType)signingAlgorithm forMessageDigest:(UInt256)messageDigest;
- (BOOL)verifySignature:(NSData *)signature ofType:(DSKeyType)signingAlgorithm forMessageDigest:(UInt256)messageDigest;
- (void)createFundingPrivateKeyWithPrompt:(NSString *)prompt completion:(void (^_Nullable)(BOOL success, BOOL cancelled))completion;
- (void)createFundingPrivateKeyForInvitationWithPrompt:(NSString *)prompt completion:(void (^_Nullable)(BOOL success, BOOL cancelled))completion;
- (void)createAndPublishRegistrationTransitionWithCompletion:(void (^_Nullable)(NSDictionary *_Nullable successInfo, NSError *_Nullable error))completion;
- (void)encryptData:(NSData *)data withKeyAtIndex:(uint32_t)index forRecipientKey:(DSKey *)recipientKey completion:(void (^_Nullable)(NSData *encryptedData))completion;
/*! @brief Register the blockchain identity to its wallet. This should only be done once on the creation of the blockchain identity.
*/
- (void)registerInWallet;
/*! @brief Unregister the blockchain identity from the wallet. This should only be used if the blockchain identity is not yet registered or if a progressive wallet wipe is happening.
@discussion When a blockchain identity is registered on the network it is automatically retrieved from the L1 chain on resync. If a client wallet wishes to change their default blockchain identity in a wallet it should be done by marking the default blockchain identity index in the wallet. Clients should not try to delete a registered blockchain identity from a wallet.
*/
- (BOOL)unregisterLocally;
/*! @brief Register the blockchain identity to its wallet from a credit funding registration transaction. This should only be done once on the creation of the blockchain identity.
@param fundingTransaction The funding transaction used to initially fund the blockchain identity.
*/
- (void)registerInWalletForRegistrationFundingTransaction:(DSCreditFundingTransaction *)fundingTransaction;
// MARK: - Keys
/*! @brief Register the blockchain identity to its wallet from a credit funding registration transaction. This should only be done once on the creation of the blockchain identity.
*/
- (void)generateBlockchainIdentityExtendedPublicKeysWithPrompt:(NSString *)prompt completion:(void (^_Nullable)(BOOL registered))completion;
- (BOOL)setExternalFundingPrivateKey:(DSECDSAKey *)privateKey;
- (BOOL)hasBlockchainIdentityExtendedPublicKeys;
- (DSBlockchainIdentityKeyStatus)statusOfKeyAtIndex:(NSUInteger)index;
- (DSKeyType)typeOfKeyAtIndex:(NSUInteger)index;
- (DSKey *_Nullable)keyAtIndex:(NSUInteger)index;
- (uint32_t)keyCountForKeyType:(DSKeyType)keyType;
+ (NSString *)localizedStatusOfKeyForBlockchainIdentityKeyStatus:(DSBlockchainIdentityKeyStatus)status;
- (NSString *)localizedStatusOfKeyAtIndex:(NSUInteger)index;
- (DSKey *_Nullable)createNewKeyOfType:(DSKeyType)type saveKey:(BOOL)saveKey returnIndex:(uint32_t *)rIndex;
- (DSKey *_Nullable)keyOfType:(DSKeyType)type atIndex:(uint32_t)rIndex;
+ (DSAuthenticationKeysDerivationPath *_Nullable)derivationPathForType:(DSKeyType)type forWallet:(DSWallet *)wallet;
+ (DSKey *_Nullable)keyFromKeyDictionary:(NSDictionary *)dictionary rType:(uint32_t *)rType rIndex:(uint32_t *)rIndex;
+ (DSKey *_Nullable)firstKeyInIdentityDictionary:(NSDictionary *)identityDictionary;
// MARK: - Dashpay
/*! @brief This is a helper to easily get the avatar path of the matching dashpay user. */
@property (nonatomic, readonly, nullable) NSString *avatarPath;
/*! @brief This is a helper to easily get the avatar fingerprint of the matching dashpay user. */
@property (nonatomic, readonly) NSData *avatarFingerprint;
/*! @brief This is a helper to easily get the avatar hash of the matching dashpay user. */
@property (nonatomic, readonly, nullable) NSData *avatarHash;
/*! @brief This is a helper to easily get the display name of the matching dashpay user. */
@property (nonatomic, readonly, nullable) NSString *displayName;
/*! @brief This is a helper to easily get the public message of the matching dashpay user. */
@property (nonatomic, readonly, nullable) NSString *publicMessage;
- (void)sendNewFriendRequestToBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity completion:(void (^)(BOOL success, NSArray<NSError *> *_Nullable errors))completion;
- (void)sendNewFriendRequestToPotentialContact:(DSPotentialContact *)potentialContact completion:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)sendNewFriendRequestMatchingPotentialFriendship:(DSPotentialOneWayFriendship *)potentialFriendship completion:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)acceptFriendRequestFromBlockchainIdentity:(DSBlockchainIdentity *)otherBlockchainIdentity completion:(void (^)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)acceptFriendRequest:(DSFriendRequestEntity *)friendRequest completion:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (BOOL)activePrivateKeysAreLoadedWithFetchingError:(NSError **)error;
- (void)fetchContactRequests:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)fetchOutgoingContactRequests:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)fetchIncomingContactRequests:(void (^_Nullable)(BOOL success, NSArray<NSError *> *errors))completion;
- (void)fetchProfileWithCompletion:(void (^_Nullable)(BOOL success, NSError *error))completion;
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName;
- (void)updateDashpayProfileWithPublicMessage:(NSString *)publicMessage;
- (void)updateDashpayProfileWithAvatarURLString:(NSString *)avatarURLString;
- (void)updateDashpayProfileWithAvatarURLString:(NSString *)avatarURLString avatarHash:(NSData *)avatarHash avatarFingerprint:(NSData *)avatarFingerprint;
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName publicMessage:(NSString *)publicMessage;
#if TARGET_OS_IOS
- (void)updateDashpayProfileWithAvatarImage:(UIImage *)avatarImage avatarData:(NSData *)data avatarURLString:(NSString *)avatarURLString;
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName publicMessage:(NSString *)publicMessage avatarImage:(UIImage *)avatarImage avatarData:(NSData *)data avatarURLString:(NSString *)avatarURLString;
#else
- (void)updateDashpayProfileWithAvatarImage:(NSImage *)avatarImage avatarData:(NSData *)data avatarURLString:(NSString *)avatarURLString;
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName publicMessage:(NSString *)publicMessage avatarImage:(NSImage *)avatarImage avatarData:(NSData *)data avatarURLString:(NSString *)avatarURLString;
#endif
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName publicMessage:(NSString *)publicMessage avatarURLString:(NSString *)avatarURLString;
- (void)updateDashpayProfileWithDisplayName:(NSString *)displayName publicMessage:(NSString *)publicMessage avatarURLString:(NSString *)avatarURLString avatarHash:(NSData *)avatarHash avatarFingerprint:(NSData *)avatarFingerprint;
- (void)signedProfileDocumentTransitionInContext:(NSManagedObjectContext *)context withCompletion:(void (^)(DSTransition *transition, BOOL cancelled, NSError *error))completion;
- (void)signAndPublishProfileWithCompletion:(void (^)(BOOL success, BOOL cancelled, NSError *error))completion;
- (BOOL)verifyKeysForWallet:(DSWallet *)wallet;
// MARK: - Dashpay Friendship Helpers
- (DSBlockchainIdentityFriendshipStatus)friendshipStatusForRelationshipWithBlockchainIdentity:(DSBlockchainIdentity *)otherBlockchainIdentity;
// MARK: - DPNS
- (void)addDashpayUsername:(NSString *)username save:(BOOL)save;
- (void)addUsername:(NSString *)username inDomain:(NSString *)domain save:(BOOL)save;
- (DSBlockchainIdentityUsernameStatus)statusOfUsername:(NSString *)username inDomain:(NSString *)domain;
- (DSBlockchainIdentityUsernameStatus)statusOfDashpayUsername:(NSString *)username;
- (void)registerUsernamesWithCompletion:(void (^_Nullable)(BOOL success, NSError *error))completion;
- (void)fetchUsernamesWithCompletion:(void (^_Nullable)(BOOL success, NSError *error))completion;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/DAPI/Networking/DSDAPICoreNetworkServiceProtocol.h | //
// Created by <NAME>
// Copyright © 2021 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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.
//
#import "BigIntTypes.h"
#import "DSDAPINetworkServiceRequest.h"
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class DSTransaction;
@protocol DSDAPICoreNetworkServiceProtocol <NSObject>
- (id<DSDAPINetworkServiceRequest>)getStatusWithCompletionQueue:(dispatch_queue_t)completionQueue success:(void (^)(NSDictionary *status))success
failure:(void (^)(NSError *error))failure;
- (id<DSDAPINetworkServiceRequest>)getTransactionWithHash:(UInt256)transactionHash completionQueue:(dispatch_queue_t)completionQueue success:(void (^)(DSTransaction *transaction))success failure:(void (^)(NSError *error))failure;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Chain/DSChain.h | //
// DSChain.h
// DashSync
//
// Created by Quantum Explorer on 05/05/18.
// Copyright (c) 2018 Quantum Explorer <<EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "BigIntTypes.h"
#import "DSChainConstants.h"
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXPORT NSString *const DSChainWalletsDidChangeNotification;
FOUNDATION_EXPORT NSString *const DSChainStandaloneDerivationPathsDidChangeNotification;
FOUNDATION_EXPORT NSString *const DSChainStandaloneAddressesDidChangeNotification;
FOUNDATION_EXPORT NSString *const DSChainChainSyncBlocksDidChangeNotification;
FOUNDATION_EXPORT NSString *const DSChainBlockWasLockedNotification;
FOUNDATION_EXPORT NSString *const DSChainNotificationBlockKey;
// For improved performance DSChainInitialHeadersDidChangeNotification is not garanteed to trigger on every initial headers change.
FOUNDATION_EXPORT NSString *const DSChainTerminalBlocksDidChangeNotification;
FOUNDATION_EXPORT NSString *const DSChainInitialHeadersDidFinishSyncingNotification;
FOUNDATION_EXPORT NSString *const DSChainBlocksDidFinishSyncingNotification;
FOUNDATION_EXPORT NSString *const DSChainNewChainTipBlockNotification;
typedef NS_ENUM(uint16_t, DSChainType)
{
DSChainType_MainNet = 0,
DSChainType_TestNet = 1,
DSChainType_DevNet = 2,
};
typedef NS_ENUM(NSUInteger, DSTransactionDirection)
{
DSTransactionDirection_Sent,
DSTransactionDirection_Received,
DSTransactionDirection_Moved,
DSTransactionDirection_NotAccountFunds,
};
typedef NS_ENUM(uint16_t, DSChainSyncPhase)
{
DSChainSyncPhase_Offline = 0,
DSChainSyncPhase_InitialTerminalBlocks,
DSChainSyncPhase_ChainSync,
DSChainSyncPhase_Synced,
};
@class DSChain, DSChainEntity, DSChainManager, DSWallet, DSMerkleBlock, DSBlock, DSFullBlock, DSPeer, DSDerivationPath, DSTransaction, DSAccount, DSSimplifiedMasternodeEntry, DSBlockchainIdentity, DSBloomFilter, DSProviderRegistrationTransaction, DSMasternodeList, DPContract, DSCheckpoint, DSChainLock;
@protocol DSChainDelegate;
@interface DSChain : NSObject
// MARK: - Shortcuts
/*! @brief The chain manager is a container for all managers (peer, identity, governance, masternode, spork and transition). It also is used to control the sync process. */
@property (nonatomic, weak, nullable) DSChainManager *chainManager;
/*! @brief The chain entity associated in Core Data in the required context. */
- (DSChainEntity *)chainEntityInContext:(NSManagedObjectContext *)context;
/*! @brief The managed object context of the chain. */
@property (nonatomic, readonly) NSManagedObjectContext *chainManagedObjectContext;
// MARK: - L1 Network Chain Info
/*! @brief The network name. Currently main, test, dev or reg. */
@property (nonatomic, readonly) NSString *networkName;
/*! @brief An array of known hard coded checkpoints for the chain. */
@property (nonatomic, readonly) NSArray<DSCheckpoint *> *checkpoints;
// MARK: Sync
/*! @brief The genesis hash is the hash of the first block of the chain. For a devnet this is actually the second block as the first block is created in a special way for devnets. */
@property (nonatomic, readonly) UInt256 genesisHash;
/*! @brief The magic number is used in message headers to indicate what network (or chain) a message is intended for. */
@property (nonatomic, readonly) uint32_t magicNumber;
/*! @brief The base reward is the intial mining reward at genesis for the chain. This goes down by 7% every year. A SPV client does not validate that the reward amount is correct as it would not make sense for miners to enter incorrect rewards as the blocks would be rejected by full nodes. */
@property (nonatomic, readonly) uint64_t baseReward;
/*! @brief minProtocolVersion is the minimum protocol version that peers on this chain can communicate with. This should only be changed in the case of devnets. */
@property (nonatomic, assign) uint32_t minProtocolVersion;
/*! @brief protocolVersion is the protocol version that we currently use for this chain. This should only be changed in the case of devnets. */
@property (nonatomic, assign) uint32_t protocolVersion;
/*! @brief headersMaxAmount is the maximum amount of headers that is expected from peers. */
@property (nonatomic, assign) uint32_t headersMaxAmount;
/*! @brief maxProofOfWork is the lowest amount of work effort required to mine a block on the chain. */
@property (nonatomic, readonly) UInt256 maxProofOfWork;
/*! @brief maxProofOfWorkTarget is the lowest amount of work effort required to mine a block on the chain. Here it is represented as the compact target. */
@property (nonatomic, readonly) uint32_t maxProofOfWorkTarget;
/*! @brief allowMinDifficultyBlocks is set to TRUE on networks where mining is low enough that it can be attacked by increasing difficulty with ASICs and then no longer running ASICs. This is set to NO for Mainnet, and generally should be YES on all other networks. */
@property (nonatomic, readonly) BOOL allowMinDifficultyBlocks;
/*! @brief This is the minimum amount that can be entered into an amount for a output for it not to be considered dust. */
@property (nonatomic, readonly) uint64_t minOutputAmount;
// MARK: Fees
@property (nonatomic, assign) uint64_t feePerByte;
/*! @brief The fee for transactions in L1 are now entirely dependent on their size. */
- (uint64_t)feeForTxSize:(NSUInteger)size;
// MARK: Ports
/*! @brief The standard port for the chain for L1 communication. */
@property (nonatomic, assign) uint32_t standardPort;
/*! @brief The standard port for the chain for L2 communication through JRPC. */
@property (nonatomic, assign) uint32_t standardDapiJRPCPort;
/*! @brief The standard port for the chain for L2 communication through GRPC. */
@property (nonatomic, assign) uint32_t standardDapiGRPCPort;
// MARK: Sporks
/*! @brief The spork public key as a hex string. */
@property (nonatomic, strong, nullable) NSString *sporkPublicKeyHexString;
/*! @brief The spork private key as a base 58 string. */
@property (nonatomic, strong, nullable) NSString *sporkPrivateKeyBase58String;
/*! @brief The spork address base 58 string (addresses are known to be base 58). */
@property (nonatomic, strong, nullable) NSString *sporkAddress;
// MARK: - L2 Network Chain Info
/*! @brief The dpns contract id. */
@property (nonatomic, assign) UInt256 dpnsContractID;
/*! @brief The dashpay contract id. */
@property (nonatomic, assign) UInt256 dashpayContractID;
// MARK: - DashSync Chain Info
/*! @brief The chain type (MainNet, TestNet or DevNet). */
@property (nonatomic, readonly) DSChainType chainType;
/*! @brief A threshold after which a peer will be banned. */
@property (nonatomic, readonly) uint32_t peerMisbehavingThreshold;
/*! @brief True if this chain syncs the blockchain. All Chains currently sync the blockchain. */
@property (nonatomic, readonly) BOOL syncsBlockchain;
/*! @brief True if this chain should sync headers first for masternode list verification. */
@property (nonatomic, readonly) BOOL needsInitialTerminalHeadersSync;
/*! @brief The default transaction version used when sending transactions. */
@property (nonatomic, readonly) uint16_t transactionVersion;
/*! @brief The number of minimumDifficultyBlocks. */
@property (nonatomic, assign) uint32_t minimumDifficultyBlocks;
/*! @brief Returns all standard derivaton paths used for the chain based on the account number. */
- (NSArray<DSDerivationPath *> *)standardDerivationPathsForAccountNumber:(uint32_t)accountNumber;
// MARK: Names and Identifiers
/*! @brief The unique identifier of the chain. This unique id follows the same chain accross devices because it is the short hex string of the genesis hash. */
@property (nonatomic, readonly) NSString *uniqueID;
/*! @brief The devnet identifier is the name of the devnet, the genesis hash of a devnet uses this devnet identifier in its construction. */
@property (nonatomic, readonly, nullable) NSString *devnetIdentifier;
/*! @brief The name of the chain (Mainnet-Testnet-Devnet). */
@property (nonatomic, readonly) NSString *name;
/*! @brief The localized name of the chain (Mainnet-Testnet-Devnet). */
@property (nonatomic, readonly) NSString *localizedName;
- (void)setDevnetNetworkName:(NSString *)networkName;
// MARK: - Wallets
/*! @brief The wallets in the chain. */
@property (nonatomic, readonly) NSArray<DSWallet *> *wallets;
/*! @brief Conveniance method. Does this walleet have a chain? */
@property (nonatomic, readonly) BOOL hasAWallet;
/*! @brief Conveniance method. The earliest known creation time for any wallet in this chain. */
@property (nonatomic, readonly) NSTimeInterval earliestWalletCreationTime;
/*! @brief Unregister a wallet from the chain, it will no longer be loaded or used. */
- (void)unregisterWallet:(DSWallet *)wallet;
/*! @brief Register a wallet to the chain. */
- (void)registerWallet:(DSWallet *)wallet;
/*! @brief Unregister all wallets from the chain, they will no longer be loaded or used. */
- (void)unregisterAllWallets;
/*! @brief Unregister all wallets from the chain that don't have an extended public key in one of their derivation paths, they will no longer be loaded or used. */
- (void)unregisterAllWalletsMissingExtendedPublicKeys;
// MARK: - Standalone Derivation Paths
/*! @brief Standalone derivation paths used in this chain. This is currently an experimental feature */
@property (nonatomic, readonly) NSArray<DSDerivationPath *> *standaloneDerivationPaths;
/*! @brief Conveniance method to find out if the chain has a standalone derivation path. Standalone derivation paths are currently an experimental feature */
@property (nonatomic, readonly) BOOL hasAStandaloneDerivationPath;
/*! @brief Unregister a standalone derivation path from the chain, it will no longer be loaded or used. Standalone derivation paths are currently an experimental feature */
- (void)unregisterStandaloneDerivationPath:(DSDerivationPath *)derivationPath;
/*! @brief Register a standalone derivation path to the chain. Standalone derivation paths are currently an experimental feature */
- (void)registerStandaloneDerivationPath:(DSDerivationPath *)derivationPath;
// MARK: - Checkpoints
/*! @brief Returns the last checkpoint that has a masternode list attached to it. */
- (DSCheckpoint *_Nullable)lastCheckpointHavingMasternodeList;
/*! @brief Returns the checkpoint matching the parameter block hash, if one exists. */
- (DSCheckpoint *_Nullable)checkpointForBlockHash:(UInt256)blockHash;
/*! @brief Returns the checkpoint at a given block height, if one exists at that block height. */
- (DSCheckpoint *_Nullable)checkpointForBlockHeight:(uint32_t)blockHeight;
/*! @brief Returns the last checkpoint on or before the given height. */
- (DSCheckpoint *)lastCheckpointOnOrBeforeHeight:(uint32_t)height;
/*! @brief Returns the last checkpoint on or before the given timestamp. */
- (DSCheckpoint *)lastCheckpointOnOrBeforeTimestamp:(NSTimeInterval)timestamp;
/*! @brief When used this will change the checkpoint used for initial headers sync. This value is not persisted. */
- (void)useCheckpointBeforeOrOnHeightForTerminalBlocksSync:(uint32_t)blockHeight;
/*! @brief When used this will change the checkpoint used for main chain syncing. This value is not persisted. */
- (void)useCheckpointBeforeOrOnHeightForSyncingChainBlocks:(uint32_t)blockHeight;
// MARK: - Blocks and Headers
/*! @brief The last known chain sync block on the chain. */
@property (nonatomic, readonly, nullable) DSBlock *lastSyncBlock;
/*! @brief The last known chain sync block on the chain, don't recover from checkpoints if it is not known. */
@property (nonatomic, readonly, nullable) DSBlock *lastSyncBlockDontUseCheckpoints;
/*! @brief The last known terminal block on the chain. */
@property (nonatomic, readonly, nullable) DSBlock *lastTerminalBlock;
/*! @brief The last known block on the chain before the given timestamp. */
- (DSBlock *)lastChainSyncBlockOnOrBeforeTimestamp:(NSTimeInterval)timestamp;
/*! @brief The last known block or header on the chain before the given timestamp. */
- (DSBlock *)lastBlockOnOrBeforeTimestamp:(NSTimeInterval)timestamp;
/*! @brief The last known orphan on the chain. An orphan is a block who's parent is currently not known. */
@property (nonatomic, readonly, nullable) DSBlock *lastOrphan;
/*! @brief A dictionary of the the most recent known blocks keyed by block hash. */
@property (nonatomic, readonly) NSDictionary<NSValue *, DSMerkleBlock *> *recentBlocks;
/*! @brief A short hex string of the last block's block hash. */
@property (nonatomic, readonly, nullable) NSString *chainTip;
/*! @brief The block locator array is an array of the 10 most recent block hashes in decending order followed by block hashes that double the step back each iteration in decending order and finishing with the previous known checkpoint after that last hash. Something like (top, -1, -2, -3, -4, -5, -6, -7, -8, -9, -11, -15, -23, -39, -71, -135, ..., 0). */
@property (nonatomic, readonly, nullable) NSArray<NSData *> *chainSyncBlockLocatorArray;
/*! @brief This block locator array is an array of 10 block hashes in decending order before the given timestamp followed by block hashes that double the step back each iteration in decending order and finishing with the previous known checkpoint after that last hash. Something like (top, -1, -2, -3, -4, -5, -6, -7, -8, -9, -11, -15, -23, -39, -71, -135, ..., 0). */
- (NSArray<NSData *> *)blockLocatorArrayOnOrBeforeTimestamp:(NSTimeInterval)timestamp includeInitialTerminalBlocks:(BOOL)includeHeaders;
/*! @brief The timestamp of a block at a given height. */
- (NSTimeInterval)timestampForBlockHeight:(uint32_t)blockHeight; // seconds since 1970, 00:00:00 01/01/01 GMT
/*! @brief The block on the main chain at a certain height. By main chain it is understood to mean not forked chain - this could be on mainnet, testnet or a devnet. */
- (DSMerkleBlock *_Nullable)blockAtHeight:(uint32_t)height;
/*! @brief Returns a known block with the given block hash. This does not have to be in the main chain. A null result could mean that the block was old and has since been discarded. */
- (DSMerkleBlock *_Nullable)blockForBlockHash:(UInt256)blockHash;
/*! @brief Returns a known block in the main chain with the given block hash. A null result could mean that the block was old and has since been discarded. */
- (DSMerkleBlock *_Nullable)recentTerminalBlockForBlockHash:(UInt256)blockHash;
/*! @brief Returns a known block with a given distance from the chain tip. A null result would mean that the given distance exceeded the number of blocks kept locally. */
- (DSMerkleBlock *_Nullable)blockFromChainTip:(NSUInteger)blocksAgo;
// MARK: Chain Sync
/*! @brief Returns the hash of the last persisted sync block. The sync block itself most likely is not persisted. */
@property (nonatomic, readonly) UInt256 lastPersistedChainSyncBlockHash;
/*! @brief Returns the height of the last persisted sync block. The sync block itself most likely is not persisted. */
@property (nonatomic, readonly) uint32_t lastPersistedChainSyncBlockHeight;
/*! @brief Returns the timestamp of the last persisted sync block. The sync block itself most likely is not persisted. */
@property (nonatomic, readonly) NSTimeInterval lastPersistedChainSyncBlockTimestamp;
/*! @brief Returns the locators of the last persisted chain sync block. The sync block itself most likely is not persisted. */
@property (nullable, nonatomic, readonly) NSArray *lastPersistedChainSyncLocators;
// MARK: Last Block Information
/*! @brief Returns the height of the last sync block. */
@property (nonatomic, readonly) uint32_t lastSyncBlockHeight;
/*! @brief Returns the hash of the last sync block. */
@property (nonatomic, readonly) UInt256 lastSyncBlockHash;
/*! @brief Returns the timestamp of the last sync block. */
@property (nonatomic, readonly) NSTimeInterval lastSyncBlockTimestamp;
/*! @brief Returns the height of the last header used in initial headers sync to get the deterministic masternode list. */
@property (nonatomic, readonly) uint32_t lastTerminalBlockHeight;
/*! @brief Returns the height of the best block. */
@property (nonatomic, readonly) uint32_t bestBlockHeight;
/*! @brief Returns the estimated height of chain. This is reported by the current download peer but can not be verified and is not secure. */
@property (nonatomic, readonly) uint32_t estimatedBlockHeight;
/*! @brief Returns the height of a block having the given hash. If no block is found returns UINT32_MAX */
- (uint32_t)heightForBlockHash:(UInt256)blockhash;
/*! @brief Returns the height of a block having the given hash. This does less expensive checks than heightForBlockHash and is not garanteed to be accurate, but can be used for logging. If no block is found returns UINT32_MAX */
- (uint32_t)quickHeightForBlockHash:(UInt256)blockhash;
// MARK: Chain Lock
/*! @brief Returns the last chainLock known by the chain at the heighest height. */
@property (nonatomic, readonly) DSChainLock *lastChainLock;
/*! @brief Adds a chainLock to the chain and applies it corresponding block. It will be applied to both terminal blocks and sync blocks. */
- (BOOL)addChainLock:(DSChainLock *)chainLock;
/*! @brief Returns if there is a block at the following height that is confirmed. */
- (BOOL)blockHeightChainLocked:(uint32_t)height;
// MARK: - Transactions
/*! @brief Returns all wallet transactions sorted by date, most recent first. */
@property (nonatomic, readonly) NSArray<DSTransaction *> *allTransactions;
/*! @brief Returns the transaction with the given hash if it's been registered in any wallet on the chain (might also return non-registered) */
- (DSTransaction *_Nullable)transactionForHash:(UInt256)txHash;
/*! @brief Returns the direction of a transaction for the chain (Sent - Received - Moved - Not Account Funds) */
- (DSTransactionDirection)directionOfTransaction:(DSTransaction *)transaction;
/*! @brief Returns the amount received globally from the transaction (total outputs to change and/or receive addresses) */
- (uint64_t)amountReceivedFromTransaction:(DSTransaction *)transaction;
/*! @brief Returns the amount sent globally by the trasaction (total wallet outputs consumed, change and fee included) */
- (uint64_t)amountSentByTransaction:(DSTransaction *)transaction;
/*! @brief Returns if this transaction has any local references. Local references are a pubkey hash contained in a wallet, pubkeys in wallets special derivation paths, or anything that would make the transaction relevant for this device. */
- (BOOL)transactionHasLocalReferences:(DSTransaction *)transaction;
// MARK: - Bloom Filter
/*! @brief Returns if a filter can be created for the chain. Generally this means that the chain has at least a wallet or a standalone derivation path. */
@property (nonatomic, readonly) BOOL canConstructAFilter;
/*! @brief Returns a bloom filter with the given false positive rate tweaked with the value tweak. The value tweak is generally peer specific. */
- (DSBloomFilter *)bloomFilterWithFalsePositiveRate:(double)falsePositiveRate withTweak:(uint32_t)tweak;
// MARK: - Accounts and Balances
/*! @brief The current wallet balance excluding transactions known to be invalid. */
@property (nonatomic, readonly) uint64_t balance;
/*! @brief All accounts that contain the specified transaction hash. The transaction is also returned if it is found. */
- (NSArray<DSAccount *> *)accountsForTransactionHash:(UInt256)txHash transaction:(DSTransaction *_Nullable *_Nullable)transaction;
/*! @brief Returns the first account with a balance. */
- (DSAccount *_Nullable)firstAccountWithBalance;
/*! @brief Returns an account to which the given transaction is or can be associated with (even if it hasn't been registered), no account if the transaction is not associated with the wallet. */
- (DSAccount *_Nullable)firstAccountThatCanContainTransaction:(DSTransaction *)transaction;
/*! @brief Returns all accounts to which the given transaction is or can be associated with (even if it hasn't been registered) */
- (NSArray *)accountsThatCanContainTransaction:(DSTransaction *_Nonnull)transaction;
/*! @brief Returns an account to which the given transaction hash is associated with, no account if the transaction hash is not associated with the wallet. */
- (DSAccount *_Nullable)firstAccountForTransactionHash:(UInt256)txHash transaction:(DSTransaction *_Nullable *_Nullable)transaction wallet:(DSWallet *_Nullable *_Nullable)wallet;
/*! @brief Returns an account to which the given address is contained in a derivation path. */
- (DSAccount *_Nullable)accountContainingAddress:(NSString *)address;
/*! @brief Returns an account to which the given address is known by a dashpay outgoing derivation path. */
- (DSAccount *_Nullable)accountContainingDashpayExternalDerivationPathAddress:(NSString *)address;
// MARK: - Governance
/*! @brief Returns a count of all governance objects. */
@property (nonatomic, assign) uint32_t totalGovernanceObjectsCount;
// MARK: - Identities
/*! @brief Returns a count of local blockchain identities. */
@property (nonatomic, readonly) uint32_t localBlockchainIdentitiesCount;
/*! @brief Returns a count of blockchain invitations that have been created locally. */
@property (nonatomic, readonly) uint32_t localBlockchainInvitationsCount;
/*! @brief Returns an array of all local blockchain identities. */
@property (nonatomic, readonly) NSArray<DSBlockchainIdentity *> *localBlockchainIdentities;
/*! @brief Returns a dictionary of all local blockchain identities keyed by uniqueId. */
@property (nonatomic, readonly) NSDictionary<NSData *, DSBlockchainIdentity *> *localBlockchainIdentitiesByUniqueIdDictionary;
/*! @brief Returns a blockchain identity by uniqueId, if it exists. */
- (DSBlockchainIdentity *_Nullable)blockchainIdentityForUniqueId:(UInt256)uniqueId;
/*! @brief Returns a blockchain identity that could have created this contract. */
- (DSBlockchainIdentity *_Nullable)blockchainIdentityThatCreatedContract:(DPContract *)contract withContractId:(UInt256)contractId foundInWallet:(DSWallet *_Nullable *_Nullable)foundInWallet;
/*! @brief Returns a blockchain identity by uniqueId, if it exists. Also returns the wallet it was found in. */
- (DSBlockchainIdentity *_Nullable)blockchainIdentityForUniqueId:(UInt256)uniqueId foundInWallet:(DSWallet *_Nullable *_Nullable)foundInWallet;
/*! @brief Returns a blockchain identity by uniqueId, if it exists. Also returns the wallet it was found in. Allows to search foreign blockchain identities too */
- (DSBlockchainIdentity *)blockchainIdentityForUniqueId:(UInt256)uniqueId foundInWallet:(DSWallet *_Nullable *_Nullable)foundInWallet includeForeignBlockchainIdentities:(BOOL)includeForeignBlockchainIdentities;
// MARK: - Chain Retrieval methods
/*! @brief Mainnet chain. */
+ (DSChain *)mainnet;
/*! @brief Testnet chain. */
+ (DSChain *)testnet;
/*! @brief Devnet chain with given identifier. */
+ (DSChain *_Nullable)devnetWithIdentifier:(NSString *)identifier;
/*! @brief Set up a given devnet with an identifier, checkpoints, default L1, JRPC and GRPC ports, a dpns contractId and a dashpay contract id. minimumDifficultyBlocks are used to speed up the initial chain creation. This devnet will be registered on the keychain. The additional isTransient property allows for test usage where you do not wish to persist the devnet. */
+ (DSChain *)setUpDevnetWithIdentifier:(NSString *)identifier withCheckpoints:(NSArray<DSCheckpoint *> *_Nullable)checkpointArray withMinimumDifficultyBlocks:(uint32_t)minimumDifficultyBlocks withDefaultPort:(uint32_t)port withDefaultDapiJRPCPort:(uint32_t)dapiJRPCPort withDefaultDapiGRPCPort:(uint32_t)dapiGRPCPort dpnsContractID:(UInt256)dpnsContractID dashpayContractID:(UInt256)dashpayContractID isTransient:(BOOL)isTransient;
/*! @brief Retrieve from the keychain a devnet with an identifier and add given checkpoints. */
+ (DSChain *)recoverKnownDevnetWithIdentifier:(NSString *)identifier withCheckpoints:(NSArray<DSCheckpoint *> *)checkpointArray performSetup:(BOOL)performSetup;
/*! @brief Retrieve a chain having the specified network name. */
+ (DSChain *_Nullable)chainForNetworkName:(NSString *_Nullable)networkName;
// MARK: - Chain Info methods
- (BOOL)isMainnet;
- (BOOL)isTestnet;
- (BOOL)isDevnetAny;
- (BOOL)isEvolutionEnabled;
- (BOOL)isDevnetWithGenesisHash:(UInt256)genesisHash;
@end
@protocol DSChainTransactionsDelegate
@required
- (void)chain:(DSChain *)chain didSetBlockHeight:(int32_t)height andTimestamp:(NSTimeInterval)timestamp forTransactionHashes:(NSArray<NSValue *> *)txHashes updatedTransactions:(NSArray *)updatedTransactions;
- (void)chainWasWiped:(DSChain *)chain;
@end
@protocol DSChainIdentitiesDelegate
@required
- (void)chain:(DSChain *)chain didFinishInChainSyncPhaseFetchingBlockchainIdentityDAPInformation:(DSBlockchainIdentity *)blockchainIdentity;
@end
@protocol DSChainDelegate <DSChainTransactionsDelegate, DSChainIdentitiesDelegate>
@required
- (void)chainWillStartSyncingBlockchain:(DSChain *)chain;
- (void)chainShouldStartSyncingBlockchain:(DSChain *)chain onPeer:(DSPeer *)peer;
- (void)chainFinishedSyncingTransactionsAndBlocks:(DSChain *)chain fromPeer:(DSPeer *_Nullable)peer onMainChain:(BOOL)onMainChain;
- (void)chainFinishedSyncingInitialHeaders:(DSChain *)chain fromPeer:(DSPeer *_Nullable)peer onMainChain:(BOOL)onMainChain;
- (void)chainFinishedSyncingMasternodeListsAndQuorums:(DSChain *)chain;
- (void)chain:(DSChain *)chain receivedOrphanBlock:(DSBlock *)merkleBlock fromPeer:(DSPeer *)peer;
- (void)chain:(DSChain *)chain wasExtendedWithBlock:(DSBlock *)merkleBlock fromPeer:(DSPeer *)peer;
- (void)chain:(DSChain *)chain badBlockReceivedFromPeer:(DSPeer *)peer;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Wallet/DSWallet.h | //
// DSWallet.h
// DashSync
//
// Created by <NAME> on 5/20/18.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "BigIntTypes.h"
#import "DSBIP39Mnemonic.h"
#import "DSBlockchainIdentity.h"
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^SeedCompletionBlock)(NSData *_Nullable seed, BOOL cancelled);
typedef void (^SeedRequestBlock)(NSString *_Nullable authprompt, uint64_t amount, _Nullable SeedCompletionBlock seedCompletion);
FOUNDATION_EXPORT NSString *_Nonnull const DSWalletBalanceDidChangeNotification;
#define DUFFS 100000000LL
#define MAX_MONEY (21000000LL * DUFFS)
@class DSChain, DSAccount, DSTransaction, DSDerivationPath, DSLocalMasternode, DSKey, DSSpecialTransactionsWalletHolder, DSBLSKey, DSECDSAKey, DSBlockchainInvitation;
@interface DSWallet : NSObject
@property (nonatomic, readonly) NSArray<DSAccount *> *accounts;
@property (nonatomic, readonly) DSSpecialTransactionsWalletHolder *specialTransactionsHolder;
@property (nonatomic, readonly) NSDictionary<NSData *, DSBlockchainIdentity *> *blockchainIdentities;
@property (nonatomic, readonly) NSDictionary<NSData *, DSBlockchainInvitation *> *blockchainInvitations;
@property (nonatomic, readonly, nullable) DSBlockchainIdentity *defaultBlockchainIdentity;
- (void)setDefaultBlockchainIdentity:(DSBlockchainIdentity *)defaultBlockchainIdentity;
@property (nonatomic, readonly) NSArray<NSString *> *blockchainIdentityAddresses;
@property (nonatomic, readonly) NSArray<NSString *> *providerOwnerAddresses;
@property (nonatomic, readonly) NSArray<NSString *> *providerVotingAddresses;
@property (nonatomic, readonly) NSArray<NSString *> *providerOperatorAddresses;
//This is unique among all wallets and all chains
@property (nonatomic, readonly) NSString *uniqueIDString;
@property (nonatomic, readonly) NSTimeInterval walletCreationTime;
// set to true if this wallet is not stored on disk
@property (nonatomic, readonly, getter=isTransient) BOOL transient;
// chain for the wallet
@property (nonatomic, readonly) DSChain *chain;
// current wallet balance excluding transactions known to be invalid
@property (nonatomic, readonly) uint64_t balance;
// all previously generated external addresses
@property (nonatomic, readonly) NSSet<NSString *> *allReceiveAddresses;
// all previously generated internal addresses
@property (nonatomic, readonly) NSSet<NSString *> *allChangeAddresses;
// NSValue objects containing UTXO structs
@property (nonatomic, readonly) NSArray *unspentOutputs;
// latest 100 transactions sorted by date, most recent first
@property (nonatomic, readonly) NSArray<DSTransaction *> *recentTransactions;
// all wallet transactions sorted by date, most recent first
@property (nonatomic, readonly) NSArray<DSTransaction *> *allTransactions;
// the total amount spent from the wallet (excluding change)
@property (nonatomic, readonly) uint64_t totalSent;
// the total amount received by the wallet (excluding change)
@property (nonatomic, readonly) uint64_t totalReceived;
// the first unused index for blockchain identity registration funding
@property (nonatomic, readonly) uint32_t unusedBlockchainIdentityIndex;
// the first unused index for invitations
@property (nonatomic, readonly) uint32_t unusedBlockchainInvitationIndex;
// the amount of known blockchain identities
@property (nonatomic, readonly) uint32_t blockchainIdentitiesCount;
// the amount of known blockchain invitations
@property (nonatomic, readonly) uint32_t blockchainInvitationsCount;
// The fingerprint for currentTransactions
@property (nonatomic, readonly) NSData *chainSynchronizationFingerprint;
- (void)authPrivateKey:(void (^_Nullable)(NSString *_Nullable authKey))completion;
+ (DSWallet *_Nullable)standardWalletWithSeedPhrase:(NSString *)seedPhrase setCreationDate:(NSTimeInterval)creationDate forChain:(DSChain *)chain storeSeedPhrase:(BOOL)storeSeedPhrase isTransient:(BOOL)isTransient;
+ (DSWallet *_Nullable)standardWalletWithRandomSeedPhraseForChain:(DSChain *)chain storeSeedPhrase:(BOOL)store isTransient:(BOOL)isTransient;
+ (DSWallet *_Nullable)standardWalletWithRandomSeedPhraseInLanguage:(DSBIP39Language)language forChain:(DSChain *)chain storeSeedPhrase:(BOOL)store isTransient:(BOOL)isTransient;
+ (DSWallet *_Nullable)transientWalletWithDerivedKeyData:(NSData *)derivedData forChain:(DSChain *)chain;
- (instancetype)initWithUniqueID:(NSString *_Nonnull)uniqueID forChain:(DSChain *_Nonnull)chain;
// true if the address is controlled by the wallet
- (BOOL)containsAddress:(NSString *)address;
// true if the address is controlled by the wallet except for evolution addresses
- (BOOL)accountsBaseDerivationPathsContainAddress:(NSString *)address;
- (DSAccount *_Nullable)accountForAddress:(NSString *)address;
- (DSAccount *_Nullable)accountForDashpayExternalDerivationPathAddress:(NSString *)address;
// true if the address was previously used as an input or output for this wallet
- (BOOL)addressIsUsed:(NSString *)address;
- (BOOL)transactionAddressAlreadySeenInOutputs:(NSString *)address;
- (void)chainUpdatedBlockHeight:(int32_t)height;
// sets the block heights and timestamps for the given transactions, and returns an array of hashes of the updated tx
// use a height of TX_UNCONFIRMED and timestamp of 0 to indicate a transaction and it's dependents should remain marked
// as unverified (not 0-conf safe)
- (NSArray *)setBlockHeight:(int32_t)height
andTimestamp:(NSTimeInterval)timestamp
forTransactionHashes:(NSArray *)txHashes;
//add an account to the wallet
- (void)addAccount:(DSAccount *)account;
// returns an account where all derivation paths have the following account number
- (DSAccount *_Nullable)accountWithNumber:(NSUInteger)accountNumber;
// returns the first account with a balance
- (DSAccount *_Nullable)firstAccountWithBalance;
// returns an account to which the given transaction is or can be associated with (even if it hasn't been registered), no account if the transaction is not associated with the wallet
- (DSAccount *_Nullable)firstAccountThatCanContainTransaction:(DSTransaction *)transaction;
// returns all accounts to which the given transaction is or can be associated with (even if it hasn't been registered)
- (NSArray *)accountsThatCanContainTransaction:(DSTransaction *)transaction;
// returns an account to which the given transaction hash is associated with, no account if the transaction hash is not associated with the wallet
- (DSAccount *_Nullable)accountForTransactionHash:(UInt256)txHash transaction:(DSTransaction *_Nullable __autoreleasing *_Nullable)transaction;
// returns the transaction with the given hash if it's been registered in the wallet (might also return non-registered)
- (DSTransaction *_Nullable)transactionForHash:(UInt256)txHash;
- (NSArray *)registerAddressesWithGapLimit:(NSUInteger)gapLimit dashpayGapLimit:(NSUInteger)dashpayGapLimit internal:(BOOL)internal error:(NSError *_Nullable *_Nullable)error;
// returns the amount received by the wallet from the transaction (total outputs to change and/or receive addresses)
- (uint64_t)amountReceivedFromTransaction:(DSTransaction *)transaction;
// retuns the amount sent from the wallet by the trasaction (total wallet outputs consumed, change and fee included)
- (uint64_t)amountSentByTransaction:(DSTransaction *)transaction;
// true if no previous wallet transaction spends any of the given transaction's inputs, and no inputs are invalid
- (BOOL)transactionIsValid:(DSTransaction *)transaction;
// this is used to save transactions atomically with the block, needs to be called before switching threads to save the block
- (void)prepareForIncomingTransactionPersistenceForBlockSaveWithNumber:(uint32_t)blockNumber;
// this is used to save transactions atomically with the block
- (void)persistIncomingTransactionsAttributesForBlockSaveWithNumber:(uint32_t)blockNumber inContext:(NSManagedObjectContext *)context;
//returns the seed phrase after authenticating
- (void)seedPhraseAfterAuthentication:(void (^_Nullable)(NSString *_Nullable seedPhrase))completion;
- (void)seedPhraseAfterAuthenticationWithPrompt:(NSString *_Nullable)authprompt completion:(void (^_Nullable)(NSString *_Nullable seedPhrase))completion;
- (NSString *_Nullable)seedPhraseIfAuthenticated;
- (DSKey *_Nullable)privateKeyForAddress:(NSString *_Nonnull)address fromSeed:(NSData *_Nonnull)seed;
//generate a random Mnemonic seed
+ (NSString *_Nullable)generateRandomSeedPhrase;
//generate a random Mnemonic seed in a specified language
+ (NSString *_Nullable)generateRandomSeedPhraseForLanguage:(DSBIP39Language)language;
//This removes all blockchain information from the wallet, used for resync
- (void)wipeBlockchainInfoInContext:(NSManagedObjectContext *)context;
//This removes all wallet based information from the wallet, used when deletion of wallet is wanted
- (void)wipeWalletInfo;
//Recreate derivation paths and addresses
- (void)reloadDerivationPaths;
- (void)unregisterBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity;
- (void)addBlockchainIdentities:(NSArray<DSBlockchainIdentity *> *)blockchainIdentities;
- (void)addBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity;
//Verify makes sure the keys for the blockchain identity are good
- (BOOL)registerBlockchainIdentities:(NSArray<DSBlockchainIdentity *> *)blockchainIdentities verify:(BOOL)verify;
- (BOOL)registerBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity verify:(BOOL)verify;
- (BOOL)registerBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity;
- (BOOL)containsBlockchainIdentity:(DSBlockchainIdentity *)blockchainIdentity;
- (void)unregisterBlockchainInvitation:(DSBlockchainInvitation *)blockchainInvitation;
- (void)addBlockchainInvitation:(DSBlockchainInvitation *)blockchainInvitation;
- (void)registerBlockchainInvitation:(DSBlockchainInvitation *)blockchainInvitation;
- (BOOL)containsBlockchainInvitation:(DSBlockchainInvitation *)blockchainInvitation;
- (DSBlockchainIdentity *)createBlockchainIdentity;
- (DSBlockchainIdentity *)createBlockchainIdentityUsingDerivationIndex:(uint32_t)index;
- (DSBlockchainIdentity *)createBlockchainIdentityForUsername:(NSString *_Nullable)username;
- (DSBlockchainIdentity *)createBlockchainIdentityForUsername:(NSString *_Nullable)username usingDerivationIndex:(uint32_t)index;
- (DSBlockchainInvitation *)createBlockchainInvitation;
- (DSBlockchainInvitation *)createBlockchainInvitationUsingDerivationIndex:(uint32_t)index;
- (DSBlockchainIdentity *_Nullable)blockchainIdentityThatCreatedContract:(DPContract *)contract withContractId:(UInt256)contractId;
- (DSBlockchainIdentity *_Nullable)blockchainIdentityForUniqueId:(UInt256)uniqueId;
- (DSBlockchainInvitation *_Nullable)blockchainInvitationForUniqueId:(UInt256)uniqueId;
- (void)seedWithPrompt:(NSString *_Nullable)authprompt forAmount:(uint64_t)amount completion:(_Nullable SeedCompletionBlock)completion;
- (void)copyForChain:(DSChain *)chain completion:(void (^_Nonnull)(DSWallet *_Nullable copiedWallet))completion;
- (void)registerMasternodeOperator:(DSLocalMasternode *)masternode; //will use indexes
- (void)registerMasternodeOperator:(DSLocalMasternode *)masternode withOperatorPublicKey:(DSBLSKey *)operatorKey; //will use defined key
- (void)registerMasternodeOwner:(DSLocalMasternode *)masternode;
- (void)registerMasternodeOwner:(DSLocalMasternode *)masternode withOwnerPrivateKey:(DSECDSAKey *)ownerKey; //will use defined key
- (void)registerMasternodeVoter:(DSLocalMasternode *)masternode;
- (void)registerMasternodeVoter:(DSLocalMasternode *)masternode withVotingKey:(DSECDSAKey *)votingKey; //will use defined key
- (BOOL)containsProviderVotingAuthenticationHash:(UInt160)votingAuthenticationHash;
- (BOOL)containsProviderOwningAuthenticationHash:(UInt160)owningAuthenticationHash;
- (BOOL)containsProviderOperatorAuthenticationKey:(UInt384)providerOperatorAuthenticationKey;
- (BOOL)containsBlockchainIdentityBLSAuthenticationHash:(UInt160)blockchainIdentityAuthenticationHash;
- (BOOL)containsHoldingAddress:(NSString *)holdingAddress;
- (NSUInteger)indexOfProviderVotingAuthenticationHash:(UInt160)votingAuthenticationHash;
- (NSUInteger)indexOfProviderOwningAuthenticationHash:(UInt160)owningAuthenticationHash;
- (NSUInteger)indexOfProviderOperatorAuthenticationKey:(UInt384)providerOperatorAuthenticationKey;
- (NSUInteger)indexOfHoldingAddress:(NSString *)holdingAddress;
- (NSUInteger)indexOfBlockchainIdentityAuthenticationHash:(UInt160)blockchainIdentityAuthenticationHash;
- (NSUInteger)indexOfBlockchainIdentityCreditFundingRegistrationHash:(UInt160)creditFundingRegistrationHash;
- (NSUInteger)indexOfBlockchainIdentityCreditFundingTopupHash:(UInt160)creditFundingTopupHash;
- (NSUInteger)indexOfBlockchainIdentityCreditFundingInvitationHash:(UInt160)creditFundingInvitationHash;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Identity/DSBlockchainInvitation.h | <reponame>QuantumExplorer/dashsync-iOS<gh_stars>10-100
//
// Created by <NAME>
// Copyright © 2564 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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.
//
#import "DSBlockchainIdentity.h"
#import <Foundation/Foundation.h>
@class DSBlockchainIdentity, DSWallet, DSCreditFundingTransaction;
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXPORT NSString *const DSBlockchainInvitationDidUpdateNotification;
FOUNDATION_EXPORT NSString *const DSBlockchainInvitationKey;
FOUNDATION_EXPORT NSString *const DSBlockchainInvitationUpdateEvents;
FOUNDATION_EXPORT NSString *const DSBlockchainInvitationUpdateEventLink;
@interface DSBlockchainInvitation : NSObject
/*! @brief Initialized with an invitation link. The wallet must be on a chain that supports platform features.
*/
- (instancetype)initWithInvitationLink:(NSString *)invitationLink inWallet:(DSWallet *)wallet;
/*! @brief This is the identity that was made from the invitation. There should always be an identity associated to a blockchain invitation. This identity might not yet be registered on Dash Platform. */
@property (nonatomic, readonly) DSBlockchainIdentity *identity;
/*! @brief This is an invitation that was created locally. */
@property (nonatomic, readonly) BOOL createdLocally;
/*! @brief This is an invitation that was created with an external link, and has not yet retrieved the identity. */
@property (nonatomic, readonly) BOOL needsIdentityRetrieval;
/*! @brief This is the wallet holding the blockchain invitation. There should always be a wallet associated to a blockchain invitation. */
@property (nonatomic, weak, readonly) DSWallet *wallet;
/*! @brief Verifies the current invitation link in the invitation was created with a link. If the invitation is valid a transaction will be returned, as well as if the transaction has already been spent.
TODO:Spent currently does not work
*/
- (void)verifyInvitationLinkWithCompletion:(void (^_Nullable)(DSTransaction *transaction, bool spent, NSError *error))completion completionQueue:(dispatch_queue_t)completionQueue;
/*! @brief Verifies an invitation link. The chain must support platform features. If the invitation is valid a transaction will be returned, as well as if the transaction has already been spent.
TODO:Spent currently does not work
*/
+ (void)verifyInvitationLink:(NSString *)invitationLink onChain:(DSChain *)chain completion:(void (^_Nullable)(DSTransaction *transaction, bool spent, NSError *error))completion completionQueue:(dispatch_queue_t)completionQueue;
/*! @brief Registers the blockchain identity if the invitation was created with an invitation link. The blockchain identity is then associated with the invitation. */
- (void)acceptInvitationUsingWalletIndex:(uint32_t)index setDashpayUsername:(NSString *)dashpayUsername authenticationPrompt:(NSString *)authenticationMessage identityRegistrationSteps:(DSBlockchainIdentityRegistrationStep)identityRegistrationSteps stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion completionQueue:(dispatch_queue_t)completionQueue;
/*! @brief Generates blockchain invitations' extended public keys by asking the user to authentication with the prompt. */
- (void)generateBlockchainInvitationsExtendedPublicKeysWithPrompt:(NSString *)prompt completion:(void (^_Nullable)(BOOL registered))completion;
/*! @brief Register the blockchain identity to its wallet. This should only be done once on the creation of the blockchain identity.
*/
- (void)registerInWallet;
/*! @brief Unregister the blockchain identity from the wallet. This should only be used if the blockchain identity is not yet registered or if a progressive wallet wipe is happening.
@discussion When a blockchain identity is registered on the network it is automatically retrieved from the L1 chain on resync. If a client wallet wishes to change their default blockchain identity in a wallet it should be done by marking the default blockchain identity index in the wallet. Clients should not try to delete a registered blockchain identity from a wallet.
*/
- (BOOL)unregisterLocally;
/*! @brief Register the blockchain invitation to its wallet from a credit funding registration transaction. This should only be done once on the creation of the blockchain invitation.
@param fundingTransaction The funding transaction used to initially fund the blockchain identity.
*/
- (void)registerInWalletForRegistrationFundingTransaction:(DSCreditFundingTransaction *)fundingTransaction;
/*! @brief Create the invitation full link and mark the "fromIdentity" as the source of the invitation.
@param identity The source of the invitation.
*/
- (void)createInvitationFullLinkFromIdentity:(DSBlockchainIdentity *)identity completion:(void (^_Nullable)(BOOL cancelled, NSString *invitationFullLink))completion;
@end
NS_ASSUME_NONNULL_END
|
QuantumExplorer/dashsync-iOS | DashSync/shared/Models/Masternode/DSMasternodeList.h | <reponame>QuantumExplorer/dashsync-iOS
//
// DSMasternodeList.h
// DashSync
//
// Created by <NAME> on 5/20/19.
//
#import "BigIntTypes.h"
#import "DSQuorumEntry.h"
#import <Foundation/Foundation.h>
#define MASTERNODE_LIST_ADDED_NODES @"MASTERNODE_LIST_ADDED_NODES"
#define MASTERNODE_LIST_ADDED_VALIDITY @"MASTERNODE_LIST_ADDED_VALIDITY"
#define MASTERNODE_LIST_REMOVED_VALIDITY @"MASTERNODE_LIST_REMOVED_VALIDITY"
#define MASTERNODE_LIST_REMOVED_NODES @"MASTERNODE_LIST_REMOVED_NODES"
NS_ASSUME_NONNULL_BEGIN
@class DSSimplifiedMasternodeEntry, DSChain, DSQuorumEntry, DSPeer;
@interface DSMasternodeList : NSObject
@property (nonatomic, readonly) NSArray<DSSimplifiedMasternodeEntry *> *simplifiedMasternodeEntries;
@property (nonatomic, readonly) NSArray<NSData *> *providerTxOrderedHashes;
@property (nonatomic, readonly) NSDictionary<NSNumber *, NSDictionary<NSData *, DSQuorumEntry *> *> *quorums;
@property (nonatomic, readonly) UInt256 blockHash;
@property (nonatomic, readonly) uint32_t height;
@property (nonatomic, readonly) NSTimeInterval approximateTimestamp;
@property (nonatomic, readonly) BOOL isInLast30Days;
@property (nonatomic, readonly) UInt256 masternodeMerkleRoot;
@property (nonatomic, readonly) UInt256 quorumMerkleRoot;
@property (nonatomic, readonly) NSUInteger quorumsCount;
@property (nonatomic, readonly) NSUInteger validQuorumsCount;
@property (nonatomic, readonly) uint64_t masternodeCount;
@property (nonatomic, readonly) uint64_t validMasternodeCount;
@property (nonatomic, readonly) DSChain *chain;
@property (nonatomic, readonly) NSArray *reversedRegistrationTransactionHashes;
@property (nonatomic, readonly) NSDictionary<NSData *, DSSimplifiedMasternodeEntry *> *simplifiedMasternodeListDictionaryByReversedRegistrationTransactionHash;
+ (instancetype)masternodeListWithSimplifiedMasternodeEntries:(NSArray<DSSimplifiedMasternodeEntry *> *)simplifiedMasternodeEntries quorumEntries:(NSArray<DSQuorumEntry *> *)quorumEntries atBlockHash:(UInt256)blockHash atBlockHeight:(uint32_t)blockHeight withMasternodeMerkleRootHash:(UInt256)masternodeMerkleRootHash withQuorumMerkleRootHash:(UInt256)quorumMerkleRootHash onChain:(DSChain *)chain;
+ (instancetype)masternodeListWithSimplifiedMasternodeEntriesDictionary:(NSDictionary<NSData *, DSSimplifiedMasternodeEntry *> *)simplifiedMasternodeEntries quorumEntriesDictionary:(NSDictionary<NSNumber *, NSDictionary<NSData *, DSQuorumEntry *> *> *)quorumEntries atBlockHash:(UInt256)blockHash atBlockHeight:(uint32_t)blockHeight withMasternodeMerkleRootHash:(UInt256)masternodeMerkleRootHash withQuorumMerkleRootHash:(UInt256)quorumMerkleRootHash onChain:(DSChain *)chain;
+ (instancetype)masternodeListAtBlockHash:(UInt256)blockHash atBlockHeight:(uint32_t)blockHeight fromBaseMasternodeList:(DSMasternodeList *)baseMasternodeList addedMasternodes:(NSDictionary *)addedMasternodes removedMasternodeHashes:(NSArray *)removedMasternodeHashes modifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums removedQuorumHashesByType:(NSDictionary *)removedQuorumHashesByType onChain:(DSChain *)chain;
- (NSDictionary<NSData *, id> *)scoreDictionaryForQuorumModifier:(UInt256)quorumModifier atBlockHeight:(uint32_t)blockHeight;
- (NSArray *)scoresForQuorumModifier:(UInt256)quorumModifier atBlockHeight:(uint32_t)blockHeight;
- (NSUInteger)validQuorumsCountOfType:(DSLLMQType)type;
- (NSDictionary *)quorumsOfType:(DSLLMQType)type;
- (NSUInteger)quorumsCountOfType:(DSLLMQType)type;
- (NSArray<DSSimplifiedMasternodeEntry *> *)validMasternodesForQuorumModifier:(UInt256)quorumModifier quorumCount:(NSUInteger)quorumCount;
- (NSArray<DSSimplifiedMasternodeEntry *> *)allMasternodesForQuorumModifier:(UInt256)quorumModifier quorumCount:(NSUInteger)quorumCount blockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSArray<DSSimplifiedMasternodeEntry *> *)validMasternodesForQuorumModifier:(UInt256)quorumModifier quorumCount:(NSUInteger)quorumCount blockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (BOOL)validateQuorumsWithMasternodeLists:(NSDictionary *)masternodeLists;
- (UInt256)calculateMasternodeMerkleRootWithBlockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSDictionary *)compare:(DSMasternodeList *)other;
- (NSDictionary *)compare:(DSMasternodeList *)other blockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSDictionary *)compareWithPrevious:(DSMasternodeList *)other;
- (NSDictionary *)compareWithPrevious:(DSMasternodeList *)other blockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSDictionary *)listOfChangedNodesComparedTo:(DSMasternodeList *)previous;
- (NSDictionary *)compare:(DSMasternodeList *)other usingOurString:(NSString *)ours usingTheirString:(NSString *)theirs blockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (DSQuorumEntry *_Nullable)quorumEntryForInstantSendRequestID:(UInt256)requestID;
- (DSQuorumEntry *_Nullable)quorumEntryForChainLockRequestID:(UInt256)requestID;
- (NSArray<DSQuorumEntry *> *)quorumEntriesRankedForInstantSendRequestID:(UInt256)requestID;
- (NSArray<DSPeer *> *)peers:(uint32_t)peerCount withConnectivityNonce:(uint64_t)connectivityNonce;
- (UInt256)masternodeMerkleRootWithBlockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSArray<NSData *> *)hashesForMerkleRootWithBlockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSDictionary<NSData *, NSData *> *)hashDictionaryForMerkleRootWithBlockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (NSDictionary *)toDictionaryUsingBlockHeightLookup:(uint32_t (^)(UInt256 blockHash))blockHeightLookup;
- (DSSimplifiedMasternodeEntry *)masternodeForRegistrationHash:(UInt256)registrationHash;
@end
NS_ASSUME_NONNULL_END
|
BoatData/pi_config | sources/imgkap.c | <reponame>BoatData/pi_config<gh_stars>1-10
/*
* This source is free writen by M'dJ at 17/05/2011
* Use open source FreeImage and gnu gcc
* Thank to freeimage, libsb and opencpn
*
* imgkap.c - Convert kap a file from/to a image file and kml to kap
* modified by nohal 2011-0812 - changed the format of CED/ED to YYYY-MM-DD
*/
#define VERS "1.11"
#include <stdint.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> /* for malloc() */
#include <string.h> /* for strncmp() */
#include <time.h> /* for date in kap */
#include <FreeImage.h>
/* color type and mask */
typedef union
{
RGBQUAD q;
uint32_t p;
} Color32;
#define RGBMASK 0x00FFFFFF
/* --- Copy this part in header for use imgkap functions in programs and define LIBIMGKAP*/
#define METTERS 0
#define FATHOMS 1
#define NORMAL 0
#define OLDKAP 1
#define COLOR_NONE 1
#define COLOR_IMG 2
#define COLOR_MAP 3
#define COLOR_KAP 4
#define FIF_KAP 1024
#define FIF_NO1 1025
#define FIF_TXT 1026
#define FIF_KML 1027
int imgtokap(int typein,char *filein, double lat0, double lon0, double lat1, double lon1, int optkap,int color,char *title, int units, char *sd,char *fileout);
int imgheadertokap(int typein,char *filein,int typeheader,int optkap,int color,char *title,char *fileheader,char *fileout);
int kaptoimg(int typein,char *filein,int typeheader,char *fileheader,int typeout,char *fileout,char *optionpal);
int findfiletype(char *file);
int writeimgkap(FILE *out,FIBITMAP **bitmap,int optkap,int colors,Color32 *pal,uint16_t widthin,uint16_t heightin,uint16_t widthout,uint16_t heightout);
int bsb_uncompress_row(int typein, FILE *in, uint8_t *buf_out, uint16_t bits_in,uint16_t bits_out,uint16_t width);
int bsb_compress_row(const uint8_t *buf_in, uint8_t *buf_out, uint16_t bits_out, uint16_t line, uint16_t widthin,uint16_t widthout);
/* --- End copy */
static const double WGSinvf = 298.257223563; /* WGS84 1/f */
static const double WGSexentrik = 0.081819; /* e = 1/WGSinvf; e = sqrt(2*e -e*e) ;*/
struct structlistoption
{
char const *name;
int val;
} ;
static struct structlistoption imagetype[] =
{
{"KAP",FIF_KAP},
{"NO1",FIF_NO1},
{"KML",FIF_KML},
{"TXT",FIF_TXT},
{NULL, FIF_UNKNOWN},
} ;
static struct structlistoption listoptcolor[] =
{
{"NONE",COLOR_NONE},
{"KAP",COLOR_KAP},
{"IMG",COLOR_IMG},
{"MAP",COLOR_MAP},
{NULL,COLOR_NONE}
} ;
int findoptlist(struct structlistoption *liste,char *name)
{
while (liste->name != NULL)
{
if (!strcasecmp(liste->name,name)) return liste->val;
liste++;
}
return liste->val;
}
int findfiletype(char *file)
{
char *s ;
s = file + strlen(file)-1;
while ((s > file) && (*s != '.')) s--;
s++;
return findoptlist(imagetype,s);
}
static double postod(double lat0, double lon0, double lat1, double lon1)
{
double x,v,w;
lat0 = lat0 * M_PI / 180.;
lat1 = lat1 * M_PI / 180.;
lon0 = lon0 * M_PI / 180.;
lon1 = lon1 * M_PI / 180.;
v = sin((lon0 - lon1)/2.0);
w = cos(lat0) * cos(lat1) * v * v;
x = sin((lat0 - lat1)/2.0);
return (180. * 60. / M_PI) * 2.0 * asinl(sqrtl(x*x + w));
}
static inline double lontox(double l)
{
return l*M_PI/180;
}
static inline double lattoy_WS84(double l)
{
double e = WGSexentrik;
double s = sinl(l*M_PI/180.0);
return log(tan(M_PI/4 + l * M_PI/360)*pow((1. - e * s)/(1. + e * s), e/2.));
}
/*------------------ Single Memory algorithm ------------------*/
#define MYBSIZE 1572880
typedef struct smymemory
{
struct smymemory *next;
uint32_t size;
} mymemory;
static mymemory *mymemoryfirst = 0;
static mymemory *mymemorycur = 0;
void * myalloc(int size)
{
void *s = NULL;
mymemory *mem = mymemorycur;
if (mem && ((mem->size + size) > MYBSIZE)) mem = 0;
if (!mem)
{
mem = (mymemory *)calloc(MYBSIZE,1);
if (mem == NULL) return 0;
mem->size = sizeof(mymemory);
if (mymemorycur) mymemorycur->next = mem;
mymemorycur = mem;
if (!mymemoryfirst) mymemoryfirst = mem;
}
s = ((int8_t *)mem + mem->size);
mem->size += size;
return s;
}
void myfree(void)
{
struct smymemory *mem, *next;
mem = mymemoryfirst;
while (mem)
{
next = mem->next;
free(mem);
mem = next;
}
mymemoryfirst = 0;
mymemorycur = 0;
}
/*------------------ Histogram algorithm ------------------*/
typedef struct
{
Color32 color;
uint32_t count;
int16_t num;
} helem;
typedef struct shistogram
{
Color32 color;
uint32_t count;
int16_t num;
int16_t used;
struct shistogram *child ;
} histogram;
#define HistIndex2(p,l) ((((p.q.rgbRed >> l) & 0x03) << 4) | (((p.q.rgbGreen >> l) & 0x03) << 2) | ((p.q.rgbBlue >> l) & 0x03) )
#define HistSize(l) (l?sizeof(histogram):sizeof(helem))
#define HistInc(h,l) (histogram *)(((char *)h)+HistSize(l))
#define HistIndex(h,p,l) (histogram *)((char *)h+HistSize(l)*HistIndex2(p,l))
static histogram *HistAddColor (histogram *h, Color32 pixel )
{
char level;
for (level=6;level>=0;level -=2)
{
h = HistIndex(h,pixel,level) ;
if (h->color.p == pixel.p) break;
if (!h->count && !h->num)
{
h->color.p = pixel.p;
break;
}
if (!h->child)
{
h->child = (histogram *)myalloc(HistSize(level)*64);
if (h->child == NULL) return 0;
}
h = h->child;
}
h->count++;
return h;
}
static int HistGetColorNum (histogram *h, Color32 pixel)
{
char level;
for (level=6;level>=0;level -=2)
{
/* 0 < index < 64 */
h = HistIndex(h,pixel,level) ;
if (h->color.p == pixel.p) break;
if (!level)
break; // erreur
if (!h->child) break;
h = h->child;
}
if (h->num < 0) return -1-h->num;
return h->num-1;
}
#define HistColorsCount(h) HistColorsCountLevel(h,6)
static int32_t HistColorsCountLevel (histogram *h,int level)
{
int i;
uint32_t count = 0;
for (i=0;i<64;i++)
{
if (h->count) count++;
if (level)
{
if(h->child) count += HistColorsCountLevel(h->child,level-2);
}
h = HistInc(h,level);
}
return count;
}
/*--------------- reduce begin -------------*/
typedef struct
{
histogram *h;
int32_t nbin;
int32_t nbout;
int32_t colorsin;
int32_t colorsout;
int nextcote;
int maxcote;
int limcote[8];
uint64_t count;
uint64_t red;
uint64_t green;
uint64_t blue;
} reduce;
static inline int HistDist(Color32 a, Color32 b)
{
int c,r;
c = a.q.rgbRed - b.q.rgbRed;
r = c*c;
c = a.q.rgbGreen - b.q.rgbGreen;
r += c*c;
c = a.q.rgbBlue - b.q.rgbBlue;
r += c*c;
return sqrt(r);
}
static int HistReduceDist(reduce *r, histogram *h, histogram *e, int cote, int level)
{
int i;
int used = 1;
int curcote;
int limcote = r->limcote[level];
for (i=0;i<64;i++)
{
if (h->count && !h->num)
{
curcote = HistDist((Color32)e->color,(Color32)h->color);
if (curcote <= cote)
{
uint64_t c;
c = h->count;
r->count += c;
r->red += c * (uint64_t)((Color32)h->color).q.rgbRed ;
r->green += c * (uint64_t)((Color32)h->color).q.rgbGreen;
r->blue += c * (uint64_t)((Color32)h->color).q.rgbBlue;
h->num = r->nbout;
h->count = 0;
r->nbin++;
}
else
{
if (r->nextcote > curcote)
r->nextcote = curcote;
used = 0;
}
}
if (level && h->child && !h->used)
{
limcote += cote ;
curcote = HistDist((Color32)e->color,(Color32)h->color);
if (curcote <= limcote)
h->used = HistReduceDist(r,h->child,e,cote,level-2);
if (!h->used)
{
if ((curcote > limcote) && (r->nextcote > limcote))
r->nextcote = curcote ;
used = 0;
}
limcote -= cote ;
}
h = HistInc(h,level);
}
return used;
}
static void HistReduceLevel(reduce *r, histogram *h, int level)
{
int i;
for (i=0;i<64;i++)
{
if (level && h->child && !h->used)
{
HistReduceLevel(r, h->child,level-2);
if (!r->colorsout) break;
}
if (h->count && !h->num)
{
int32_t cote = 0;
int32_t nbcolors;
int32_t curv;
r->count = r->red = r->green = r->blue = 0;
r->nbin = 0;
r->nextcote = 0;
r->nbout++;
cote = (int32_t)(pow((double)((1<<24)/(double)r->colorsout),1.0/3.0)/2); //-1;
r->maxcote = sqrt(3*cote*cote);
curv = 0;
nbcolors = (r->colorsin +r->colorsout -1)/r->colorsout;
while (r->nbin < nbcolors)
{
curv += nbcolors - r->nbin;
cote = (int32_t)(pow(curv,1.0/3.0)/2); // - 1;
cote = sqrt(3*cote*cote);
if (r->nextcote > cote)
cote = r->nextcote;
r->nextcote = r->maxcote+1;
if (cote >= r->maxcote)
break;
h->used = HistReduceDist(r,r->h,h,cote,6);
if (!r->count)
{
fprintf(stderr,"Erreur quantize\n");
return;
}
}
r->colorsin -= r->nbin;
r->colorsout--;
{
histogram *e;
Color32 pixel ;
uint64_t c,cc;
c = r->count; cc = c >> 1 ;
pixel.q.rgbRed = (uint8_t)((r->red + cc) / c);
pixel.q.rgbGreen = (uint8_t)((r->green + cc) / c);
pixel.q.rgbBlue = (uint8_t)((r->blue + cc) / c);
pixel.q.rgbReserved = 0;
e = HistAddColor(r->h,pixel);
e->count = r->count;
e->num = -r->nbout;
}
if (!r->colorsout) break;
}
h = HistInc(h,level);
}
}
static int HistReduce(histogram *h, int colorsin, int colorsout)
{
reduce r;
r.h = h;
r.nbout = 0;
if (!colorsout || !colorsin) return 0;
if (colorsout > 0x7FFF) colorsout = 0x7FFF;
if (colorsout > colorsin) colorsout = colorsin;
r.colorsin = colorsin;
r.colorsout = colorsout;
r.limcote[2] = sqrt(3*3*3) ;
r.limcote[4] = sqrt(3*15*15) ;
r.limcote[6] = sqrt(3*63*63) ;
HistReduceLevel(&r,h,6);
return r.nbout;
}
/*--------------- reduce end -------------*/
static int _HistGetList(histogram *h,helem **e,int nbcolors,char level)
{
int i;
int nb;
nb = 0;
for (i=0;i<64;i++)
{
if (h->count && (h->num < 0))
{
e[-1-h->num] = (helem *)h;
nb++;
}
if (level && h->child) nb += _HistGetList(h->child,e,nbcolors-nb,level-2);
if (nb > nbcolors)
return 0;
h = HistInc(h,level);
}
return nb;
}
static int HistGetPalette(uint8_t *colorskap,uint8_t *colors,Color32 *palette,histogram *h,int nbcolors, int nb, int optcolors, Color32 *imgpal,int maxpal)
{
int i,j;
helem *t,*e[128];
uint8_t numpal[128];
/* get colors used */
if ((i= _HistGetList(h,e,nbcolors,6)) != nbcolors)
return 0;
/* load all color in final palette */
memset(numpal,0,sizeof(numpal));
if (!imgpal)
{
for (i=0;i<nbcolors;i++)
{
if (!(palette[i].q.rgbReserved & 1)) palette[i].p = e[i]->color.p;
palette[i].q.rgbReserved |= 1;
colors[i] = i;
numpal[i] = i;
}
palette->q.rgbReserved |= 8;
maxpal = nbcolors;
}
else
{
for (i=maxpal-1;i>=0;i--)
{
j = HistGetColorNum(h,imgpal[i]);
if (j>=0)
{
if (!(palette[i].q.rgbReserved & 1))
palette[i].p = imgpal[i].p;
palette[i].q.rgbReserved |= 1;
numpal[j] = i;
colors[i] = j;
}
}
palette->q.rgbReserved |= 8;
}
/* sort palette desc count */
for (i=0;i<nbcolors;i++)
{
for (j=i+1;j<nbcolors;j++)
if (e[j]->count > e[i]->count)
{
t = e[i];
e[i] = e[j];
e[j] = t;
}
}
/* if palkap 0 put first in last */
if (nb)
{
nb=1;
t = e[0];
e[0] = e[nbcolors-1];
e[nbcolors-1] = t;
}
/* get kap palette colors */
colorskap[0] = 0;
for (i=0;i<nbcolors;i++)
colorskap[i+nb] = numpal[-1-e[i]->num];
/* get num colors in kap palette */
for (i=0;i<maxpal;i++)
{
for (j=0;j<nbcolors;j++)
if (colors[i] == (-1 - e[j]->num))
break;
colors[i] = j+nb;
}
/* taitement img && map sur colorskap */
if ((optcolors == COLOR_IMG) || (optcolors == COLOR_MAP))
{
for(i=0;i<maxpal;i++)
{
palette[256+i].q.rgbRed = palette[i].q.rgbRed ;
palette[256+i].q.rgbGreen = palette[i].q.rgbGreen ;
palette[256+i].q.rgbBlue = palette[i].q.rgbBlue ;
palette[512+i].q.rgbRed = (palette[i].q.rgbRed)/2 ;
palette[512+i].q.rgbGreen = (palette[i].q.rgbGreen)/2 ;
palette[512+i].q.rgbBlue = (palette[i].q.rgbBlue)/2 ;
palette[768+i].q.rgbRed = (palette[i].q.rgbRed)/4 ;
palette[768+i].q.rgbGreen = (palette[i].q.rgbGreen)/4 ;
palette[768+i].q.rgbBlue = (palette[i].q.rgbBlue)/4 ;
palette[768+i].q.rgbReserved = palette[512+i].q.rgbReserved = palette[256+i].q.rgbReserved = palette[i].q.rgbReserved ;
}
if ((optcolors == COLOR_MAP) && (nbcolors < 64))
{
Color32 *p = palette+768;
for(i=0;i<maxpal;i++)
{
if ((p->q.rgbRed <= 4) && (p->q.rgbGreen <= 4) && (p->q.rgbBlue <= 4))
p->q.rgbRed = p->q.rgbGreen = p->q.rgbBlue = 55;
if ((p->q.rgbRed >= 60) && (p->q.rgbGreen >= 60) && (p->q.rgbBlue >= 60))
p->q.rgbRed = p->q.rgbGreen = p->q.rgbBlue = 0;
p++;
}
}
}
/*
for (i=0;i<nbcolors;i++)
{
printf("eorder %d rgb %d %d %d\n",i,e[i]->color.q.rgbRed,e[i]->color.q.rgbGreen,e[i]->color.q.rgbBlue);
}
for (i=0;i<maxpal;i++)
{
printf("palette %d rgb %d %d %d\n",i,palette[i].q.rgbRed,palette[i].q.rgbGreen,palette[i].q.rgbBlue);
}
for (i=0;i<nbcolors+nb;i++)
{
j = colorskap[i];
printf("palkap %d rgb %d %d %d\n",i,palette[j].q.rgbRed,palette[j].q.rgbGreen,palette[j].q.rgbBlue);
}
for (i=0;i<maxpal;i++)
{
printf("indexcol %i colors : %d\n",i,colors[i]);
}
*/
nbcolors += nb;
return nbcolors;
}
#define HistFree(h) myfree()
/*------------------ End of Histogram ------------------*/
typedef struct shsv
{
double hue;
double sat;
double val;
} HSV;
/* read in kap file */
//* si size < 0 lit jusqu'a \n (elimine \r) et convertie NO1 int r = (c - 9) & 0xFF; */
static inline int fgetkapc(int typein, FILE *in)
{
int c;
c = getc(in);
if (typein == FIF_NO1) return (c - 9) & 0xff;
return c;
}
static int fgetkaps(char *s, int size, FILE *in, int typein)
{
int i,c;
i = 0;
while (((c = getc(in)) != EOF) && size)
{
if (typein == FIF_NO1) c = (c - 9) & 0xff ;
if (size > 0)
{
s[i++] = (char)c ;
size--;
continue;
}
if (c == '\r') continue;
if (c == '\n')
{
s[i] = 0;
size++;
break;
}
s[i++] = (char)c;
size++;
if (!c) break;
}
return i;
}
/* function read and write kap index */
static int bsb_write_index(FILE *fp, uint16_t height, uint32_t *index)
{
uint8_t l;
/* Write index table */
while (height--)
{
/* Indices must be written as big-endian */
l = (*index >> 24) & 0xff;
fputc(l, fp);
l = (*index >> 16) & 0xff;
fputc(l, fp);
l = (*index >> 8) & 0xff;
fputc(l, fp);
l = *index & 0xff;
fputc(l, fp);
index++;
}
return 1;
}
static uint32_t *bsb_read_index(int typein,FILE *in,uint16_t height)
{
uint32_t l,end;
uint32_t *index;
int i;
index = NULL;
fseek(in,-4,SEEK_END);
end = ftell(in);
l = ((uint32_t)fgetkapc(typein,in)<<24)+((uint32_t)fgetkapc(typein,in)<<16)+((uint32_t)fgetkapc(typein,in)<<8)+((uint32_t)fgetkapc(typein,in));
if (((end - l)/4) != height) return NULL;
index = (uint32_t *)malloc(height*sizeof(uint32_t));
if (index == NULL) return NULL;
fseek(in,l,SEEK_SET);
/* Read index table */
for (i=0; i < height; i++)
{
index[i] = ((uint32_t)fgetkapc(typein,in)<<24)+((uint32_t)fgetkapc(typein,in)<<16)+((uint32_t)fgetkapc(typein,in)<<8)+((uint32_t)fgetkapc(typein,in));
}
return index;
}
/* bsb compress number, not value 0 at first write */
static uint16_t bsb_compress_nb(uint8_t *p, uint16_t nb, uint8_t pixel, uint16_t max)
{
uint16_t count = 0;
if (nb > max)
{
count = bsb_compress_nb(p,nb>>7,pixel|0x80,max);
p[count++] = (nb & 0x7F) | (pixel & 0x80);
return count;
}
pixel |= nb ;
if (!pixel) p[count++] = 0x80;
p[count++] = pixel ;
return count;
}
/* write line bsb */
int bsb_compress_row(const uint8_t *buf_in, uint8_t *buf_out, uint16_t bits_out, uint16_t line, uint16_t widthin, uint16_t widthout)
{
uint16_t ibuf,run_length ;
uint16_t ipixelin,ipixelout,xout;
uint8_t last_pix;
uint16_t dec, max;
dec = 7-bits_out;
max = (1<<dec) -1;
/* write the line number */
ibuf = bsb_compress_nb(buf_out,line,0,0x7F);
ipixelin = ipixelout = 0;
while ( ipixelin < widthin )
{
last_pix = buf_in[ipixelin];
ipixelin++;
ipixelout++;
/* Count length of same pixel */
run_length = 0;
if (ipixelin == 1592)
ipixelin = 1592;
while ( (ipixelin < widthin) && (buf_in[ipixelin] == last_pix) )
{
ipixelin++;
ipixelout++;
run_length++;
}
/* Extend, like but faster (total time/2) than xout = round((double)ipixelin*widthout/widthin); */
xout = ((uint32_t)((ipixelin<<1)+1)*widthout)/((uint32_t)widthin<<1);
if (xout > ipixelout)
{
run_length += xout - ipixelout;
ipixelout = xout;
}
/* write pixel*/
ibuf += bsb_compress_nb(buf_out+ibuf,run_length,last_pix<<dec,max);
}
buf_out[ibuf++] = 0;
return ibuf;
}
/* bsb uncompress number */
static uint16_t bsb_uncompress_nb(int typein,FILE *in, uint8_t *pixel, uint8_t decin, uint8_t maxin)
{
uint8_t c;
uint16_t count;
c = fgetkapc(typein,in);
count = (c & 0x7f);
*pixel = count >> decin;
count &= maxin;
while (c & 0x80)
{
c = fgetkapc(typein,in);
count = (count << 7) + (c & 0x7f);
}
return count+1;
}
/* read line bsb */
int bsb_uncompress_row(int typein, FILE *in, uint8_t *buf_out, uint16_t bits_in,uint16_t bits_out, uint16_t width)
{
uint16_t count;
uint8_t pixel;
uint8_t decin, maxin;
uint16_t xout = 0;
decin = 7-bits_in;
maxin = (1<<decin) - 1;
/* read the line number */
count = bsb_uncompress_nb(typein, in,&pixel,0,0x7F);
/* no test count = line number */
switch (bits_out)
{
case 1:
while ( width )
{
count = bsb_uncompress_nb(typein,in,&pixel, decin,maxin);
if (count > width) count = width;
width -= count;
while (count)
{
buf_out[xout>>3] |= pixel<<(7-(xout&0x7));
xout++;
count--;
}
}
break;
case 4:
while ( width )
{
count = bsb_uncompress_nb(typein,in,&pixel, decin,maxin);
if (count > width) count = width;
width -= count;
while (count)
{
buf_out[xout>>1] |= pixel<<(4-((xout&1)<<2));
xout++;
count--;
}
}
break;
case 8:
while ( width )
{
count = bsb_uncompress_nb(typein,in,&pixel, decin,maxin);
if (count > width) count = width;
width -= count;
while (count)
{
*buf_out++ = pixel;
count--;
}
}
break;
}
/* read last byte (0) */
getc(in);
return 0;
}
static void read_line(uint8_t *in, uint16_t bits, int width, uint8_t *colors, histogram *hist, uint8_t *out)
{
int i;
uint8_t c = 0;
switch (bits)
{
case 1:
for (i=0;i<width;i++)
{
out[i] = colors[(in[i>>3] >> (7-(i & 0x7))) & 1];
}
return;
case 4:
for (i=0;i<width;i++)
{
c = in[i >> 1];
out[i++] = colors[(c>>4) & 0xF];
out[i] = colors[c & 0xF];
}
return;
case 8:
for (i=0;i<width;i++)
{
out[i] = colors[in[i]];
}
return;
case 24:
{
Color32 cur, last;
last.p = 0xFFFFFFFF;
for (i=0;i<width;i++)
{
cur.p = ( *(uint32_t *)in & RGBMASK);
if (last.p != cur.p)
{
c = colors[HistGetColorNum(hist, cur)];
last = cur;
}
out[i] = c;
in += 3;
}
}
}
}
static uint32_t GetHistogram(FIBITMAP *bitmap,uint32_t bits,uint16_t width,uint16_t height,Color32 *pal,histogram *hist)
{
uint32_t i,j;
Color32 cur;
uint8_t *line,k;
histogram *h = hist;
switch (bits)
{
case 1:
HistAddColor (hist, pal[0]);
h = HistAddColor (hist, pal[1]);
h->count++;
break;
case 4:
for (i=0;i<height;i++)
{
line = FreeImage_GetScanLine(bitmap, i);
cur.p = (width+1)>>1;
for (j=0;j<cur.p;j++)
{
k = (*line++)>>4;
if (h->color.p == pal[k].p)
{
h->count++;
continue;
}
h = HistAddColor (hist, pal[k]);
}
line = FreeImage_GetScanLine(bitmap, i);
cur.p = width >> 1;
for (j=0;j<cur.p;j++)
{
k = (*line++)&0x0F;
if (h->color.p == pal[k].p)
{
h->count++;
continue;
}
h = HistAddColor (hist, pal[k]);
}
}
break;
case 8:
for (i=0;i<height;i++)
{
line = FreeImage_GetScanLine(bitmap, i);
for (j=0;j<width;j++)
{
k = *line++ ;
if (h->color.p == pal[k].p)
{
h->count++;
continue;
}
h = HistAddColor (hist, pal[k]);
}
}
break;
case 24:
for (i=0;i<height;i++)
{
line = FreeImage_GetScanLine(bitmap, i);
for (j=0;j<width;j++)
{
cur.p = *(uint32_t *)(line) & RGBMASK;
line += 3;
if (h->color.p == cur.p)
{
h->count++;
continue;
}
h = HistAddColor (hist, cur);
}
}
break;
}
return HistColorsCount(hist);
}
static const char *colortype[] = {"RGB","DAY","DSK","NGT","NGR","GRY","PRC","PRG"};
int writeimgkap(FILE *out,FIBITMAP **bitmap,int optkap, int optcolors, Color32 *palette, uint16_t widthin,uint16_t heightin, uint16_t widthout, uint16_t heightout)
{
uint16_t i,cpt,len,cur,last;
int num_colors;
uint32_t *index;
uint8_t *buf_in,*buf_out;
int bits_in,bits_out;
uint8_t colorskap[128];
uint8_t colors[256];
histogram hist[64];
memset(hist,0,sizeof(hist));
memset(colors,0,sizeof(colors));
memset(colorskap,0,sizeof(colorskap));
bits_in = FreeImage_GetBPP(*bitmap);
/* make bitmap 24, accept only 1 4 8 24 bits */
if ((bits_in > 8) && (bits_in != 24))
{
FIBITMAP *bitmap24;
bitmap24 = FreeImage_ConvertTo24Bits(*bitmap);
if (bitmap24 == NULL)
{
fprintf(stderr,"ERROR - bitmap PPP is incorrect\n");
return 2;
}
FreeImage_Unload(*bitmap);
*bitmap = bitmap24;
bits_in = 24;
}
/* read histogram */
num_colors = GetHistogram(*bitmap,bits_in,widthin,heightin,(Color32 *)FreeImage_GetPalette(*bitmap),hist);
if (!num_colors)
{
fprintf(stderr,"ERROR - No Colors or bitmap bits %d\n",num_colors);
return 2;
}
/* reduce colors */
num_colors = HistReduce(hist,num_colors,(optkap == NORMAL)?128:127);
bits_out = ceil(log2(num_colors + ((optkap == NORMAL)?0:1)));
/* if possible do not use colors 0 */
len = ((1<<bits_out) > num_colors)?1:0;
if (optcolors != COLOR_KAP )
memset(palette,0,sizeof(Color32)*256*8);
/* sort palette with 0 blank and get index */
num_colors = HistGetPalette(colorskap,colors,palette,hist,num_colors,len,optcolors,(Color32 *)FreeImage_GetPalette(*bitmap),FreeImage_GetColorsUsed(*bitmap));
if (!num_colors)
{
fprintf(stderr,"ERROR - internal GetPalette\n");
return 2;
}
fputs("OST/1\r\n", out);
fprintf(out, "IFM/%d\r\n",bits_out);
/* Write RGB tags for colormap */
for (cpt=0;cpt<8;cpt++)
{
if (! palette[256*cpt].q.rgbReserved) continue;
for (i = len; i < num_colors; i++)
{
fprintf(out, "%s/%d,%d,%d,%d\r\n",
colortype[cpt],
i,
palette[256*cpt+colorskap[i]].q.rgbRed,
palette[256*cpt+colorskap[i]].q.rgbGreen,
palette[256*cpt+colorskap[i]].q.rgbBlue
);
}
}
fputc(0x1a, out);
fputc('\0', out);
fputc(bits_out, out);
buf_in = (uint8_t *)malloc((widthin + 4)/4*4);
/* max space bsb encoded line can take */
buf_out = (uint8_t *)malloc((widthout*2 + 8)/4*4);
index = (uint32_t *)malloc((heightout + 1) * sizeof(uint32_t));
if ((buf_in == NULL) || (buf_out == NULL) || (index == NULL))
{
fprintf(stderr,"ERROR - mem malloc\n");
return 2;
}
last = -1;
for (i = 0; i<heightout; i++)
{
/* Extend on height */
cur = round((double)i * heightin / heightout);
if (cur != last)
{
last = cur;
read_line(FreeImage_GetScanLine(*bitmap, heightin-cur-1), bits_in, widthin, colors, hist,buf_in);
}
/* Compress raster and write to BSB file */
len = bsb_compress_row(buf_in, buf_out, bits_out, i, widthin,widthout);
/* Record index table */
index[i] = ftell(out);
/* write data*/
fwrite(buf_out, len, 1, out);
}
free(buf_in);
free(buf_out);
HistFree(hist);
/* record start-of-index-table file tion in the index table */
index[heightout] = ftell(out);
bsb_write_index(out, heightout+1, index);
free(index);
return 0;
}
static int readkapheader(int typein,FILE *in,int typeout, FILE *out, char *date,char *title,int optcolor,int *widthout, int *heightout, double *rx, double *ry, int *depth, RGBQUAD *palette)
{
char *s;
int result = 0;
char line[1024];
/* lit l entete kap y compris RGB et l'écrit dans un fichier sauf RGB*/
*widthout = *heightout = 0;
if (depth != NULL) *depth = 0;
if (palette != NULL) memset(palette,0,sizeof(RGBQUAD)*128);
while (fgetkaps(line,-1024,in,typein) > 0)
{
if (line[0] == 0x1a)
break;
if ((s = strstr(line, "RA=")))
{
unsigned x0, y0;
/* Attempt to read old-style NOS (4 parameter) version of RA= */
/* then fall back to newer 2-argument version */
if ((sscanf(s,"RA=%d,%d,%d,%d",&x0,&y0,widthout,heightout)!=4) &&
(sscanf(s,"RA=%d,%d", widthout, heightout) != 2))
{
result = 1;
break;
}
}
if (palette != NULL)
{
int index,r,g,b;
RGBQUAD *p = NULL;
if (sscanf(line, "RGB/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette;
if (sscanf(line, "DAY/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256;
if (sscanf(line, "DSK/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*2;
if (sscanf(line, "NGT/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*3;
if (sscanf(line, "NGR/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*4;
if (sscanf(line, "GRY/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*5;
if (sscanf(line, "PRC/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*6;
if (sscanf(line, "PRG/%d,%d,%d,%d", &index, &r, &g, &b) == 4) p = palette+256*7;
if (p != NULL)
{
if ((unsigned)index > 127)
{
result = 2;
break;
}
p[0].rgbReserved |= 8;
p[index].rgbReserved |= 1;
p[index].rgbRed = r;
p[index].rgbGreen = g;
p[index].rgbBlue = b;
}
}
if (depth != NULL) sscanf(line, "IFM/%d", depth);
if ( (rx != NULL) && (s = strstr(line, "DX=")) ) sscanf(s, "DX=%lf", rx);
if ( (ry != NULL) && (s = strstr(line, "DY=")) ) sscanf(s, "DY=%lf", ry);
if ((out != NULL) && (typeout != FIF_UNKNOWN))
{
if (typeout != FIF_TXT)
{
if (!strncmp(line,"RGB/",4)) continue;
if (!strncmp(line,"DAY/",4)) continue;
if (!strncmp(line,"DSK/",4)) continue;
if (!strncmp(line,"NGT/",4)) continue;
if (!strncmp(line,"NGR/",4)) continue;
if (!strncmp(line,"GRY/",4)) continue;
if (!strncmp(line,"PRC/",4)) continue;
if (!strncmp(line,"PRG/",4)) continue;
}
if ((*line == '!') && strstr(line,"M'dJ")) continue;
if ((*line == '!') && strstr(line,"imgkap")) continue;
if (!strncmp(line,"VER/",4) && ((optcolor == COLOR_IMG) || (optcolor == COLOR_MAP)))
{
fprintf(out,"VER/3.0\r\n");
continue;
}
if (!strncmp(line,"OST/",4)) continue;
if (!strncmp(line,"IFM/",4)) continue;
if ((s = strstr(line, "ED=")) && (date != NULL))
{
*s = 0;
while (*s && (*s != ',')) s++;
fprintf(out,"%sED=%s%s\r\n",line,date,s);
continue;
}
if ((s = strstr(line, "NA=")) && (title != NULL) && *title)
{
*s = 0;
while (*s && (*s != ',')) s++;
fprintf(out,"%sNA=%s%s\r\n",line,title,s);
continue;
}
fprintf(out,"%s\r\n",line);
}
}
return result;
}
int kaptoimg(int typein,char *filein,int typeheader,char *fileheader,int typeout, char *fileout, char *optionpal)
{
int result;
int cpt, width, height;
int bits_in,bits_out;
RGBQUAD palette[256*8];
RGBQUAD *bitmappal;
FIBITMAP *bitmap;
FILE *in, *header = NULL ;
header = NULL;
double rx,ry;
uint8_t *line = NULL;
uint32_t *index;
memset(palette,0,sizeof(palette));
if (optionpal && !strcasecmp(optionpal,"ALL") && (typeout != (int)FIF_TIFF) && (typeout != (int)FIF_GIF))
{
typeout = FIF_TIFF;
fprintf(stderr,"ERROR - Palette ALL accepted with only TIF or GIF %s\n",fileout);
return 2;
}
in = fopen(filein, "rb");
if (in == NULL)
{
fprintf(stderr,"ERROR - Can't open KAP file %s\n",filein);
return 2;
}
if (fileheader != NULL)
{
header = fopen(fileheader, "wb");
if (header == NULL)
{
fprintf(stderr,"ERROR - Can't create header KAP file %s\n",fileheader);
fclose(in);
return 2;
}
}
if (typeheader == FIF_KAP) typeheader = FIF_TXT;
result = readkapheader(typein,in,typeheader,header,NULL,NULL,COLOR_NONE,&width,&height,&rx,&ry,&bits_in,palette);
if (header != NULL) fclose(header);
if (result)
{
fprintf(stderr,"ERROR - Invalid Header file %s\n",fileheader);
fclose(in);
return result;
}
if ((fileout == NULL) || !*fileout) return 0;
bits_out = bits_in;
if (bits_in > 1)
{
if (bits_in > 4) bits_out = 8;
else bits_out = 4;
}
if ((typeout != (int)FIF_TIFF) && (typeout != (int)FIF_ICO) && (typeout != (int)FIF_PNG) && (typeout != (int)FIF_BMP))
bits_out = 8;
index = bsb_read_index(typein,in,height);
if (index == NULL)
{
fprintf(stderr,"ERROR - Invalid index table in %s\n",fileheader);
fclose(in);
return 3;
}
/* Create bitmap */
bitmap = FreeImage_AllocateEx(width, height, bits_out,palette,FI_COLOR_IS_RGB_COLOR,palette,0,0,0);
bitmappal = FreeImage_GetPalette(bitmap);
/* a revoir
FreeImage_SetDotsPerMeterX(bitmap,rx);
FreeImage_SetDotsPerMeterY(bitmap,ry);
*/
/* uncompress and write kap image into bitmap */
for (cpt=0;cpt<height;cpt++)
{
fseek(in,index[cpt],SEEK_SET);
line = FreeImage_GetScanLine(bitmap,height-cpt-1);
bsb_uncompress_row (typein,in,line,bits_in,bits_out,width);
}
free(index);
fclose(in);
cpt = 0;
if (optionpal)
{
cpt = -2;
if (!strcasecmp(optionpal,"ALL")) cpt = -1;
if (!strcasecmp(optionpal,"RGB")) cpt = 0;
if (!strcasecmp(optionpal,"DAY")) cpt = 1;
if (!strcasecmp(optionpal,"DSK")) cpt = 2;
if (!strcasecmp(optionpal,"NGT")) cpt = 3;
if (!strcasecmp(optionpal,"NGR")) cpt = 4;
if (!strcasecmp(optionpal,"GRY")) cpt = 5;
if (!strcasecmp(optionpal,"PRC")) cpt = 6;
if (!strcasecmp(optionpal,"PRG")) cpt = 7;
if (cpt == -2)
{
fprintf(stderr,"ERROR - Palette %s not exist in %s\n",optionpal,filein);
FreeImage_Unload(bitmap);
return 2;
}
}
if (cpt >= 0)
{
if (cpt > 0)
{
RGBQUAD *pal = palette + 256*cpt;
if (!pal->rgbReserved)
{
fprintf(stderr,"ERROR - Palette %s not exist in %s\n",optionpal,filein);
FreeImage_Unload(bitmap);
return 2;
}
for (result=0;result<256;result++) pal[result].rgbReserved = 0;
memcpy(bitmappal,pal,sizeof(RGBQUAD)*256);
}
result = FreeImage_Save((FREE_IMAGE_FORMAT)typeout,bitmap,fileout,0);
}
else
{
FIMULTIBITMAP *multi;
RGBQUAD *pal;
multi = FreeImage_OpenMultiBitmap((FREE_IMAGE_FORMAT)typeout,fileout,TRUE,FALSE,TRUE,0);
if (multi == NULL)
{
fprintf(stderr,"ERROR - Alloc multi bitmap\n");
FreeImage_Unload(bitmap);
return 2;
}
for (cpt=0;cpt<8;cpt++)
{
pal = palette + 256*cpt;
if (pal->rgbReserved)
{
for (result=0;result<256;result++) pal[result].rgbReserved = 0;
memcpy(bitmappal,pal,sizeof(RGBQUAD)*256);
FreeImage_AppendPage(multi,bitmap);
}
}
FreeImage_CloseMultiBitmap(multi,0);
result = 1;
}
FreeImage_Unload(bitmap);
return !result;
}
int imgheadertokap(int typein,char *filein,int typeheader, int optkap, int color, char *title, char *fileheader,char *fileout)
{
int widthin,heightin,widthout,heightout;
int bits_in,bits_out;
int result;
RGBQUAD palette[256*8];
FIBITMAP *bitmap = 0;
FILE *out;
FILE *header;
char datej[20];
memset(palette,0,sizeof(palette));
widthin = heightin = 0;
/* Read image file */
if (typein != FIF_KAP)
{
bitmap = FreeImage_Load((FREE_IMAGE_FORMAT)typein,filein,BMP_DEFAULT);
if (bitmap == NULL)
{
fprintf(stderr, "ERROR - Could not open or error in image file\"%s\"\n", filein);
return 2;
}
widthin = FreeImage_GetWidth(bitmap);
heightin = FreeImage_GetHeight(bitmap);
if (!widthin || !heightin)
{
fprintf(stderr, "ERROR - Invalid image size (width=%d,height=%d)\n", widthin, heightin);
FreeImage_Unload(bitmap);
return 2;
}
}
out = fopen(fileout, "wb");
if (out == NULL)
{
fprintf(stderr,"ERROR - Can't open KAP file %s\n",fileout);
if (bitmap) FreeImage_Unload(bitmap);
return 2;
}
/* Read date */
{
time_t t;
struct tm *date;
time(&t) ;
date = localtime(&t);
strftime(datej, sizeof(datej), "%Y-%m-%d",date);
}
header = fopen(fileheader, "rb");
if (header == NULL)
{
fprintf(stderr,"ERROR - Can't open Header file %s\n",fileheader);
if (bitmap) FreeImage_Unload(bitmap);
fclose(out);
return 2;
}
result = 1;
if ((typeheader == FIF_TXT) || (typeheader == FIF_KAP))
{
/* Header comment file outut */
char *s;
for (s=filein+strlen(filein)-1;s>filein;s--)
if ((*s == '\\') || (*s =='/'))
{
s++;
break;
}
fprintf(out,"! 2011 imgkap %s - at %s from %.35s\r\n", VERS,datej,s);
result = readkapheader(typeheader,header,FIF_KAP,out,datej,title,color, &widthout, &heightout,NULL,NULL,&bits_in,palette);
}
if (result)
{
fprintf(stderr,"ERROR - Invalid Header type %s\n",fileheader);
if (bitmap) FreeImage_Unload(bitmap);
fclose(header);
fclose(out);
return 2;
}
if (typein == FIF_KAP)
{
int cpt;
uint8_t *line = NULL;
uint32_t *index;
widthin = widthout;
heightin = heightout;
bits_out = bits_in;
if (bits_in > 1)
{
if (bits_in > 4) bits_out = 8;
else bits_out = 4;
}
index = bsb_read_index(typein,header,heightin);
if (index == NULL)
{
fprintf(stderr,"ERROR - Invalid index table in %s\n",fileheader);
fclose(header);
fclose(out);
return 3;
}
/* Create bitmap */
bitmap = FreeImage_AllocateEx(widthin, heightin, bits_out,palette,FI_COLOR_IS_RGB_COLOR,palette,0,0,0);
/* uncompress and write kap image into bitmap */
for (cpt=0;cpt<heightin;cpt++)
{
fseek(header,index[cpt],SEEK_SET);
line = FreeImage_GetScanLine(bitmap,heightin-cpt-1);
bsb_uncompress_row (typein,header,line,bits_in,bits_out,widthin);
}
free(index);
}
fclose(header);
if ((widthin > widthout) || (heightin > heightout))
{
fprintf(stderr, "ERROR - Image input is greater than outpout width=%d -> %d,height=%d -> %d \n", widthin,widthout, heightin,heightout);
FreeImage_Unload(bitmap);
fclose(out);
return 2;
}
if (((widthout*10/widthin) > 11) || ((heightout*10/heightin) > 11))
{
fprintf(stderr, "ERROR - Image input is too smaller than outpout width=%d -> %d,height=%d -> %d \n", widthin,widthout, heightin,heightout);
FreeImage_Unload(bitmap);
fclose(out);
return 2;
}
result = writeimgkap(out,&bitmap,optkap,color,(Color32 *)palette,widthin,heightin,widthout,heightout);
FreeImage_Unload(bitmap);
fclose(out);
return result;
}
int imgtokap(int typein,char *filein, double lat0, double lon0, double lat1, double lon1,int optkap, int color, char *title,int units, char *sd,char *fileout)
{
uint16_t dpi,widthout,heightout;
uint32_t widthin,heightin;
double scale;
double lx,ly,dx,dy ;
char datej[20];
int result;
const char *sunits;
FIBITMAP *bitmap;
FREE_IMAGE_TYPE type;
RGBQUAD palette[256*8];
FILE *out;
sunits = "METERS";
if (units != METTERS) sunits = "FATHOMS";
/* get latitude and longitude */
if (abs((int)lat0) > 85) return 1;
if (abs((int)lon0) > 180) return 1;
if (abs((int)lat1) > 85) return 1;
if (abs((int)lon1) > 180) return 1;
memset(palette,0,sizeof(palette));
/* Read image file */
bitmap = FreeImage_Load((FREE_IMAGE_FORMAT)typein,filein,BMP_DEFAULT);
if (bitmap == NULL)
{
fprintf(stderr, "ERROR - Could not open or error in image file\"%s\"\n", filein);
return 2;
}
type = FreeImage_GetImageType(bitmap);
if (type != FIT_BITMAP)
{
fprintf(stderr, "ERROR - Image is not a bitmap file\"%s\"\n", filein);
FreeImage_Unload(bitmap);
return 2;
}
widthin = FreeImage_GetWidth(bitmap);
heightin = FreeImage_GetHeight(bitmap);
if (!widthin || !heightin)
{
fprintf(stderr, "ERROR - Invalid image size (width=%d,height=%d)\n", widthin, heightin);
FreeImage_Unload(bitmap);
return 2;
}
out = fopen(fileout, "wb");
if (! out)
{
fprintf(stderr,"ERROR - Can't open KAP file %s\n",fileout);
FreeImage_Unload(bitmap);
return 2;
};
/* Header comment file outut */
/* Read date */
{
time_t t;
struct tm *date;
time(&t) ;
date = localtime(&t);
strftime(datej, sizeof(datej), "%d/%m/%Y",date);
}
/* Header comment file outut */
fprintf(out,"! 2011 imgkap %s file generator by M'dJ\r\n", VERS);
fprintf(out,"! Map generated not for navigation created at %s\r\n",datej);
/* calculate size */
dpi = 254;
lx = lontox(lon1)-lontox(lon0);
if (lx < 0) lx = -lx;
ly = lattoy_WS84(lat0)-lattoy_WS84(lat1);
if (ly < 0) ly = -ly;
/* calculate extend widthout heightout */
dx = heightin * lx / ly - widthin;
dy = widthin * ly / lx - heightin;
widthout = widthin ;
if (dy < 0) widthout = (int)round(widthin + dx) ;
heightout = (int)round(widthout * ly / lx) ;
fprintf(out,"! Extend widthin %d heightin %d to widthout %d heightout %d\r\n",
widthin,heightin,widthout,heightout);
scale = (1-(widthin/lx) / (heightin/ly)) *100;
if ((scale > 5) || (scale < -5))
{
fprintf(stderr,"ERROR - size of image is not correct\n");
fprintf(stderr,"\tExtend widthin %d heightin %d to widthout %d heightout %d\n",
widthin,heightin,widthout,heightout);
FreeImage_Unload(bitmap);
fclose(out);
return 2;
}
/* calculate resolution en size in meters */
dx = postod((lat0+lat1)/2,lon0,(lat0+lat1)/2,lon1);
dy = postod(lat0,lon0,lat1,lon0);
fprintf(out,"! Size in milles %.2f x %.2f\r\n",dx,dy) ;
scale = round(dy*18520000.0*dpi/(heightout*254));
if (units == METTERS)
{
dx = dx*1852.0/(double)widthout;
dy = dy*1852.0/(double)heightout;
}
else
{
dx = dx*1157500./((double)widthout*1143.);
dy = dy*1157500./((double)heightout*1143.);
}
fprintf(out,"! Resolution units %s - %.2fx%.2f -> %.0f at %d dpi\r\n", sunits, dx,dy,scale,dpi) ;
/* Write KAP header */
if (color == COLOR_NONE)
fputs("VER/2.0\r\n", out);
else
fputs("VER/3.0\r\n", out);
fprintf(out,"CED/SE=1,RE=1,ED=%s\r\n",datej);
/* write filename and date*/
{
char *s;
if (title == NULL)
{
s = fileout + strlen(fileout) -1;
while ((s > fileout) && (*s != '.')) s--;
if (s > fileout) *s = 0;
while ((s > fileout) && (*s != '\\') && (*s != '/')) s--;
if (s > fileout) s++;
title = s;
}
fprintf(out,"BSB/NA=%.70s\r\n",title);
}
fprintf(out," NU=UNKNOWN,RA=%d,%d,DU=%d\r\n",widthout,heightout,dpi);
fprintf(out,"KNP/SC=%0.f,GD=WGS 84,PR=MERCATOR,PP=%.2f\r\n", scale,0.0);
fputs(" PI=UNKNOWN,SP=UNKNOWN,SK=0.0,TA=90\r\n", out);
fprintf(out," UN=%s,SD=%s,DX=%.2f,DY=%.2f\r\n", sunits, sd,dx,dy);
fprintf(out,"REF/1,%u,%u,%f,%f\r\n",0,0,lat0,lon0);
fprintf(out,"REF/2,%u,%u,%f,%f\r\n",widthout-1,0,lat0,lon1);
fprintf(out,"REF/3,%u,%u,%f,%f\r\n",widthout-1,heightout-1,lat1,lon1);
fprintf(out,"REF/4,%u,%u,%f,%f\r\n",0,heightout-1,lat1,lon0);
fprintf(out,"PLY/1,%f,%f\r\n",lat0,lon0);
fprintf(out,"PLY/2,%f,%f\r\n",lat0,lon1);
fprintf(out,"PLY/3,%f,%f\r\n",lat1,lon1);
fprintf(out,"PLY/4,%f,%f\r\n",lat1,lon0);
fprintf(out,"DTM/%.6f,%.6f\r\n", 0.0, 0.0);
result = writeimgkap(out,&bitmap,optkap,color,(Color32 *)palette,widthin,heightin,widthout,heightout);
FreeImage_Unload(bitmap);
fclose(out);
return result;
}
typedef struct sxml
{
struct sxml *child;
struct sxml *next;
char tag[1];
} mxml;
static int mxmlreadtag(FILE *in, char *buftag)
{
int c;
int end = 0;
int endtag = 0;
int i = 0;
while ((c = getc(in)) != EOF)
if (strchr(" \t\r\n",c) == NULL) break;
if (c == EOF) return -1;
if (c == '<')
{
endtag = 1;
c = getc(in);
if (strchr("?!/",c) != NULL)
{
end = 1;
c = getc(in);
}
}
if (c == EOF) return -1;
do
{
if (endtag && (c == '>')) break;
else if (c == '<')
{
ungetc(c,in);
break;
}
buftag[i++] = c;
if (i > 1024)
return -1;
} while ((c = getc(in)) != EOF) ;
while ((i > 0) && (strchr(" \t\r\n",buftag[i-1]) != NULL)) i--;
buftag[i] = 0;
if (end) return 1;
if (endtag) return 2;
return 0;
}
static int mistag(char *tag, const char *s)
{
while (*s)
{
if (!*tag || (*s != *tag)) return 0;
s++;
tag++;
}
if (!*tag || (strchr(" \t\r\n",*tag) != NULL)) return 1;
return 0;
}
static mxml *mxmlread(FILE *in, mxml *parent, char *buftag)
{
int r;
mxml *x , *cur , *first;
x = cur = first = 0 ;
while ((r = mxmlreadtag(in,buftag)) >= 0)
{
if (parent && mistag(parent->tag,buftag)) return first;
x = (mxml *)myalloc(sizeof(mxml)+strlen(buftag)+1);
if (x == NULL)
{
fprintf(stderr,"ERROR - Intern malloc\n");
return first;
}
if (!first) first = x;
if (cur) cur->next = x;
cur = x;
x->child = 0;
x->next = 0;
strcpy(x->tag,buftag);
if (!r) break;
if (r > 1) x->child = mxmlread(in,x,buftag);
}
return first;
}
static mxml *mxmlfindtag(mxml *first,const char *tag)
{
while (first)
{
if (mistag(first->tag,tag)) break;
first = first->next;
}
return first;
}
#define mxmlfree(x) myfree()
static int readkml(char *filein,double *lat0, double *lon0, double *lat1, double *lon1, char *title)
{
int result;
mxml *kml,*ground,*cur;
FILE *in;
char *s;
char buftag[1024];
in = fopen(filein, "rb");
if (in == NULL)
{
fprintf(stderr,"ERROR - Can't open KML file %s\n",filein);
return 2;
}
if (*filein)
{
s = filein + strlen(filein) - 1;
while ((s >= filein) && (strchr("/\\",*s) == NULL)) s--;
s[1] = 0;
}
kml = mxmlread(in,0,buftag);
fclose(in);
if (kml == NULL)
{
fprintf(stderr,"ERROR - Not XML KML file %s\n",filein);
return 2;
}
ground = mxmlfindtag(kml,"kml");
result = 2;
while (ground)
{
ground = mxmlfindtag(ground->child,"GroundOverlay");
if (!ground || ground->next)
{
fprintf(stderr,"ERROR - KML no GroundOverlay or more one\n");
break;
}
cur = mxmlfindtag(ground->child,"name");
if (!cur || !cur->child)
{
fprintf(stderr,"ERROR - KML no Name\n");
break;
}
if (!*title)
strcpy(title,cur->child->tag);
cur = mxmlfindtag(ground->child,"Icon");
if (!cur || !cur->child)
{
fprintf(stderr,"ERROR - KML no Icon\n");
break;
}
cur = mxmlfindtag(cur->child,"href");
if (!cur || !cur->child)
{
fprintf(stderr,"ERROR - KML no href\n");
break;
}
strcat(filein,cur->child->tag);
#if (defined(_WIN32) || defined(__WIN32__))
s = filein + strlen(filein);
while (*s)
{
if (*s == '/') *s = '\\';
s++;
}
#endif
cur = mxmlfindtag(ground->child,"LatLonBox");
if (!cur || !cur->child)
{
fprintf(stderr,"ERROR - KML no LatLonBox\n");
break;
}
result = 3;
ground = cur->child;
cur = mxmlfindtag(ground,"rotation");
if (cur && cur->child)
{
*lat0 = strtod(cur->child->tag,&s);
if (*s || (*lat0 > 0.5))
{
result = 4;
fprintf(stderr,"ERROR - KML rotation is not accepted\n");
break;
}
}
cur = mxmlfindtag(ground,"north");
if (!cur || !cur->child) break;
*lat0 = strtod(cur->child->tag,&s);
if (*s) break;
cur = mxmlfindtag(ground,"south");
if (!cur || !cur->child) break;
*lat1 = strtod(cur->child->tag,&s);
if (*s) break;
cur = mxmlfindtag(ground,"west");
if (!cur || !cur->child) break;
*lon0 = strtod(cur->child->tag,&s);
if (*s) break;
cur = mxmlfindtag(ground,"east");
if (!cur || !cur->child) break;
*lon1 = strtod(cur->child->tag,&s);
if (*s) break;
result = 0;
break;
}
mxmlfree(kml);
if (result == 3) fprintf(stderr,"ERROR - KML no Lat Lon\n");
return result;
}
#ifndef LIBIMGKAP
inline double mystrtod(char *s, char **end)
{
double d = 0, r = 1;
while ((*s >= '0') && (*s <= '9')) {d = d*10 + (*s-'0'); s++;}
if ((*s == '.') || (*s == ','))
{
s++;
while ((*s >= '0') && (*s <= '9')) { r /= 10; d += r * (*s-'0'); s++;}
}
*end = s;
return d;
}
double strtopos(char *s, char **end)
{
int sign = 1;
double degree = 0;
double minute = 0;
double second = 0;
char c;
*end = s;
/* eliminate space */
while (*s == ' ') s++;
/* begin read sign */
c = toupper(*s);
if ((c == '-') || (c == 'O') || (c == 'W') || (c == 'S')) {s++;sign = -1;}
if ((c == '+') || (c == 'E') || (c == 'N')) s++;
/* eliminate space */
while (*s == ' ') s++;
/* error */
if (!*s) return 0;
/* read degree */
degree = mystrtod(s,&s);
/* eliminate space and degree */
while ((*s == ' ') || (*s == 'd') || (*s < 0)) s++;
/* read minute */
minute = mystrtod(s,&s);
/* eliminate space and minute separator */
while ((*s == ' ') || (*s == 'm') || (*s == 'n') || (*s == '\'')) s++;
/* read second */
second = mystrtod(s,&s);
/* eliminate space and second separator*/
while ((*s == ' ') || (*s == '\'') || (*s == '\"') || (*s == 's')) s++;
/* end read sign */
c = toupper(*s);
if ((c == '-') || (c == 'O') || (c == 'W') || (c == 'S')) {s++;sign = -1;}
if ((c == '+') || (c == 'E') || (c == 'N')) s++;
/* eliminate space */
while (*s == ' ') s++;
*end = s;
return sign * (degree + ((minute + (second/60.))/60.));
}
static void makefileout(char *fileout, const char *filein)
{
char *s;
strcpy(fileout,filein);
s = fileout + strlen(fileout)-1;
while ((s > fileout) && (*s != '.')) s--;
if (s > fileout) strcpy(s,".kap");
}
/* Main programme */
int main (int argc, char *argv[])
{
int result = 0;
char filein[1024];
char *fileheader = NULL;
char fileout[1024];
int typein, typeheader,typeout;
char *optionsd ;
int optionunits = METTERS;
int optionkap = NORMAL;
int optcolor;
char *optionpal ;
char optiontitle[256];
double lat0,lon0,lat1,lon1;
double l;
optionsd = (char *)"UNKNOWN" ;
optionpal = NULL;
typein = typeheader = typeout = FIF_UNKNOWN;
lat0 = lat1 = lon0 = lon1 = HUGE_VAL;
*filein = *fileout = *optiontitle = 0;
while (--argc)
{
argv++;
if (*argv == NULL) break;
if (((*argv)[0] == '-') && ((*argv)[2] == 0))
{
/* options */
char c = toupper((*argv)[1]);
if (c == 'N')
{
optionkap = OLDKAP;
continue;
}
if (c == 'F')
{
optionunits = FATHOMS;
continue;
}
if (c == 'S')
{
if (argc > 1) optionsd = argv[1];
argc--;
argv++;
continue;
}
if (c == 'T')
{
if (argc > 1) strcpy(optiontitle,argv[1]);
argc--;
argv++;
continue;
}
if (c == 'P')
{
if (argc > 1) optionpal = argv[1];
argc--;
argv++;
continue;
}
if ((c < '0') || (c > '9'))
{
result = 1;
break;
}
}
if (!*filein)
{
strcpy(filein,*argv);
continue;
}
if (fileheader == NULL)
{
char *s;
/* if numeric */
l = strtopos(*argv,&s);
if (!*s)
{
if (lat0 == HUGE_VAL)
{
lat0 = l;
continue;
}
if (lon0 == HUGE_VAL)
{
lon0 = l;
continue;
}
if (lat1 == HUGE_VAL)
{
lat1 = l;
continue;
}
if (lon1 == HUGE_VAL)
{
lon1 = l;
continue;
}
result = 1;
break;
}
fileheader = *argv;
continue;
}
if (!*fileout)
{
strcpy(fileout,*argv);
continue;
}
result = 1;
break;
}
if (!*filein) result = 1;
if (!result)
{
FreeImage_Initialise(0);
typein = findfiletype(filein);
if (typein == FIF_UNKNOWN) typein = (int)FreeImage_GetFileType(filein,0);
switch (typein)
{
case FIF_KML :
if (fileheader != NULL) strcpy(fileout,fileheader);
result = readkml(filein,&lat0,&lon0,&lat1,&lon1,optiontitle);
if (result) break;
if (!*fileout) makefileout(fileout,filein);
typein = (int)FreeImage_GetFileType(filein,0);
optcolor = COLOR_NONE;
if (optionpal) optcolor = findoptlist(listoptcolor,optionpal);
result = imgtokap(typein,filein,lat0,lon0,lat1,lon1,optionkap,optcolor,optiontitle,optionunits,optionsd,fileout);
break;
case FIF_KAP :
case FIF_NO1 :
if (fileheader == NULL)
{
result = 1;
break;
}
typeheader = findfiletype(fileheader);
if (typeheader == FIF_UNKNOWN)
{
if (*fileout)
{
result = 1;
break;
}
typeout = typeheader;
typeheader = FIF_UNKNOWN;
strcpy(fileout,fileheader);
fileheader = NULL;
}
if (*fileout)
{
typeout = FreeImage_GetFIFFromFilename(fileout);
if (typeout == FIF_UNKNOWN)
{
result = 1;
break;
}
}
if (!*fileout && (typeheader == FIF_KAP))
{
optcolor = COLOR_KAP;
if (optionpal) optcolor = findoptlist(listoptcolor,optionpal);
result = imgheadertokap(typein,filein,typein,optionkap,optcolor,optiontitle,filein,fileheader);
break;
}
result = kaptoimg(typein,filein,typeheader,fileheader,typeout,fileout,optionpal);
break;
case (int)FIF_UNKNOWN:
fprintf(stderr, "ERROR - Could not open or error in image file\"%s\"\n", filein);
result = 2;
break;
default:
if ((lon1 != HUGE_VAL) && (fileheader != NULL))
{
strcpy(fileout,fileheader);
fileheader = NULL;
}
optcolor = COLOR_NONE;
if (optionpal) optcolor = findoptlist(listoptcolor,optionpal);
if (!*fileout) makefileout(fileout,filein);
if (fileheader != NULL)
{
typeheader = findfiletype(fileheader);
result = imgheadertokap(typein,filein,typeheader,optionkap,optcolor,optiontitle,fileheader,fileout);
break;
}
if (lon1 == HUGE_VAL)
{
result = 1;
break;
}
result = imgtokap(typein,filein,lat0,lon0,lat1,lon1,optionkap,optcolor,optiontitle,optionunits,optionsd,fileout);
break;
}
FreeImage_DeInitialise();
}
// si kap et fileheader avec ou sans file out lire kap - > image ou header et image
// sinon lire image et header ou image et position -> kap
if (result == 1)
{
fprintf(stderr, "ERROR - Usage:\\imgkap [option] [inputfile] [lat0 lon0 lat1 lon1 | headerfile] [outputfile]\n");
fprintf(stderr, "\nimgkap Version %s by M'dJ\n",VERS);
fprintf(stderr, "\nConvert kap to img :\n");
fprintf(stderr, "\timgkap mykap.kap myimg.png : convert mykap into myimg.png\n" );
fprintf(stderr, "\timgkap mykap.kap mheader.kap myimg.png : convert mykap into header myheader (only text header kap file) and myimg.png\n" );
fprintf(stderr, "\nConvert img to kap : \n");
fprintf(stderr, "\timgkap myimg.png myheaderkap.kap : convert myimg.png into myimg.kap using myheader.kap for kap informations\n" );
fprintf(stderr, "\timgkap myimg.png myheaderkap.kap myresult.kap : convert myimg.png into myresult.kap using myheader.kap for kap informations\n" );
fprintf(stderr, "\timgkap mykap.png lat0 lon0 lat1 lon2 myresult.kap : convert myimg.png into myresult.kap using WGS84 positioning\n" );
fprintf(stderr, "\timgkap -s 'LOWEST LOW WATER' myimg.png lat0 lon0 lat1 lon2 -f : convert myimg.png into myimg.kap using WGS84 positioning and options\n" );
fprintf(stderr, "\nConvert kml to kap : \n");
fprintf(stderr, "\timgkap mykml.kml : convert GroundOverlay mykml file into kap file using name and directory of image\n" );
fprintf(stderr, "\timgkap mykml.kml mykap.kap: convert GroundOverlay mykml into mykap file\n" );
fprintf(stderr, "\nWGS84 positioning :\n");
fprintf(stderr, "\tlat0 lon0 is a left,top point\n");
fprintf(stderr, "\tlat1 lon1 is a right,bottom point\n");
fprintf(stderr, "\tlat to be beetwen -85 and +85 degree\n");
fprintf(stderr, "\tlon to be beetwen -180 and +180 degree\n");
fprintf(stderr, "\t different format are accepted : -1.22 1°10'20.123N -1d22.123 ...\n");
fprintf(stderr, "Options :\n");
fprintf(stderr, "\t-n : Force compatibilty all KAP software, max 127 colors\n" );
fprintf(stderr, "\t-f : fix units to FATHOMS\n" );
fprintf(stderr, "\t-s name : fix souding datum\n" );
fprintf(stderr, "\t-t title : change name of map\n" );
fprintf(stderr, "\t-p color : color of map\n" );
fprintf(stderr, "\t - Kap to image color : ALL|RGB|DAY|DSK|NGT|NGR|GRY|PRC|PRG\n" );
fprintf(stderr, "\t\t ALL generate multipage image, use only with GIF or TIF" );
fprintf(stderr, "\t - image or Kap to Kap color : NONE|KAP|MAP|IMG\n" );
fprintf(stderr, "\t\t NONE use colors in image file, default\n" );
fprintf(stderr, "\t\t KAP only width KAP or header file, use RGB tag in KAP file\n" );
fprintf(stderr, "\t\t MAP generate DSK and NGB colors for map scan (< 64 colors) Black -> Gray, White -> Black\n" );
fprintf(stderr, "\t\t IMG generate DSK and NGB colors for image (photo, satellite...)\n" );
return 1;
}
if (result) fprintf(stderr, "ERROR - imgkap return %d\n",result );
return result;
}
#endif
|
mrmotta/progetto-asd-2020-2021 | graphranker.c | <reponame>mrmotta/progetto-asd-2020-2021<filename>graphranker.c
// +---------------------------------------+
// | |
// | Progetto realizzato da <NAME> |
// | |
// +---------------------------------------+
#include <stdio.h>
#include <stdlib.h>
// Numero di grafi oltre cui controllare se i grafi sono messi in ordine decrescente
#define CONTROLLO_DECRESCENTE 16
// Definizione del tipo boolean
typedef enum {false, true} boolean;
// Struttura dati per la classifica e per i nodi dei grafi
typedef struct {
int identificativo;
unsigned long long int peso;
} nodo_t;
// Prototipi delle funzioni legate ad 'AggiungiGrafo'
void AggiungiGrafo (void);
void Inizializzazione (void);
void Dijkstra (void);
void MinMucchifica (unsigned int padre);
// Prototipi delle funzioni legate a 'TopK'
void TopK (void);
void MaxMucchifica (unsigned int padre);
void Inserimento (unsigned long long int peso);
// Funzioni per ordinare l'output del programma
#ifdef SORT
void Quicksort (int inizio, int fine);
int Partition (int inizio, int fine);
#endif
// Variabili globali di configurazione
boolean decrescente = false;
unsigned int lunghezzaClassifica = 0U;
unsigned int lunghezzaMassimaClassifica;
unsigned int lunghezzaMassimaClassificaCorrente;
unsigned int numeroGrafi = 0U;
unsigned int numeroNodi;
unsigned int numeroNodiDaProcessare;
unsigned int colonne;
unsigned int penultimaColonna;
// Puntatori ai vettori utilizzati
nodo_t *classifica;
nodo_t *nodiDaProcessare;
unsigned long long int *percorsiMinimi;
unsigned long int *matrice;
unsigned int *posizionePercorsiMinimi;
// Puntatore alla classifica per la stampa ordinata dei valori
#ifdef SORT
unsigned int *classificaOrdinata;
#endif
int main () {
char *indiceLettura;
char carattereLetto;
char numero[11];
// Configurazione dell'ambiente: lettura del numero di nodi
indiceLettura = numero;
carattereLetto = getchar_unlocked();
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != ' ');
*indiceLettura = '\0';
numeroNodi = atoi(numero);
// Configurazione dell'ambiente: lettura della lunghezza massima della classifica
indiceLettura = numero;
carattereLetto = getchar_unlocked();
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != '\n');
*indiceLettura = '\0';
lunghezzaMassimaClassifica = atoi(numero);
// Calcolo della lunghezza iniziale della classifica
if (lunghezzaMassimaClassifica <= 16U)
lunghezzaMassimaClassificaCorrente = lunghezzaMassimaClassifica;
else
if (lunghezzaMassimaClassifica > 16U)
lunghezzaMassimaClassificaCorrente = 16U;
// Inizializzazione di variabili ricorrenti e statiche
colonne = numeroNodi - 1;
penultimaColonna = colonne - 1;
// Creazione dei vettori utili durante il processo
classifica = malloc(sizeof(nodo_t) * lunghezzaMassimaClassificaCorrente);
nodiDaProcessare = malloc(sizeof(nodo_t) * colonne);
percorsiMinimi = malloc(sizeof(unsigned long long int) * colonne);
matrice = malloc(sizeof(unsigned long int) * colonne * colonne);
posizionePercorsiMinimi = malloc(sizeof(int) * colonne);
#ifdef SORT
classificaOrdinata = malloc(sizeof(unsigned int) * lunghezzaMassimaClassifica);
#endif
// Lettura ed esecuzione delle istruzioni
carattereLetto = getchar_unlocked();
do {
if (carattereLetto == 'A')
AggiungiGrafo();
else
TopK();
carattereLetto = getchar_unlocked();
} while (carattereLetto != EOF);
return 0;
}
void AggiungiGrafo () {
int indice = 0;
unsigned long long int pesoTotale = 0U;
if (decrescente) {
// Aggiornamento della lunghezza della classifica (se necessario)
if (lunghezzaClassifica < lunghezzaMassimaClassifica)
++ lunghezzaClassifica;
// Spostamento al prossimo comando da eseguire
for (int indice = 0; indice <= numeroNodi; ++ indice)
while (getchar_unlocked() != '\n');
} else {
// Inizializzazione dei vettori e calcolo del primo nodo da processare
Inizializzazione();
// Dijkstra, eseguito solo se parte almeno un arco dal nodo sorgente
if (nodiDaProcessare[0].peso != 0U) {
Dijkstra();
// Calcolo del peso totale del grafo
do {
pesoTotale += percorsiMinimi[indice];
++ indice;
} while (indice < colonne);
} else
pesoTotale = 0U;
// Aggiunta del nodo alla classifica
if (lunghezzaClassifica == lunghezzaMassimaClassifica) {
if (pesoTotale < classifica[0].peso) {
// Cancellazione del massimo
classifica[0] = classifica[-- lunghezzaClassifica];
MaxMucchifica(0);
// Inserimento del nodo
Inserimento(pesoTotale);
}
} else Inserimento(pesoTotale);
}
// Aggiornamento del numero di grafi letti fin'ora
++ numeroGrafi;
}
void Inizializzazione () {
int riga = 0;
int indiceMatrice = 0;
unsigned long int pesoArco;
char *indiceLettura;
char carattereLetto;
char numero[11];
numeroNodiDaProcessare = colonne;
// Inizializzazione vettore dei percorsi minimi
while (getchar_unlocked() != ',');
for (int indice = 0; indice < numeroNodiDaProcessare; ++ indice) {
// Lettura del numero
indiceLettura = numero;
carattereLetto = getchar_unlocked();
if (indice != penultimaColonna)
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != ',');
else
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != '\n');
*indiceLettura = '\0';
pesoArco = atol(numero);
// Inizializzazione dei vettori
percorsiMinimi[indice] = pesoArco;
nodiDaProcessare[indice].peso = pesoArco;
nodiDaProcessare[indice].identificativo = indice;
posizionePercorsiMinimi[indice] = indice;
}
// Costruzione del MinHeap dei nodi
for (int indice = (penultimaColonna - 1) / 2; indice >= 0; -- indice)
MinMucchifica(indice);
// Inizializzazione della matrice di adiacenza
do {
// Spostamento al primo nodo d'interesse
while (getchar_unlocked() != ',');
for (int colonna = 0; colonna < colonne; ++ colonna, ++ indiceMatrice) {
// Lettura del numero
indiceLettura = numero;
carattereLetto = getchar_unlocked();
if (colonna != penultimaColonna)
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != ',');
else
do {
*indiceLettura = carattereLetto;
++ indiceLettura;
carattereLetto = getchar_unlocked();
} while (carattereLetto != '\n');
*indiceLettura = '\0';
matrice[indiceMatrice] = atol(numero);
}
++ riga;
} while (riga < colonne);
}
void Dijkstra () {
nodo_t tmp;
unsigned int iniziale;
unsigned int corrente;
unsigned long int pesoArco;
do {
// Per ogni nodo ancora nella lista controllo se devo aggiornare il percorso minimo
for (int nodo = 1; nodo < numeroNodiDaProcessare; ++ nodo) {
iniziale = nodiDaProcessare[0].identificativo;
corrente = nodiDaProcessare[nodo].identificativo;
pesoArco = matrice[iniziale * colonne + corrente];
// Controllo se devo aggiornare il percorso minimo
if (pesoArco != 0 && (percorsiMinimi[corrente] == 0 || percorsiMinimi[iniziale] + pesoArco < percorsiMinimi[corrente])) {
percorsiMinimi[corrente] = percorsiMinimi[iniziale] + pesoArco;
// Decremento la priorità del nodo
nodiDaProcessare[posizionePercorsiMinimi[corrente]].peso = percorsiMinimi[corrente];
for (int indice = posizionePercorsiMinimi[corrente]; indice > 0 && (nodiDaProcessare[(indice - 1) / 2].peso > nodiDaProcessare[indice].peso || nodiDaProcessare[(indice - 1) / 2].peso == 0); indice = (indice - 1) / 2) {
// Aggiustamento delle posizioni
posizionePercorsiMinimi[nodiDaProcessare[indice].identificativo] = (indice - 1) / 2;
posizionePercorsiMinimi[nodiDaProcessare[(indice - 1) / 2].identificativo] = indice;
// Scambio dei valori
tmp = nodiDaProcessare[(indice - 1) / 2];
nodiDaProcessare[(indice - 1) / 2] = nodiDaProcessare[indice];
nodiDaProcessare[indice] = tmp;
}
}
}
// Cancellazione del minimo
nodiDaProcessare[0] = nodiDaProcessare[-- numeroNodiDaProcessare];
MinMucchifica(0);
} while (numeroNodiDaProcessare != 0 && nodiDaProcessare[0].peso != 0);
}
void MinMucchifica (unsigned int padre) {
nodo_t tmp;
unsigned int minimo = padre;
unsigned int sinistra = 2 * padre + 1;
unsigned int destra = 2 * padre + 2;
// Ricerca del massimo tra i figli
if (sinistra < numeroNodiDaProcessare && nodiDaProcessare[sinistra].peso != 0 && (nodiDaProcessare[sinistra].peso < nodiDaProcessare[minimo].peso || nodiDaProcessare[minimo].peso == 0))
minimo = sinistra;
if (destra < numeroNodiDaProcessare && nodiDaProcessare[destra].peso != 0 && (nodiDaProcessare[destra].peso < nodiDaProcessare[minimo].peso || nodiDaProcessare[minimo].peso == 0))
minimo = destra;
// Se non c'è nulla da scambiare ho finito
if (minimo == padre)
return;
// Aggiustamento delle posizioni
posizionePercorsiMinimi[nodiDaProcessare[padre].identificativo] = minimo;
posizionePercorsiMinimi[nodiDaProcessare[minimo].identificativo] = padre;
// Scambio dei valori
tmp = nodiDaProcessare[padre];
nodiDaProcessare[padre] = nodiDaProcessare[minimo];
nodiDaProcessare[minimo] = tmp;
// Chiamata ricorsiva per sistemare gli eventuali problemi
MinMucchifica(minimo);
}
void TopK () {
int indice = 0;
// Aggiustamento della posizione del cursore per evitare problemi
while (getchar_unlocked() != '\n');
// Stampa dei valori all'interno della classifica a seconda che i grafi siano in ordine decrescente o no
if (decrescente) {
if (numeroGrafi - lunghezzaClassifica > 0)
indice = numeroGrafi - lunghezzaClassifica;
while (indice < numeroGrafi - 1) {
printf("%d ", indice);
++ indice;
}
printf("%d\n", indice);
} else {
// Stampa senza ordinamento
#ifndef SORT
// Se la classifica è vuota stampa soltanto un '\n', altrimenti li stampa nell'ordine in cui sono nel vettore
if (lunghezzaClassifica != 0) {
do {
printf("%d ", classifica[indice].identificativo);
++ indice;
} while (indice < lunghezzaClassifica - 1);
printf("%d\n", classifica[lunghezzaClassifica - 1].identificativo);
} else
printf("\n");
#endif
// Stampa con ordinamento
#ifdef SORT
// Copia gli identificativi dei nodi in un nuovo vettore
do {
classificaOrdinata[indice] = classifica[indice].identificativo;
++ indice;
} while (indice < lunghezzaClassifica);
// Ordina questo nuovo vettore
Quicksort(0, lunghezzaClassifica - 1);
// Se la classifica è vuota stampa soltanto un '\n', altrimenti li stampa in ordine
if (lunghezzaClassifica != 0) {
indice = 0;
do {
printf("%d ", classificaOrdinata[indice]);
++ indice;
} while (indice < lunghezzaClassifica - 1);
printf("%d\n", classificaOrdinata[lunghezzaClassifica - 1]);
} else
printf("\n");
#endif
}
}
void MaxMucchifica (unsigned int padre) {
nodo_t tmp;
unsigned int massimo = padre;
unsigned int sinistra = 2 * padre + 1;
unsigned int destra = 2 * padre + 2;
// Ricerca del massimo tra i figli
if (sinistra < lunghezzaClassifica && classifica[sinistra].peso > classifica[padre].peso)
massimo = sinistra;
if (destra < lunghezzaClassifica && classifica[destra].peso > classifica[massimo].peso)
massimo = destra;
// Se non c'è nulla da scambiare ho finito
if (massimo == padre)
return;
// Scambio dei valori
tmp = classifica[padre];
classifica[padre] = classifica[massimo];
classifica[massimo] = tmp;
// Chiamata ricorsiva per sistemare gli eventuali problemi
MaxMucchifica(massimo);
}
void Inserimento (unsigned long long int peso) {
nodo_t tmp;
// Controllo se i grafi hanno peso decrescente, così da ottimizzare la classifica
if (numeroGrafi == CONTROLLO_DECRESCENTE) {
// Dico che è decrescente e vedo se è da smentire
decrescente = true;
for (int indice = 0; indice < lunghezzaClassifica - 1; ++ indice)
if (classifica[indice].identificativo > classifica[indice + 1].identificativo) {
decrescente = false;
return;
}
++ lunghezzaClassifica;
} else {
// Controlla che ci sia spazio, altrimenti rialloca
if (lunghezzaClassifica == lunghezzaMassimaClassificaCorrente) {
// Calcolo della lunghezza della nuova classifica
if (lunghezzaMassimaClassificaCorrente * 2 <= lunghezzaMassimaClassifica)
lunghezzaMassimaClassificaCorrente *= 2;
else
if (lunghezzaMassimaClassificaCorrente * 2 > lunghezzaMassimaClassifica)
lunghezzaMassimaClassificaCorrente = lunghezzaMassimaClassifica;
// Riallocazione dello spazio
classifica = realloc(classifica, sizeof(nodo_t) * lunghezzaMassimaClassificaCorrente);
}
// Inserimento del nuovo valore
classifica[lunghezzaClassifica].peso = peso;
classifica[lunghezzaClassifica].identificativo = numeroGrafi;
++ lunghezzaClassifica;
// Risoluzione degli eventuali problemi
for (int indice = lunghezzaClassifica-1; indice > 0 && classifica[(indice - 1) / 2].peso < classifica[indice].peso; indice = (indice - 1) / 2) {
tmp = classifica[(indice - 1) / 2];
classifica[(indice - 1) / 2] = classifica[indice];
classifica[indice] = tmp;
}
}
}
#ifdef SORT
// Implementazione del Quicksort
void Quicksort (int inizio, int fine) {
int pivot;
if (inizio < fine) {
pivot = Partition(inizio, fine);
Quicksort(inizio, pivot);
Quicksort(pivot + 1, fine);
}
}
// Schema di partizione di Hoare
int Partition (int inizio, int fine) {
unsigned int pivot = classificaOrdinata[(fine + inizio) / 2];
int indice1 = inizio - 1;
int indice2 = fine + 1;
unsigned int tmp;
while (true) {
do
++ indice1;
while (classificaOrdinata[indice1] < pivot);
do
-- indice2;
while (classificaOrdinata[indice2] > pivot);
if (indice1 < indice2) {
tmp = classificaOrdinata[indice1];
classificaOrdinata[indice1] = classificaOrdinata[indice2];
classificaOrdinata[indice2] = tmp;
} else
return indice2;
}
}
#endif
|
rkrajnc/hdr-plus | src/finish.h | #ifndef HDRPLUS_FINISH_H_
#define HDRPLUS_FINISH_H_
#include "Halide.h"
struct WhiteBalance {
float r;
float g0;
float g1;
float b;
};
typedef uint16_t BlackPoint;
typedef uint16_t WhitePoint;
typedef float Compression;
typedef float Gain;
/*
* finish -- Applies a series of standard local and global image processing
* operations to an input mosaicked image, producing a pleasant color output.
* Input pecifies black-level, white-level and white balance. Additionally,
* tone mapping is applied to the image, as specified by the input compression
* and gain amounts. This produces natural-looking brightened shadows, without
* blowing out highlights. The output values are 8-bit.
*/
Halide::Func finish(Halide::Func input, int width, int height, const BlackPoint bp, const WhitePoint wp, const WhiteBalance &wb, const Compression c, const Gain g);
#endif |
rkrajnc/hdr-plus | src/align.h | #ifndef HDRPLUS_ALIGN_H_
#define HDRPLUS_ALIGN_H_
#define T_SIZE 32 // Size of a tile in the bayer mosaiced image
#define T_SIZE_2 16 // Half of T_SIZE and the size of a tile throughout the alignment pyramid
#define MIN_OFFSET -168 // Min total alignment (based on three levels and downsampling by 4)
#define MAX_OFFSET 126 // Max total alignment. Differs from MIN_OFFSET because total search range is 8 for better vectorization
#define DOWNSAMPLE_RATE 4 // Rate at which layers of the alignment pyramid are downsampled relative to each other
#include "Halide.h"
/*
* prev_tile -- Returns an index to the nearest tile in the previous level of the pyramid.
*/
inline Halide::Expr prev_tile(Halide::Expr t) { return (t - 1) / DOWNSAMPLE_RATE; }
/*
* tile_0 -- Returns the upper (for y input) or left (for x input) tile that an image
* index touches.
*/
inline Halide::Expr tile_0(Halide::Expr e) { return e / T_SIZE_2 - 1; }
/*
* tile_1 -- Returns the lower (for y input) or right (for x input) tile that an image
* index touches.
*/
inline Halide::Expr tile_1(Halide::Expr e) { return e / T_SIZE_2; }
/*
* idx_0 -- Returns the inner index into the upper (for y input) or left (for x input)
* tile that an image index touches.
*/
inline Halide::Expr idx_0(Halide::Expr e) { return e % T_SIZE_2 + T_SIZE_2; }
/*
* idx_1 -- Returns the inner index into the lower (for y input) or right (for x input)
* tile that an image index touches.
*/
inline Halide::Expr idx_1(Halide::Expr e) { return e % T_SIZE_2; }
/*
* idx_im -- Returns the image index given a tile and the inner index into the tile.
*/
inline Halide::Expr idx_im(Halide::Expr t, Halide::Expr i) { return t * T_SIZE_2 + i; }
/*
* idx_layer -- Returns the image index given a tile and the inner index into the tile.
*/
inline Halide::Expr idx_layer(Halide::Expr t, Halide::Expr i) { return t * T_SIZE_2 / 2 + i; }
/*
* align -- Aligns multiple raw RGGB frames of a scene in T_SIZE x T_SIZE tiles which overlap
* by T_SIZE_2 in each dimension. align(imgs)(tile_x, tile_y, n) is a point representing the x and y offset
* for a tile in layer n that most closely matches that tile in the reference (relative to the reference tile's location)
*/
Halide::Func align(const Halide::Image<uint16_t> imgs);
#endif |
kildevaeld/restler | Example/Pods/Target Support Files/Pods-Restler_Tests/Pods-Restler_Tests-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_Restler_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Restler_TestsVersionString[];
|
kildevaeld/restler | Example/Pods/Target Support Files/Restler/Restler-umbrella.h | <gh_stars>0
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double RestlerVersionNumber;
FOUNDATION_EXPORT const unsigned char RestlerVersionString[];
|
kildevaeld/restler | Example/Pods/Target Support Files/Pods-Restler_Example/Pods-Restler_Example-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_Restler_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Restler_ExampleVersionString[];
|
kildevaeld/restler | Example/Pods/Target Support Files/Promissum/Promissum-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double PromissumVersionNumber;
FOUNDATION_EXPORT const unsigned char PromissumVersionString[];
|
rontian/xLua | build/pbc/src/map.h | #ifndef PROTOBUF_C_MAP_H
#define PROTOBUF_C_MAP_H
#include "alloc.h"
struct map_ip;
struct map_si;
struct map_sp;
struct map_kv {
int id;
void *pointer;
};
struct map_si * _pbcM_si_new(struct map_kv * table, int size);
int _pbcM_si_query(struct map_si *map, const char *key, int *result);
void _pbcM_si_delete(struct map_si *map);
struct map_ip * _pbcM_ip_new(struct map_kv * table, int size);
struct map_ip * _pbcM_ip_combine(struct map_ip * a, struct map_ip * b);
void * _pbcM_ip_query(struct map_ip * map, int id);
void _pbcM_ip_delete(struct map_ip *map);
struct map_sp * _pbcM_sp_new(int max, struct heap *h);
void _pbcM_sp_insert(struct map_sp *map, const char *key, void * value);
void * _pbcM_sp_query(struct map_sp *map, const char *key);
void ** _pbcM_sp_query_insert(struct map_sp *map, const char *key);
void _pbcM_sp_delete(struct map_sp *map);
void _pbcM_sp_foreach(struct map_sp *map, void (*func)(void *p));
void _pbcM_sp_foreach_ud(struct map_sp *map, void (*func)(void *p, void *ud), void *ud);
void * _pbcM_sp_next(struct map_sp *map, const char ** key);
#endif
|
rontian/xLua | build/luasocket/luasocket_scripts.h |
/* luasocket_scripts.h.h */
#ifndef __LUA_MODULES_606BA1C00D116CA81B695C141D124DB7_H_
#define __LUA_MODULES_606BA1C00D116CA81B695C141D124DB7_H_
#if __cplusplus
extern "C" {
#endif
#include "lua.h"
void luaopen_luasocket_scripts(lua_State* L);
/*
int luaopen_lua_m_ltn12(lua_State* L);
int luaopen_lua_m_mime(lua_State* L);
int luaopen_lua_m_socket_ftp(lua_State* L);
int luaopen_lua_m_socket_headers(lua_State* L);
int luaopen_lua_m_socket_http(lua_State* L);
int luaopen_lua_m_socket_mbox(lua_State* L);
int luaopen_lua_m_socket_smtp(lua_State* L);
int luaopen_lua_m_socket_tp(lua_State* L);
int luaopen_lua_m_socket_url(lua_State* L);
int luaopen_lua_m_socket(lua_State* L);
*/
#if __cplusplus
}
#endif
#endif /* __LUA_MODULES_606BA1C00D116CA81B695C141D124DB7_H_ */
|
rontian/xLua | build/pbc/test/readfile.h | <filename>build/pbc/test/readfile.h
#ifndef readfile_h
#define readfile_h
#include <stdio.h>
#include <stdlib.h>
static void
read_file (const char *filename , struct pbc_slice *slice) {
FILE *f = fopen(filename, "rb");
if (f == NULL) {
slice->buffer = NULL;
slice->len = 0;
return;
}
fseek(f,0,SEEK_END);
slice->len = ftell(f);
fseek(f,0,SEEK_SET);
slice->buffer = malloc(slice->len);
if (fread(slice->buffer, 1 , slice->len , f) == 0)
exit(1);
fclose(f);
}
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArMapObject.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
/* \file ArMapObject.h
* \brief Contains the definition of the ArMapObject class.
* \date 06/27/08
* \author <NAME>
*/
#ifndef ARMAPOBJECT_H
#define ARMAPOBJECT_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
/// A point or region of interest in an Aria map.
/**
* ArMapObject contains the data related to an Aria map object, i.e a point or
* region of interest in an Aria map that is not part of the sensed obstacle
* data. Examples of map objects include goals, docks, forbidden lines, and
* forbidden areas. Applications may define their own custom ArMapObject types
* using the ArMap MapInfo mechanism. See @ref ArMap for more information.
*
* The basic attributes of an ArMapObject include the type of the map object,
* an optional name of the object, and its position information. As mentioned
* above, there are two basic categories of ArMapObjects:
*
* - Points: A single ArPose in the map. By convention, if a map object
* can have an optional heading, then "WithHeading" appears at the end of
* the object type when the heading is specified. For example, "Goal"
* designates an (x,y) location in the map (any heading or theta value should
* be ignored) and "GoalWithHeading" designates
* an (x,y,th) location.
*
* - Regions: A set of two ArPoses ("from" and "to") which define a rectangle
* or a line. Rectangles may have an associated rotation value. It is the
* rotation to be applied to the "from" and "to" poses <em> around
* the global origin </em>. To retrieve the list of line segments that
* comprise the rotated rectangle's perimeter, use the getFromToSegments()
* method.
*
* Note that the ArMapObject is generally immutable. If an object needs to be
* changed, then the original version should simply be replaced with a new one.
* See ArMap::getMapObjects(), ArMap::setMapObjects(), and ArMap::mapChanged().
*
**/
class ArMapObject
{
public:
/// Creates a new ArMapObject whose attributes are as specified in the given arguments
/**
* @param arg the ArArgumentBuilder * from which to create the ArMapObject; this
* should correspond to a parsed line in the ArMap file
* @return ArMapObject * the newly created map object, or NULL if an error
* occurred
**/
AREXPORT static ArMapObject *createMapObject(ArArgumentBuilder *arg);
/// ArArgumentBuilder indices for the various map object attributes
enum ArgIndex {
TYPE_ARG_INDEX = 0,
POSE_X_ARG_INDEX = 1,
POSE_Y_ARG_INDEX = 2,
TH_ARG_INDEX = 3,
DESC_ARG_INDEX = 4,
ICON_ARG_INDEX = 5,
NAME_ARG_INDEX = 6,
LAST_POSE_ARG_INDEX = NAME_ARG_INDEX,
FROM_X_ARG_INDEX = 7,
FROM_Y_ARG_INDEX = 8,
TO_X_ARG_INDEX = 9,
TO_Y_ARG_INDEX = 10,
LAST_ARG_INDEX = TO_Y_ARG_INDEX
};
enum {
ARG_INDEX_COUNT = LAST_ARG_INDEX + 1
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Instance Methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/// Constructor
/**
* @param type the char * type of the map object (e.g. "Goal", "ForbiddenLine");
* must be non-empty
* @param pose the primary ArPose of the map object; for points, this is its
* location; for rectangles, this specifies the rotation of the rectangle (in
* pose.getTh())
* @param description an optional char * description of the object.
* @param iconName char * currently unused: use "ICON" or NULL as a dummy value. Must
* be a non-empty, non-whitespace string.
* @param name the char * name of the map object; depending on the object type,
* this may be optional or required
* @param hasFromTo a bool set to true if the object is a region (i.e. line or
* rectangle); false if the object is a point
* @param fromPose the ArPose that defines the start point of the region object;
* applicable only when hasFromTo is true
* @param toPose the ArPose that defines the end point of the region object;
* applicable only when hasFromTo is true
**/
AREXPORT ArMapObject(const char *type,
ArPose pose,
const char *description,
const char *iconName,
const char *name,
bool hasFromTo,
ArPose fromPose,
ArPose toPose);
/// Copy constructor
AREXPORT ArMapObject(const ArMapObject &mapObject);
/// Assignment operator
AREXPORT ArMapObject &operator=(const ArMapObject &mapObject);
/// Destructor
AREXPORT virtual ~ArMapObject();
// --------------------------------------------------------------------------
// Text Attributes:
// --------------------------------------------------------------------------
/// Returns the type of the map object
AREXPORT const char *getType(void) const;
/// Returns the "base" (or root) type of the map object
/**
* If the map object type ends with "WithHeading", then the base is the
* corresponding heading-less type. For example, "GoalWithHeading" has a
* base type of "Goal".
*
* If the map object type does not end with "WithHeading", then the base
* is the same as the type.
**/
AREXPORT const char *getBaseType(void) const;
/// Returns the name of the map object (if any)
AREXPORT const char *getName(void) const;
/// Returns the optional description of the map object
AREXPORT const char *getDescription() const ;
/// Returns the icon string of the object
/**
* The use of the ICON field is application-dependent. It currently contains
* either the string "ICON" or "ID=<n>". The ID is used only when auto-numbering
* has been turned on in the MapInfo.
**/
AREXPORT const char *getIconName(void) const;
/// Returns the numerical identifier of the object, when auto-numbering is on.
/**
* This method returns 0 when auto-numbering is off.
**/
AREXPORT int getId() const;
/// Sets the description of the map object
/**
* This method really should only be called immediately after the object
* is created, and before it is added to the map. (Since the map object
* isn't intended to be mutable.) It exists for backwards compatibility.
**/
AREXPORT void setDescription(const char *description);
// --------------------------------------------------------------------------
// Position Attributes:
// --------------------------------------------------------------------------
/// Returns the primary pose of the object
/**
* For points, this is the map object's location; for rectangles, this
* specifies the rotation of the rectangle (in getPose().getTh())
**/
AREXPORT ArPose getPose(void) const;
/// Returns true if the map object has valid "from/to" poses (i.e. is a line or rectangle)
AREXPORT bool hasFromTo(void) const;
/// Returns the "from" pose for lines and rectangles; valid only if hasFromTo()
AREXPORT ArPose getFromPose(void) const;
/// Returns the "to" pose for lines and rectangles; valid only if hasFromTo()
AREXPORT ArPose getToPose(void) const;
void setPose(ArPose p) { myPose = p; }
AREXPORT void setFromTo(ArPose from, ArPose to);
/// Returns the optional rotation of a rectangle; or 0 if none
/**
* Note that this function doesn't know whether it actually makes sense
* for this map object to have the rotation. (For example, it makes sense
* on a ForbiddenArea but not a ForbiddenLine.)
*
**/
AREXPORT double getFromToRotation(void) const;
/// Gets a list of fromTo line segments that have been rotated
/**
* Note that this function doesn't know whether it actually makes sense
* for this map object to have the rotation. (For example, it makes sense
* on a ForbiddenArea but not a ForbiddenLine.) This is just here so
* that everyone doesn't have to do the same calculation. Note that
* this might be a little more CPU/Memory intensive transfering
* these around, so you may want to keep a copy of them if you're
* using them a lot (but make sure you clear the copy if the map
* changes). It may not make much difference on a modern processor
* though (its set up this way for safety).
**/
AREXPORT std::list<ArLineSegment> getFromToSegments(void);
/// Gets a line segment that goes from the from to the to
/**
* Note that this function doesn't know whether this is supposed to
* be a rectangle or a line. (For example, it makes sense on a
* ForbiddenLine but not a ForbiddenAra.) This is just here to
* store it. Note that this might be a little more CPU/Memory
* intensive transfering these around, so you may want to keep a
* copy of them if you're using them a lot (but make sure you clear
* the copy if the map changes). It may not make much difference on
* a modern processor though (its set up this way for safety).
**/
AREXPORT ArLineSegment getFromToSegment(void);
/// Computes the center pose of the map object.
/**
* This method determines the center of map objects that have a "from" and a
* "to" pose (i.e. lines and rectangles). For map objects that are poses,
* this method simply returns the pose.
**/
AREXPORT ArPose findCenter(void) const;
/** Return true if the given point is inside the region of this object,
* assuming that this object is a region or sector. False if not.
*/
bool isPointInside(const ArPose& p) const {
if(!hasFromTo()) return false;
const std::vector<ArPose> v = getRegionVertices();
if(v.size() > 2)
return p.isInsidePolygon(v);
else
return false;
}
/** If this object is a region or sector type, return a std::vector containing
* the position (in global map coordinate frame) of each corner. I.e. taking
* object rotation into account, find each corner. If this object is not a
* region or sector (i.e. does not have "from" and "to" corners), then
* an empty std::vector is returned. The "Theta" components of the vertex
* ArPose objects is not set or used.
*/
AREXPORT std::vector<ArPose> getRegionVertices() const;
// --------------------------------------------------------------------------
// I/O Methods
// --------------------------------------------------------------------------
/// Returns the text representation of the map object
/**
* The returned string is suitable for writing to the ArMap file. Note that
* the string does NOT include the map object's optional parameters.
**/
AREXPORT const char *toString() const;
/// Returns the text representation of the map object
/**
* This method is equivalent to toString();
**/
const char *getStringRepresentation() const {
return toString();
}
/// Writes the map object to the ArLog.
/**
* @param intro an optional string that should appear before the object
**/
AREXPORT void log(const char *intro = NULL) const;
// --------------------------------------------------------------------------
// Miscellaneous Methods
// --------------------------------------------------------------------------
/// Less than operator (for sets), orders by position
AREXPORT bool operator<(const ArMapObject& other) const;
/// Gets the fileName of the object (probably never used for maps)
/**
* This method is maintained solely for backwards compatibility.
* It now returns the same value as getDescription (i.e. any file names
* that may have been associated with an object can now be found in the
* description attribute).
* @deprecated
**/
AREXPORT const char *getFileName(void) const;
private:
/// Parses the given arguments and sets the description of the given ArMapObject
static bool setObjectDescription(ArMapObject *object,
ArArgumentBuilder *arg);
protected:
/// The type of the map object
std::string myType;
/// If non-empty, then myType ends with "WithHeading" and this is the "root"
std::string myBaseType;
/// The name of the map object, if any
std::string myName;
/// The description of the map object
std::string myDescription;
/// For pose objects, THE pose; For rectangle objects, contains the optional rotation
ArPose myPose;
/// Reserved for future use
std::string myIconName;
/// Whether the map object is a region (line or rect) with "from/to" poses
bool myHasFromTo;
/// The "from" pose of a region map object; valid only if myHasFromTo is true
ArPose myFromPose;
/// The "to" pose of a region map object; valid only if myHasFromTo is true
ArPose myToPose;
/// For rectangle objects, the line segments that comprise the perimeter (even if rotated)
std::list<ArLineSegment> myFromToSegments;
/// For line objects, the line
ArLineSegment myFromToSegment;
/// Text representation written to the map file
mutable std::string myStringRepresentation;
}; // end class ArMapObject
// =============================================================================
#ifndef SWIG
/// Comparator for two pointers to map objects
/** @swigomit */
struct ArMapObjectCompare :
public std::binary_function<const ArMapObject *,
const ArMapObject *,
bool>
{
/// Returns true if obj1 is less than obj2; NULL pointers are greater than non-NULL
bool operator()(const ArMapObject *obj1,
const ArMapObject *obj2)
{
if ((obj1 != NULL) && (obj2 != NULL)) {
return *obj1 < *obj2;
}
else if ((obj1 == NULL) && (obj2 == NULL)) {
return false;
}
else {
return (obj1 == NULL);
}
} // end operator()
}; // end struct ArMapObjectCompare
#endif //ifndef SWIG
#endif // ARMAPOBJECT_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArSimulatedLaser.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSIMULATEDLASER_H
#define ARSIMULATEDLASER_H
#include "ariaTypedefs.h"
#include "ArLaser.h"
class ArRobot;
class ArRobotPacket;
/**
This class is a subclass of ArRangeDeviceThreaded meant for any
planar scanning lasers, like the SICK lasers, Hokoyo URG series
lasers, etc. Unlike most base classes this contains the superset
of everything that may need to be configured on any of the sensors,
this is so that the configuration and parameter files don't have to
deal with anything sensor specific.
To see the different things you can set on a laser, call the
functions canSetDegrees, canChooseRange, canSetIncrement,
canChooseIncrement, canChooseUnits, canChooseReflectorBits,
canSetPowerControlled, canChooseStartBaud, and canChooseAutoBaud to
see what is available (the help for each of those tells you what
functions they are associated with, and for each function
associated with one of those it tells you to see the associated
function).
@since 2.7.0
**/
class ArSimulatedLaser : public ArLaser
{
public:
/// Constructor
AREXPORT ArSimulatedLaser(ArLaser *laser);
/// Destructor
AREXPORT virtual ~ArSimulatedLaser();
AREXPORT virtual bool blockingConnect(void);
AREXPORT virtual bool asyncConnect(void);
AREXPORT virtual bool disconnect(void);
AREXPORT virtual bool isConnected(void)
{ return myIsConnected; }
AREXPORT virtual bool isTryingToConnect(void)
{
if (myStartConnect)
return true;
else if (myTryingToConnect)
return true;
else
return false;
}
protected:
AREXPORT virtual void * runThread(void *arg);
AREXPORT virtual bool laserCheckParams(void);
AREXPORT bool finishParams(void);
AREXPORT bool simPacketHandler(ArRobotPacket *packet);
ArLaser *myLaser;
double mySimBegin;
double mySimEnd;
double mySimIncrement;
// stuff for the sim packet
ArPose mySimPacketStart;
ArTransform mySimPacketTrans;
ArTransform mySimPacketEncoderTrans;
unsigned int mySimPacketCounter;
unsigned int myWhichReading;
unsigned int myTotalNumReadings;
bool myStartConnect;
bool myIsConnected;
bool myTryingToConnect;
bool myReceivedData;
std::list<ArSensorReading *>::iterator myIter;
// range buffers to hold current range set and assembling range set
std::list<ArSensorReading *> *myAssembleReadings;
std::list<ArSensorReading *> *myCurrentReadings;
ArRetFunctor1C<bool, ArSimulatedLaser, ArRobotPacket *> mySimPacketHandler;
};
#endif // ARSIMULATEDLASER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArLCDConnector.h | <filename>Aria/ArLCDConnector.h
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARLCDCONNECTOR_H
#define ARLCDCONNECTOR_H
#include "ariaTypedefs.h"
#include "ArSerialConnection.h"
#include "ArTcpConnection.h"
#include "ArArgumentBuilder.h"
#include "ArArgumentParser.h"
#include "ariaUtil.h"
#include "ArRobotConnector.h"
class ArLCDMTX;
class ArRobot;
/// Connect to robot and lcd based on run-time availablitily and command-line arguments
/**
ArLCDConnector makes a lcd connection either through a serial port
connection, or through a TCP
port (for the simulator or for robots with Ethernet-serial bridge
devices instead of onboard computers).
Normally, it first attempts a TCP connection on
@a localhost port 8101, to use a simulator if running. If the simulator
is not running, then it normally then connects using the serial port
Various connection
parameters are configurable through command-line arguments or in the robot
parameter file. (Though the internal interface used by ARIA to do this is also
available if you need to use it: See addLCD(); otherwise don't use
addLCD(), setupLCD(), etc.).
When you create your ArLCDConnector, pass it command line parameters via
either the argc and argv variables from main(), or pass it an
ArArgumentBuilder or ArArgumentParser object. (ArArgumentBuilder
is able to obtain command line parameters from a Windows program
that uses WinMain() instead of main()).
ArLCDConnector registers a callback with the global Aria class. Use
Aria::parseArgs() to parse all command line parameters to the program, and
Aria::logOptions() to print out information about all registered command-line parameters.
The following command-line arguments are checked:
@verbinclude ArLCDConnector_options
To connect to any lcds that were set up in the robot parameter file or
via command line arguments, call connectLCDs(). If successful,
connectLCDs() will return true and add an entry for each lcd connected
in the ArRobot object's list of lcds. These ArLCDMTX objects can be
accessed from your ArRobot object via ArRobot::findLCD() or ArRobot::getLCDMap().
@since 2.8.0
**/
class ArLCDConnector
{
public:
/// Constructor that takes argument parser
AREXPORT ArLCDConnector(
ArArgumentParser *parser,
ArRobot *robot, ArRobotConnector *robotConnector,
bool autoParseArgs = true,
ArLog::LogLevel infoLogLevel = ArLog::Verbose,
ArRetFunctor1<bool, const char *> *turnOnPowerOutputCB = NULL,
ArRetFunctor1<bool, const char *> *turnOffPowerOutputCB = NULL);
/// Destructor
AREXPORT ~ArLCDConnector(void);
/// Connects all the lcds the robot has that should be auto connected
AREXPORT bool connectLCDs(bool continueOnFailedConnect = false,
bool addConnectedLCDsToRobot = true,
bool addAllLCDsToRobot = false,
bool turnOnLCDs = true,
bool powerCycleLCDOnFailedConnect = true);
/// Sets up a lcd to be connected
AREXPORT bool setupLCD(ArLCDMTX *lcd,
int lcdNumber = 1);
/// Connects the lcd synchronously (will take up to a minute)
AREXPORT bool connectLCD(ArLCDMTX *lcd,
int lcdNumber = 1,
bool forceConnection = true);
/// Adds a lcd so parsing will get it
AREXPORT bool addLCD(ArLCDMTX *lcd,
int lcdNumber = 1);
/// Function to parse the arguments given in the constructor
AREXPORT bool parseArgs(void);
/// Function to parse the arguments given in an arbitrary parser
AREXPORT bool parseArgs(ArArgumentParser *parser);
/// Log the options the simple connector has
AREXPORT void logOptions(void) const;
/// Internal function to get the lcd (only useful between parseArgs and connectLCDs)
AREXPORT ArLCDMTX *getLCD(int lcdNumber);
/// Internal function to replace the lcd (only useful between parseArgs and connectLCDs) but not the lcd data
AREXPORT bool replaceLCD(ArLCDMTX *lcd, int lcdNumber);
AREXPORT void turnOnPowerCB (int);
AREXPORT void turnOffPowerCB (int);
AREXPORT void setIdentifier(const char *identifier);
protected:
/// Class that holds information about the lcd data
class LCDData
{
public:
LCDData (int number, ArLCDMTX *lcd) {
myNumber = number;
myLCD = lcd;
myConn = NULL;
myConnect = false; myConnectReallySet = false;
myPort = NULL;
myPortType = NULL;
myType = NULL;
myRemoteTcpPort = 0; myRemoteTcpPortReallySet = false;
myBaud = NULL;
myAutoConn = NULL;
myConnFailOption = NULL;
}
virtual ~LCDData() {}
/// The number of this lcd
int myNumber;
/// The actual pointer to this lcd
ArLCDMTX *myLCD;
// our connection
ArDeviceConnection *myConn;
// if we want to connect the lcd
bool myConnect;
// if myConnect was really set
bool myConnectReallySet;
// the port we want to connect the lcd on
const char *myPort;
// the type of port we want to connect to the lcd on
const char *myPortType;
// lcd Type
const char *myType;
// wheather to auto conn
const char *myAutoConn;
// wheather to disconnect on conn faiure
const char *myConnFailOption;
// lcd tcp port if we're doing a remote host
int myRemoteTcpPort;
// if our remote lcd tcp port was really set
bool myRemoteTcpPortReallySet;
/// the baud we want to use
const char *myBaud;
};
std::map<int, LCDData *> myLCDs;
/// Turns on the power for the specific board in the firmware
AREXPORT bool turnOnPower(LCDData *LCDData);
/// Turns off the power for the specific board in the firmware
AREXPORT bool turnOffPower(LCDData *LCDData);
/// Verifies the firmware version on the LCD and loads new firmware
/// if there is no match
AREXPORT bool verifyFirmware(LCDData *LCDData);
AREXPORT std::string searchForFile(
const char *dirToLookIn, const char *prefix, const char *suffix);
/// Parses the lcd arguments
AREXPORT bool parseLCDArgs(ArArgumentParser *parser,
LCDData *lcdData);
/// Logs the lcd command line option help text.
AREXPORT void logLCDOptions(LCDData *lcddata, bool header = true, bool metaOpts = true) const;
// Sets the lcd parameters
bool internalConfigureLCD(LCDData *lcdData);
std::string myLCDTypes;
// our parser
ArArgumentParser *myParser;
bool myOwnParser;
// if we should autoparse args or toss errors
bool myAutoParseArgs;
bool myParsedArgs;
ArRobot *myRobot;
ArRobotConnector *myRobotConnector;
// variables to hold if we're logging or not
bool myLCDLogPacketsReceived;
bool myLCDLogPacketsSent;
ArLog::LogLevel myInfoLogLevel;
ArRetFunctor1<bool, const char *> *myTurnOnPowerOutputCB;
ArRetFunctor1<bool, const char *> *myTurnOffPowerOutputCB;
ArRetFunctorC<bool, ArLCDConnector> myParseArgsCB;
ArConstFunctorC<ArLCDConnector> myLogOptionsCB;
ArFunctor1C<ArLCDConnector, int> myTurnOnPowerCB;
ArFunctor1C<ArLCDConnector, int> myTurnOffPowerCB;
};
#endif // ARLASERCONNECTOR_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ariaUtil.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARIAUTIL_H
#define ARIAUTIL_H
#define _GNU_SOURCE 1
#include <string>
// #define _XOPEN_SOURCE 500
#include <list>
#include <map>
#include <math.h>
#include <stdarg.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <float.h>
#include <vector>
#if defined(_WIN32) || defined(WIN32)
#include <sys/timeb.h>
#include <sys/stat.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <strings.h>
#endif // ifndef win32
#include <time.h>
#include "ariaTypedefs.h"
#include "ArLog.h"
#include "ArFunctor.h"
#include "ArArgumentParser.h"
//#include "ariaInternal.h"
#include "ariaOSDef.h"
class ArLaser;
class ArBatteryMTX;
class ArLCDMTX;
class ArSonarMTX;
class ArDeviceConnection;
#ifndef M_PI
#define M_PI 3.1415927
#endif // of M_PI, windows has a function call instead of a define
/// Contains various utility functions, including cross-platform wrappers around common system functions.
/** @ingroup UtilityClasses
@ingroup ImportantClasses
*/
class ArUtil
{
public:
/// Values for the bits from 0 to 16
enum BITS {
BIT0 = 0x1, ///< value of BIT0
BIT1 = 0x2, ///< value of BIT1
BIT2 = 0x4, ///< value of BIT2
BIT3 = 0x8, ///< value of BIT3
BIT4 = 0x10, ///< value of BIT4
BIT5 = 0x20, ///< value of BIT5
BIT6 = 0x40, ///< value of BIT6
BIT7 = 0x80, ///< value of BIT7
BIT8 = 0x100, ///< value of BIT8
BIT9 = 0x200, ///< value of BIT9
BIT10 = 0x400, ///< value of BIT10
BIT11 = 0x800, ///< value of BIT11
BIT12 = 0x1000, ///< value of BIT12
BIT13 = 0x2000, ///< value of BIT13
BIT14 = 0x4000, ///< value of BIT14
BIT15 = 0x8000, ///< value of BIT15
};
#ifdef WIN32
typedef int mode_t;
#endif
/// Sleep for the given number of milliseconds
/// @ingroup easy
AREXPORT static void sleep(unsigned int ms);
/// Get the time in milliseconds
AREXPORT static unsigned int getTime(void);
/// Delete all members of a set. Does NOT empty the set.
/**
Assumes that T is an iterator that supports the operator*, operator!=
and operator++. The return is assumed to be a pointer to a class that
needs to be deleted.
*/
template<class T> static void deleteSet(T begin, T end)
{
for (; begin != end; ++begin)
{
delete (*begin);
}
}
/// Delete all members of a set. Does NOT empty the set.
/**
Assumes that T is an iterator that supports the operator**, operator!=
and operator++. The return is assumed to be a pair. The second value of
the pair is assumed to be a pointer to a class that needs to be deleted.
*/
template<class T> static void deleteSetPairs(T begin, T end)
{
for (; begin != end; ++begin)
{
delete (*begin).second;
}
}
/// Returns the minimum of the two values
/// @ingroup easy
static int findMin(int first, int second)
{ if (first < second) return first; else return second; }
/// Returns the maximum of the two values
/// @ingroup easy
static int findMax(int first, int second)
{ if (first > second) return first; else return second; }
/// Returns the minimum of the two values
/// @ingroup easy
static unsigned int findMinU(unsigned int first, unsigned int second)
{ if (first < second) return first; else return second; }
/// Returns the maximum of the two values
/// @ingroup easy
static unsigned int findMaxU(unsigned int first, unsigned int second)
{ if (first > second) return first; else return second; }
/// Returns the minimum of the two values
/// @ingroup easy
static double findMin(double first, double second)
{ if (first < second) return first; else return second; }
/// Returns the maximum of the two values
/// @ingroup easy
static double findMax(double first, double second)
{ if (first > second) return first; else return second; }
/// OS-independent way of finding the size of a file.
AREXPORT static long sizeFile(const char *fileName);
/// OS-independent way of finding the size of a file.
AREXPORT static long sizeFile(std::string fileName);
/// OS-independent way of checking to see if a file exists and is readable.
AREXPORT static bool findFile(const char *fileName);
// OS-independent way of stripping the directory from the fileName.
// commented out with std::string changes since this didn't seem worth fixing right now
//AREXPORT static bool stripDir(std::string fileIn, std::string &fileOut);
// OS-independent way of stripping the fileName from the directory.
// commented out with std::string changes since this didn't seem worth fixing right now
//AREXPORT static bool stripFile(std::string fileIn, std::string &fileOut);
/// Appends a slash to a path if there is not one there already
AREXPORT static void appendSlash(char *path, size_t pathLength);
/// Appends a slash to the given string path if necessary.
AREXPORT static void appendSlash(std::string &path);
/// Fix the slash orientation in file path string for windows or linux
AREXPORT static void fixSlashes(char *path, size_t pathLength);
/// Fixes the slash orientation in the given file path string for the current platform
AREXPORT static void fixSlashes(std::string &path);
/// Fix the slash orientation in file path string to be all forward
AREXPORT static void fixSlashesForward(char *path, size_t pathLength);
/// Fix the slash orientation in file path string to be all backward
AREXPORT static void fixSlashesBackward(char *path, size_t pathLength);
/// Returns the slash (i.e. separator) character for the current platform
AREXPORT static char getSlash();
/// Adds two directories, taking care of all slash issues
AREXPORT static void addDirectories(char *dest, size_t destLength,
const char *baseDir,
const char *insideDir);
/// Finds out if two strings are equal
AREXPORT static int strcmp(const std::string &str, const std::string &str2);
/// Finds out if two strings are equal
AREXPORT static int strcmp(const std::string &str, const char *str2);
/// Finds out if two strings are equal
AREXPORT static int strcmp(const char *str, const std::string &str2);
/// Finds out if two strings are equal
AREXPORT static int strcmp(const char *str, const char *str2);
/// Finds out if two strings are equal (ignoring case)
AREXPORT static int strcasecmp(const std::string &str, const std::string &str2);
/// Finds out if two strings are equal (ignoring case)
AREXPORT static int strcasecmp(const std::string &str, const char *str2);
/// Finds out if two strings are equal (ignoring case)
AREXPORT static int strcasecmp(const char *str, const std::string &str2);
/// Finds out if two strings are equal (ignoring case)
AREXPORT static int strcasecmp(const char *str, const char *str2);
/// Finds out if a string has a suffix
AREXPORT static bool strSuffixCmp(const char *str, const char *suffix);
/// Finds out if a string has a suffix
AREXPORT static bool strSuffixCaseCmp(const char *str, const char *suffix);
/// Compares two strings (ignoring case and surrounding quotes)
/**
* This helper method is primarily used to ignore surrounding quotes
* when comparing ArArgumentBuilder args.
* @return int set to 0 if the two strings are equivalent, a negative
* number if str1 is "less than" str2, and a postive number if it is
* "greater than".
**/
AREXPORT static int strcasequotecmp(const std::string &str1,
const std::string &str2);
/// Puts a \ before spaces in src, puts it into dest
AREXPORT static void escapeSpaces(char *dest, const char *src,
size_t maxLen);
/// Strips out the quotes in the src buffer into the dest buffer
AREXPORT static bool stripQuotes(char *dest, const char *src,size_t destLen);
/// Strips the quotes from the given string.
AREXPORT static bool stripQuotes(std::string *strToStrip);
/// Fixes the bad characters in the given string.
AREXPORT static bool fixBadCharacters(std::string *strToFix,
bool removeSpaces, bool fixOtherWhiteSpace = true);
/// Lowers a string from src into dest, make sure there's enough space
AREXPORT static void lower(char *dest, const char *src,
size_t maxLen);
/// Returns true if this string is only alphanumeric (i.e. it contains only leters and numbers), false if it contains any non alphanumeric characters (punctuation, whitespace, control characters, etc.)
AREXPORT static bool isOnlyAlphaNumeric(const char *str);
/// Returns true if this string is only numeric (i.e. it contains only numeric
//digits), or it's null, or false if it contains any non nonnumeric characters (alphabetic, punctuation, whitespace, control characters, etc.)
AREXPORT static bool isOnlyNumeric(const char *str);
/// Returns true if the given string is null or of zero length, false otherwise
AREXPORT static bool isStrEmpty(const char *str);
/// Determines whether the given text is contained in the given list of strings.
AREXPORT static bool isStrInList(const char *str,
const std::list<std::string> &list,
bool isIgnoreCase = false);
/// Returns the floating point number from the string representation of that number in @a nptr, or HUGE_VAL for "inf" or -HUGE_VAL for "-inf".
AREXPORT static double atof(const char *nptr);
/// Converts an integer value into a string for true or false
AREXPORT static const char *convertBool(int val);
#ifndef SWIG
/** Invoke a functor with a string generated via sprintf format conversion
@param functor The functor to invoke with the formatted string
@param formatstr The format string into which additional argument values are inserted using vsnprintf()
@param ... Additional arguments are values to interpolate into @a formatstr to generate the final string passed as the argument in the functor invocation.
@swigomit
*/
AREXPORT static void functorPrintf(ArFunctor1<const char *> *functor,
const char *formatstr, ...);
/// @deprecated format string should be a const char*
AREXPORT static void functorPrintf(ArFunctor1<const char *> *functor,
char *formatstr, ...);
#endif
/// Function for doing a fprintf to a file (here to make a functor for)
AREXPORT static void writeToFile(const char *str, FILE *file);
/// Gets a string contained in an arbitrary file
AREXPORT static bool getStringFromFile(const char *fileName,
char *str, size_t strLen);
/**
These are for passing into getStringFromRegistry
**/
enum REGKEY {
REGKEY_CLASSES_ROOT, ///< use HKEY_CLASSES_ROOT
REGKEY_CURRENT_CONFIG, ///< use HKEY_CURRENT_CONFIG
REGKEY_CURRENT_USER, ///< use HKEY_CURRENT_USER
REGKEY_LOCAL_MACHINE, ///< use HKEY_LOCAL_MACHINE
REGKEY_USERS ///< use HKEY_USERS
};
/// Returns a string from the Windows registry
AREXPORT static bool getStringFromRegistry(REGKEY root,
const char *key,
const char *value,
char *str,
int len);
/// Returns a string from the Windows registry, searching each of the following registry root paths in order: REGKEY_CURRENT_USER, REGKEY_LOCAL_MACHINE
static bool findFirstStringInRegistry(const char* key, const char* value, char* str, int len) {
if(!getStringFromRegistry(REGKEY_CURRENT_USER, key, value, str, len))
return getStringFromRegistry(REGKEY_LOCAL_MACHINE, key, value, str, len);
return true;
}
AREXPORT static const char *COM1; ///< First serial port device name (value depends on compilation platform)
AREXPORT static const char *COM2; ///< Second serial port device name (value depends on compilation platform)
AREXPORT static const char *COM3; ///< Third serial port device name (value depends on compilation platform)
AREXPORT static const char *COM4; ///< Fourth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM5; ///< Fifth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM6; ///< Sixth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM7; ///< Seventh serial port device name (value depends on compilation platform)
AREXPORT static const char *COM8; ///< Eighth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM9; ///< Ninth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM10; ///< Tenth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM11; ///< Eleventh serial port device name (value depends on compilation platform)
AREXPORT static const char *COM12; ///< Twelth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM13; ///< Thirteenth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM14; ///< Fourteenth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM15; ///< Fifteenth serial port device name (value depends on compilation platform)
AREXPORT static const char *COM16; ///< Sixteenth serial port device name (value depends on compilation platform)
AREXPORT static const char *TRUESTRING; ///< "true"
AREXPORT static const char *FALSESTRING; ///< "false"
/** Put the current year (GMT) in s (e.g. "2005").
* @param s String buffer (allocated) to write year into
* @param len Size of @a s
*/
AREXPORT static void putCurrentYearInString(char* s, size_t len);
/** Put the current month (GMT) in s (e.g. "09" if September).
* @param s String buffer (allocated) to write month into
* @param len Size of @a s
*/
AREXPORT static void putCurrentMonthInString(char* s, size_t len);
/** Put the current day (GMT) of the month in s (e.g. "20").
* @param s String buffer (allocated) to write day into
* @param len Size of @a s
*/
AREXPORT static void putCurrentDayInString(char* s, size_t len);
/** Put the current hour (GMT) in s (e.g. "13" for 1 o'clock PM).
* @param s String buffer (allocated) to write hour into
* @param len Size of @a s
*/
AREXPORT static void putCurrentHourInString(char* s, size_t len);
/** Put the current minute (GMT) in s (e.g. "05").
* @param s String buffer (allocated) to write minutes into
* @param len Size of @a s
*/
AREXPORT static void putCurrentMinuteInString(char* s, size_t len);
/** Put the current second (GMT) in s (e.g. "59").
* @param s String buffer (allocated) to write seconds into
* @param len Size of @a s
*/
AREXPORT static void putCurrentSecondInString(char* s, size_t len);
/// Parses the given time string (h:mm) and returns the corresponding time.
/**
* @param str the char * string to be parsed; in the 24-hour format h:mm
* @param ok an output bool * set to true if the time is successfully parsed;
* false, otherwise
* @param toToday true to find the time on the current day, false to find the time on 1/1/70
* @return time_t if toToday is true then its the parsed time on the current day, if toToday is false then its the parsed time on 1/1/70
* 1/1/70
**/
AREXPORT static time_t parseTime(const char *str, bool *ok = NULL, bool toToday = true);
/** Interface to native platform localtime() function.
* On Linux, this is equivalent to a call to localtime_r(@a timep, @a result) (which is threadsafe, including the returned pointer, since it uses a different time struct for each thread)
* On Windows, this is equivalent to a call to localtime(@a timep, @a result). In addition, a static mutex is used to make it threadsafe.
*
* @param timep Pointer to current time (Unix time_t; seconds since epoch)
* @param result The result of calling platform localtime function is copied into this struct, so it must have been allocated.
* @return false on error (e.g. invalid input), otherwise true.
*
* Example:
* @code
* struct tm t;
* ArUtil::localtime(time(NULL), &t);
* ArLog::log("Current month is %d.\n", t.tm_mon);
* @endcode
*/
AREXPORT static bool localtime(const time_t *timep, struct tm *result);
/** Call ArUtil::localtime(const time_t*, struct tm *) with the current time obtained by calling
* time(NULL).
* @return false on error (e.g. invalid input), otherwise true.
*/
AREXPORT static bool localtime(struct tm *result);
// these aren't needed in windows since it ignores case anyhow
#ifndef WIN32
/// this matches the case out of what file we want
AREXPORT static bool matchCase(const char *baseDir, const char *fileName,
char * result, size_t resultLen);
#endif
/// Pulls the directory out of a file name
AREXPORT static bool getDirectory(const char *fileName,
char * result, size_t resultLen);
/// Pulls the filename out of the file name
AREXPORT static bool getFileName(const char *fileName,
char * result, size_t resultLen);
/// Sets the timestamp on the specified file
AREXPORT static bool changeFileTimestamp(const char *fileName,
time_t timestamp);
/// Opens a file, defaulting it so that the file will close on exec
AREXPORT static FILE *fopen(const char *path, const char *mode,
bool closeOnExec = true);
/// Opens a file, defaulting it so that the file will close on exec
AREXPORT static int open(const char *pathname, int flags,
bool closeOnExec = true);
/// Opens a file, defaulting it so that the file will close on exec
AREXPORT static int open(const char *pathname, int flags, mode_t mode,
bool closeOnExec = true);
AREXPORT static int close(int fd);
/// Opens a file, defaulting it so that the file will close on exec
AREXPORT static int creat(const char *pathname, mode_t mode,
bool closeOnExec = true);
/// Opens a pipe, defaulting it so that the file will close on exec
AREXPORT static FILE *popen(const char *command, const char *type,
bool closeOnExec = true);
/// Sets if the file descriptor will be closed on exec or not
AREXPORT static void setFileCloseOnExec(int fd, bool closeOnExec = true);
/// Sets if the file descriptor will be closed on exec or not
AREXPORT static void setFileCloseOnExec(FILE *file, bool closeOnExec = true);
/** Return true if the value of @a f is not NaN and is not infinite (+/- INF) */
AREXPORT static bool floatIsNormal(double f);
/** Convert seconds to milliseconds */
static double secToMSec(const double sec) { return sec * 1000.0; }
/** Convert milliseconds to seconds */
static double mSecToSec(const double msec) { return msec / 1000.0; }
/** Convert meters to US feet */
static double metersToFeet(const double m) { return m * 3.2808399; }
/** Convert US feet to meters */
static double feetToMeters(const double f) { return f / 3.2808399; }
AREXPORT static int atoi(const char *str, bool *ok = NULL,
bool forceHex = false);
protected:
//#ifndef WIN32
/// this splits up a file name (it isn't exported since it'd crash with dlls)
static std::list<std::string> splitFileName(const char *fileName);
//#endif
private:
/// The character used as a file separator on the current platform (i.e. Linux or Windows)
static const char SEPARATOR_CHAR;
/// The character used as a file separator on the current platform, in a string format
static const char *SEPARATOR_STRING;
/// The character used as a file separator on the other platforms (i.e. slash in opposite direction)
static const char OTHER_SEPARATOR_CHAR;
#ifdef WIN32
// Used on Windows to make ArUtil::localtime() function threadsafe
static ArMutex ourLocaltimeMutex;
#endif
};
/** Common math operations
@ingroup UtilityClasses
@ingroup easy
*/
class ArMath
{
private:
/* see ArMath::epsilon() */
static const double ourEpsilon;
// see getRandMax())
static const long ourRandMax;
public:
/** @return a very small number which can be used for comparisons of floating
* point values, etc.
*/
AREXPORT static double epsilon();
/// This adds two angles together and fixes the result to [-180, 180]
/**
@param ang1 first angle
@param ang2 second angle, added to first
@return sum of the angles, in range [-180,180]
@see subAngle
@see fixAngle
@ingroup easy
*/
static double addAngle(double ang1, double ang2)
{ return fixAngle(ang1 + ang2); }
/// This subtracts one angle from another and fixes the result to [-180,180]
/**
@param ang1 first angle
@param ang2 second angle, subtracted from first angle
@return resulting angle, in range [-180,180]
@see addAngle
@see fixAngle
@ingroup easy
*/
static double subAngle(double ang1, double ang2)
{ return fixAngle(ang1 - ang2); }
/// Takes an angle and returns the angle in range (-180,180]
/**
@param angle the angle to fix
@return the angle in range (-180,180]
@see addAngle
@see subAngle
@ingroup easy
*/
static double fixAngle(double angle)
{
if (angle >= 360)
angle = angle - 360.0 * (double)((int)angle / 360);
if (angle < -360)
angle = angle + 360.0 * (double)((int)angle / -360);
if (angle <= -180)
angle = + 180.0 + (angle + 180.0);
if (angle > 180)
angle = - 180.0 + (angle - 180.0);
return angle;
}
/// Converts an angle in degrees to an angle in radians
/**
@param deg the angle in degrees
@return the angle in radians
@see radToDeg
@ingroup easy
*/
static double degToRad(double deg) { return deg * M_PI / 180.0; }
/// Converts an angle in radians to an angle in degrees
/**
@param rad the angle in radians
@return the angle in degrees
@see degToRad
@ingroup easy
*/
static double radToDeg(double rad) { return rad * 180.0 / M_PI; }
/// Finds the cos, from angles in degrees
/**
@param angle angle to find the cos of, in degrees
@return the cos of the angle
@see sin
@ingroup easy
*/
static double cos(double angle) { return ::cos(ArMath::degToRad(angle)); }
/// Finds the sin, from angles in degrees
/**
@param angle angle to find the sin of, in degrees
@return the sin of the angle
@see cos
@ingroup easy
*/
static double sin(double angle) { return ::sin(ArMath::degToRad(angle)); }
/// Finds the tan, from angles in degrees
/**
@param angle angle to find the tan of, in degrees
@return the tan of the angle
@ingroup easy
*/
static double tan(double angle) { return ::tan(ArMath::degToRad(angle)); }
/// Finds the arctan of the given y/x pair
/**
@param y the y distance
@param x the x distance
@return the angle y and x form
@ingroup easy
*/
static double atan2(double y, double x)
{ return ArMath::radToDeg(::atan2(y, x)); }
/// Finds if one angle is between two other angles
/// @ingroup easy
static bool angleBetween(double angle, double startAngle, double endAngle)
{
angle = fixAngle(angle);
startAngle = fixAngle(startAngle);
endAngle = fixAngle(endAngle);
if ((startAngle < endAngle && angle > startAngle && angle < endAngle) ||
(startAngle > endAngle && (angle > startAngle || angle < endAngle)))
return true;
else
return false;
}
/// Finds the absolute value of a double
/**
@param val the number to find the absolute value of
@return the absolute value of the number
*/
static double fabs(double val)
{
if (val < 0.0)
return -val;
else
return val;
}
/// Finds the closest integer to double given
/**
@param val the double to find the nearest integer to
@return the integer the value is nearest to (also caps it within
int bounds)
*/
static int roundInt(double val)
{
val += .49;
if (val > INT_MAX)
return (int) INT_MAX;
else if (val < INT_MIN)
return (int) INT_MIN;
else
return((int) floor(val));
}
/// Finds the closest short to double given
/**
@param val the double to find the nearest short to
@return the integer the value is nearest to (also caps it within
short bounds)
*/
static short roundShort(double val)
{
val += .49;
if (val > 32767)
return (short) 32767;
else if (val < -32768)
return (short) -32768;
else
return((short) floor(val));
}
/// Rotates a point around 0 by degrees given
static void pointRotate(double *x, double *y, double th)
{
double cs, sn, xt, yt;
cs = cos(th);
sn = sin(th);
xt = *x;
yt = *y;
*x = cs*xt + sn*yt;
*y = cs*yt - sn*xt;
}
/** Returns a random number between 0 and RAND_MAX on Windows, 2^31 on Linux
* (see ArUtil::getRandMax()). On Windows, rand() is used, on Linux, lrand48(). */
static long random(void)
{
#ifdef WIN32
return(rand());
#else
return(lrand48());
#endif
}
/// Maximum of value returned by random()
AREXPORT static long getRandMax();
/** Returns a random number between @a m and @a n. On Windows, rand() is used,
* on Linux lrand48().
* @ingroup easy
*/
AREXPORT static long randomInRange(long m, long n);
/// Finds the distance between two coordinates
/**
@param x1 the first coords x position
@param y1 the first coords y position
@param x2 the second coords x position
@param y2 the second coords y position
@return the distance between (x1, y1) and (x2, y2)
* @ingroup easy
**/
static double distanceBetween(double x1, double y1, double x2, double y2)
{ return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); }
/// Finds the squared distance between two coordinates
/**
use this only where speed really matters
@param x1 the first coords x position
@param y1 the first coords y position
@param x2 the second coords x position
@param y2 the second coords y position
@return the distance between (x1, y1) and (x2, y2)
**/
static double squaredDistanceBetween(double x1, double y1, double x2, double y2)
{ return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); }
/** Base-2 logarithm */
static double log2(double x)
{
return log10(x) / 0.3010303; // 0.301... is log10(2.0).
}
/// Platform-independent call to determine whether the given double is not-a-number.
static bool isNan(double d) {
#ifdef WIN32
return _isnan(d);
#else
return isnan(d);
#endif
}
static bool isNan(float f) {
#ifdef WIN32
return _isnan(f);
#else
return isnan(f);
#endif
}
static bool isFinite(float f) {
#ifdef WIN32
return _finite(f);
#else
return finitef(f);
#endif
}
static bool isFinite(double d) {
#ifdef WIN32
return _finite(d);
#else
return finite(d);
#endif
}
static bool compareFloats(double f1, double f2, double epsilon)
{
return (fabs(f2-f1) <= epsilon);
}
static bool compareFloats(double f1, double f2)
{
return compareFloats(f1, f2, epsilon());
}
}; // end class ArMath
/// Represents an x, y position with an orientation
/**
This class represents a robot position with heading. The heading is
automatically adjusted to be in the range -180 to 180. It also defaults
to 0, and so does not need to be used. (This avoids having 2 types of
positions.) Everything in the class is inline so it should be fast.
@ingroup UtilityClasses
@ingroup easy
@sa ArPoseWithTime
*/
class ArPose
{
public:
/// Constructor, with optional initial values
/**
Sets the pose to the given values. The constructor can be called with no
parameters, with just x and y, or with x, y, and th. The given heading (th)
is automatically adjusted to be in the range -180 to 180.
@param x the double to set the x position to, default of 0
@param y the double to set the y position to, default of 0
@param th the double value for the pose's heading (or th), default of 0
*/
ArPose(double x = 0, double y = 0, double th = 0) :
myX(x),
myY(y),
myTh(ArMath::fixAngle(th))
{}
/// Copy Constructor
ArPose(const ArPose &pose) :
myX(pose.myX), myY(pose.myY), myTh(pose.myTh) {}
/// Destructor
virtual ~ArPose() {}
/// Sets the position to the given values
/**
Sets the position with the given three values, but the theta does not
need to be given as it defaults to 0.
@param x the position to set the x position to
@param y the position to set the y position to
@param th the position to set the th position to, default of 0
*/
virtual void setPose(double x, double y, double th = 0)
{ setX(x); setY(y); setTh(th); }
/// Sets the position equal to the given position
/** @param position the position value this instance should be set to */
virtual void setPose(ArPose position)
{
setX(position.getX());
setY(position.getY());
setTh(position.getTh());
}
/// Sets the x position
void setX(double x) { myX = x; }
/// Sets the y position
void setY(double y) { myY = y; }
/// Sets the heading
void setTh(double th) { myTh = ArMath::fixAngle(th); }
/// Sets the heading, using radians
void setThRad(double th) { myTh = ArMath::fixAngle(ArMath::radToDeg(th)); }
/// Gets the x position
double getX(void) const { return myX; }
/// Gets the y position
double getY(void) const { return myY; }
/// Gets the heading
double getTh(void) const { return myTh; }
/// Gets the heading, in radians
double getThRad(void) const { return ArMath::degToRad(myTh); }
/// Gets the whole position in one function call
/**
Gets the whole position at once, by giving it 2 or 3 pointers to
doubles. If you give the function a null pointer for a value it won't
try to use the null pointer, so you can pass in a NULL if you don't
care about that value. Also note that th defaults to NULL so you can
use this with just x and y.
@param x a pointer to a double to set the x position to
@param y a pointer to a double to set the y position to
@param th a pointer to a double to set the heading to, defaults to NULL
*/
void getPose(double *x, double *y, double *th = NULL) const
{
if (x != NULL)
*x = myX;
if (y != NULL)
*y = myY;
if (th != NULL)
*th = myTh;
}
/// Finds the distance from this position to the given position
/**
@param position the position to find the distance to
@return the distance to the position from this instance
*/
virtual double findDistanceTo(ArPose position) const
{
return ArMath::distanceBetween(getX(), getY(),
position.getX(),
position.getY());
}
/// Finds the square distance from this position to the given position
/**
This is only here for speed, if you aren't doing this thousands
of times a second don't use this one use findDistanceTo
@param position the position to find the distance to
@return the distance to the position from this instance
**/
virtual double squaredFindDistanceTo(ArPose position) const
{
return ArMath::squaredDistanceBetween(getX(), getY(),
position.getX(),
position.getY());
}
/// Finds the angle between this position and the given position
/**
@param position the position to find the angle to
@return the angle to the given position from this instance, in degrees
*/
virtual double findAngleTo(ArPose position) const
{
return ArMath::radToDeg(atan2(position.getY() - getY(),
position.getX() - getX()));
}
/// Logs the coordinates using ArLog
virtual void log(void) const
{ ArLog::log(ArLog::Terse, "%.0f %.0f %.1f", myX, myY, myTh); }
/// Add the other pose's X, Y and theta to this pose's X, Y, and theta (sum in theta will be normalized to (-180,180)), and return the result
virtual ArPose operator+(const ArPose& other) const
{
return ArPose( myX + other.getX(),
myY + other.getY(),
ArMath::fixAngle(myTh + other.getTh()) );
}
/// Substract the other pose's X, Y, and theta from this pose's X, Y, and theta (difference in theta will be normalized to (-180,180)), and return the result
virtual ArPose operator-(const ArPose& other) const
{
return ArPose( myX - other.getX(),
myY - other.getY(),
ArMath::fixAngle(myTh - other.getTh()) );
}
/** Adds the given pose to this one.
* @swigomit
*/
ArPose & operator+= ( const ArPose & other)
{
myX += other.myX;
myY += other.myY;
myTh = ArMath::fixAngle(myTh + other.myTh);
return *this;
}
/** Subtracts the given pose from this one.
* @swigomit
*/
ArPose & operator-= ( const ArPose & other)
{
myX -= other.myX;
myY -= other.myY;
myTh = ArMath::fixAngle(myTh - other.myTh);
return *this;
}
/// Equality operator (for sets)
virtual bool operator==(const ArPose& other) const
{
return ((fabs(myX - other.myX) < ArMath::epsilon()) &&
(fabs(myY - other.myY) < ArMath::epsilon()) &&
(fabs(myTh - other.myTh) < ArMath::epsilon()));
}
virtual bool operator!=(const ArPose& other) const
{
return ((fabs(myX - other.myX) > ArMath::epsilon()) ||
(fabs(myY - other.myY) > ArMath::epsilon()) ||
(fabs(myTh - other.myTh) > ArMath::epsilon()));
}
/// Less than operator (for sets)
virtual bool operator<(const ArPose& other) const
{
if (fabs(myX - other.myX) > ArMath::epsilon()) {
return myX < other.myX;
}
else if (fabs(myY - other.myY) > ArMath::epsilon()) {
return myY < other.myY;
}
else if (fabs(myTh - other.myTh) > ArMath::epsilon()) {
return myTh < other.myTh;
}
// Otherwise... x, y, and th are equal
return false;
} // end operator <
/// Finds the distance between two poses (static function, uses no
/// data from any instance and shouldn't be able to be called on an
/// instance)
/**
@param pose1 the first coords
@param pose2 the second coords
@return the distance between the poses
**/
static double distanceBetween(ArPose pose1, ArPose pose2)
{ return ArMath::distanceBetween(pose1.getX(), pose1.getY(),
pose2.getX(), pose2.getY()); }
/// Return true if the X value of p1 is less than the X value of p2
static bool compareX(const ArPose& p1, const ArPose &p2)
{ return (p1.getX() < p2.getX()); }
/// Return true if the Y value of p1 is less than the X value of p2
static bool compareY(const ArPose& p1, const ArPose &p2)
{ return (p1.getY() < p2.getY()); }
bool isInsidePolygon(const std::vector<ArPose>& vertices) const
{
bool inside = false;
const size_t n = vertices.size();
size_t i = 0;
size_t j = n-1;
for(; i < n; j = i++)
{
const double x1 = vertices[i].getX();
const double x2 = vertices[j].getX();
const double y1 = vertices[i].getY();
const double y2 = vertices[j].getY();
if((((y1 < getY()) && (getY() < y2)) || ((y2 <= getY()) && (getY() < y1))) && (getX() <= (x2 - x1) * (getY() - y1) / (y2 - y1) + x1))
inside = !inside;
}
return inside;
}
protected:
double myX;
double myY;
double myTh;
};
/// A class for time readings and measuring durations
/**
This class is for timing durations or time between events.
The time values it stores are relative to an abritrary starting time; it
does not correspond to "real world" or "wall clock" time in any way,
so DON'T use this for keeping track of what time it is,
just for timestamps and relative timing (e.g. "this loop needs to sleep another 100 ms").
The recommended methods to use are setToNow() to reset the time,
mSecSince() to obtain the number of milliseconds elapsed since it was
last reset (or secSince() if you don't need millisecond precision), and
mSecSince(ArTime) or secSince(ArTime) to find the difference between
two ArTime objects.
On systems where it is supported this will use a monotonic clock,
this is an ever increasing system that is not dependent on what
the time of day is set to. Normally for linux gettimeofday is
used, but if the time is changed forwards or backwards then bad
things can happen. Windows uses a time since bootup, which
functions the same as the monotonic clock anyways. You can use
ArTime::usingMonotonicClock() to see if this is being used. Note
that an ArTime will have had to have been set to for this to be a
good value... Aria::init does this however, so that should not be
an issue. It looks like the monotonic clocks won't work on linux
kernels before 2.6.
@ingroup UtilityClasses
*/
class ArTime
{
public:
/// Constructor. Time is initialized to the current time.
/// @ingroup easy
ArTime() { setToNow(); }
/// Copy constructor
//
ArTime(const ArTime &other) :
mySec(other.mySec),
myMSec(other.myMSec)
{}
/// Assignment operator
ArTime &operator=(const ArTime &other)
{
if (this != &other) {
mySec = other.mySec;
myMSec = other.myMSec;
}
return *this;
}
//
/// Destructor
~ArTime() {}
/// Gets the number of milliseconds since the given timestamp to this one
/// @ingroup easy
long mSecSince(ArTime since) const
{
long long ret = mSecSinceLL(since);
if (ret > INT_MAX)
return INT_MAX;
if (ret < -INT_MAX)
return -INT_MAX;
return ret;
/* The old way that had problems with wrapping
long long timeSince, timeThis;
timeSince = since.getSec() * 1000 + since.getMSec();
timeThis = mySec * 1000 + myMSec;
return timeSince - timeThis;
*/
}
/// Gets the number of milliseconds since the given timestamp to this one
long long mSecSinceLL(ArTime since) const
{
long long timeSince, timeThis;
timeSince = since.getSecLL() * 1000 + since.getMSecLL();
timeThis = mySec * 1000 + myMSec;
return timeSince - timeThis;
}
/// Gets the number of seconds since the given timestamp to this one
/// @ingroup easy
long secSince(ArTime since) const
{
return mSecSince(since)/1000;
}
/// Gets the number of seconds since the given timestamp to this one
long long secSinceLL(ArTime since) const
{
return mSecSinceLL(since)/1000;
}
/// Finds the number of millisecs from when this timestamp is set to to now (the inverse of mSecSince())
/// @ingroup easy
long mSecTo(void) const
{
ArTime now;
now.setToNow();
return -mSecSince(now);
}
/// Finds the number of millisecs from when this timestamp is set to to now (the inverse of mSecSince())
long long mSecToLL(void) const
{
ArTime now;
now.setToNow();
return -mSecSinceLL(now);
}
/// Finds the number of seconds from when this timestamp is set to to now (the inverse of secSince())
/// @ingroup easy
long secTo(void) const
{
return mSecTo()/1000;
}
/// Finds the number of seconds from when this timestamp is set to to now (the inverse of secSince())
long long secToLL(void) const
{
return mSecToLL()/1000;
}
/// Finds the number of milliseconds from this timestamp to now
long mSecSince(void) const
{
ArTime now;
now.setToNow();
return mSecSince(now);
}
/// Finds the number of milliseconds from this timestamp to now
long long mSecSinceLL(void) const
{
ArTime now;
now.setToNow();
return mSecSinceLL(now);
}
/// Finds the number of seconds from when this timestamp was set to now
long secSince(void) const
{
return mSecSince()/1000;
}
/// Finds the number of seconds from when this timestamp was set to now
long long secSinceLL(void) const
{
return mSecSinceLL()/1000;
}
/// returns whether the given time is before this one or not
/// @ingroup easy
bool isBefore(ArTime testTime) const
{
if (mSecSince(testTime) < 0)
return true;
else
return false;
}
/// returns whether the given time is equal to this time or not
bool isAt(ArTime testTime) const
{
if (mSecSince(testTime) == 0)
return true;
else
return false;
}
/// returns whether the given time is after this one or not
/// @ingroup easy
bool isAfter(ArTime testTime) const
{
if (mSecSince(testTime) > 0)
return true;
else
return false;
}
/// Resets the time
/// @ingroup easy
AREXPORT void setToNow(void);
/// Add some milliseconds (can be negative) to this time
bool addMSec(long ms)
{
//unsigned long timeThis;
long long timeThis;
timeThis = mySec * 1000 + myMSec;
//if (ms < 0 && (unsigned)abs(ms) > timeThis)
if (ms < 0 && -ms > timeThis)
{
ArLog::log(ArLog::Terse, "ArTime::addMSec: tried to subtract too many milliseconds, would result in a negative time.");
mySec = 0;
myMSec = 0;
return false;
}
else
{
timeThis += ms;
mySec = timeThis / 1000;
myMSec = timeThis % 1000;
}
return true;
} // end method addMSec
/// Add some milliseconds (can be negative) to this time
bool addMSecLL(long long ms)
{
//unsigned long timeThis;
long long timeThis;
timeThis = mySec * 1000 + myMSec;
//if (ms < 0 && (unsigned)abs(ms) > timeThis)
if (ms < 0 && -ms > timeThis)
{
ArLog::log(ArLog::Terse, "ArTime::addMSec: tried to subtract too many milliseconds, would result in a negative time.");
mySec = 0;
myMSec = 0;
return false;
}
else
{
timeThis += ms;
mySec = timeThis / 1000;
myMSec = timeThis % 1000;
}
return true;
} // end method addMSec
/// Sets the seconds value (since the arbitrary starting time)
void setSec(unsigned long sec) { mySec = sec; }
/// Sets the milliseconds value (occuring after the seconds value)
void setMSec(unsigned long msec) { myMSec = msec; }
/// Gets the seconds value (since the arbitrary starting time)
unsigned long getSec(void) const { return mySec; }
/// Gets the milliseconds value (occuring after the seconds value)
unsigned long getMSec(void) const { return myMSec; }
/// Sets the seconds value (since the arbitrary starting time)
void setSecLL(unsigned long long sec) { mySec = sec; }
/// Sets the milliseconds value (occuring after the seconds value)
void setMSecLL(unsigned long long msec) { myMSec = msec; }
/// Gets the seconds value (since the arbitrary starting time)
unsigned long long getSecLL(void) const { return mySec; }
/// Gets the milliseconds value (occuring after the seconds value)
unsigned long long getMSecLL(void) const { return myMSec; }
/// Logs the time
/// @ingroup easy
void log(const char *prefix = NULL) const
{ ArLog::log(ArLog::Terse,
"%sTime: %lld.%lld",
((prefix != NULL) ? prefix : ""),
mySec,
myMSec); }
/// Gets if we're using a monotonic (ever increasing) clock
static bool usingMonotonicClock()
{
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
return ourMonotonicClock;
#endif
#ifdef WIN32
return true;
#endif
return false;
}
/// Equality operator (for sets)
bool operator==(const ArTime& other) const
{
return isAt(other);
}
bool operator!=(const ArTime& other) const
{
return (!isAt(other));
}
// Less than operator for sets
/// @ingroup easy
bool operator<(const ArTime& other) const
{
return isBefore(other);
} // end operator <
/// @ingroup easy
bool operator>(const ArTime& other) const
{
return isAfter(other);
}
protected:
unsigned long long mySec;
unsigned long long myMSec;
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
static bool ourMonotonicClock;
#endif
}; // end class ArTime
/// A subclass of ArPose that also stores a timestamp (ArTime)
/**
@ingroup UtilityClasses
*/
class ArPoseWithTime : public ArPose
{
public:
ArPoseWithTime(double x = 0, double y = 0, double th = 0,
ArTime thisTime = ArTime()) : ArPose(x, y, th)
{ myTime = thisTime; }
/// Copy Constructor
ArPoseWithTime(const ArPose &pose) : ArPose(pose) {}
virtual ~ArPoseWithTime() {}
void setTime(ArTime newTime) { myTime = newTime; }
void setTimeToNow(void) { myTime.setToNow(); }
ArTime getTime(void) const { return myTime; }
protected:
ArTime myTime;
};
/// A class for keeping track of if a complete revolution has been attained
/**
This class can be used to keep track of if a complete revolution has been
done, it is used by doing doing a clearQuadrants when you want to stat
the revolution. Then at each point doing an updateQuadrant with the current
heading of the robot. When didAllQuadrants returns true, then all the
quadrants have been done.
@ingroup UtilityClasses
*/
class ArSectors
{
public:
/// Constructor
ArSectors(int numSectors = 8)
{
mySectorSize = 360/numSectors;
mySectors = new int[numSectors];
myNumSectors = numSectors;
clear();
}
/// Destructor
virtual ~ArSectors() { delete mySectors; }
/// Clears all quadrants
void clear(void)
{
int i;
for (i = 0; i < myNumSectors; i++)
mySectors[i] = false;
}
/// Updates the appropriate quadrant for the given angle
void update(double angle)
{
int angleInt;
angleInt = ArMath::roundInt(ArMath::fixAngle(angle) + 180);
mySectors[angleInt / mySectorSize] = true;
}
/// Returns true if the all of the quadrants have been gone through
bool didAll(void) const
{
int i;
for (i = 0; i < myNumSectors; i++)
if (mySectors[i] == false)
return false;
return true;
}
protected:
int *mySectors;
int myNumSectors;
int mySectorSize;
};
/// Represents geometry of a line in two-dimensional space.
/**
Note this the theoretical line, i.e. it goes infinitely.
For a line segment with endpoints, use ArLineSegment.
@sa ArLineSegment
@ingroup UtilityClasses
**/
class ArLine
{
public:
///// Empty constructor
ArLine() {}
/// Constructor with parameters
ArLine(double a, double b, double c) { newParameters(a, b, c); }
/// Constructor with endpoints
ArLine(double x1, double y1, double x2, double y2)
{ newParametersFromEndpoints(x1, y1, x2, y2); }
/// Destructor
virtual ~ArLine() {}
/// Sets the line parameters (make it not a segment)
void newParameters(double a, double b, double c)
{ myA = a; myB = b; myC = c; }
/// Sets the line parameters from endpoints, but makes it not a segment
void newParametersFromEndpoints(double x1, double y1, double x2, double y2)
{ myA = y1 - y2; myB = x2 - x1; myC = (y2 *x1) - (x2 * y1); }
/// Gets the A line parameter
double getA(void) const { return myA; }
/// Gets the B line parameter
double getB(void) const { return myB; }
/// Gets the C line parameter
double getC(void) const { return myC; }
/// finds the intersection of this line with another line
/**
@param line the line to check if it intersects with this line
@param pose if the lines intersect, the pose is set to the location
@return true if they intersect, false if they do not
**/
bool intersects(const ArLine *line, ArPose *pose) const
{
double x, y;
double n;
n = (line->getB() * getA()) - (line->getA() * getB());
// if this is 0 the lines are parallel
if (fabs(n) < .0000000000001)
{
return false;
}
// they weren't parallel so see where the intersection is
x = ((line->getC() * getB()) - (line->getB() * getC())) / n;
y = ((getC() * line->getA()) - (getA() * line->getC())) / n;
pose->setPose(x, y);
return true;
}
/// Makes the given line perpendicular to this one through the given pose
void makeLinePerp(const ArPose *pose, ArLine *line) const
{
line->newParameters(getB(), -getA(),
(getA() * pose->getY()) - (getB() * pose->getX()));
}
/// Calculate the distance from the given point to (its projection on) this line segment
/**
@param pose the the pose to find the perp point of
@return if the pose does not intersect line it will return < 0
if the pose intersects the segment it will return the distance to
the intersection
**/
virtual double getPerpDist(const ArPose &pose) const
{
ArPose perpPose;
ArLine perpLine;
makeLinePerp(&pose, &perpLine);
if (!intersects(&perpLine, &perpPose))
return -1;
return (perpPose.findDistanceTo(pose));
}
/// Calculate the squared distance from the given point to (its projection on) this line segment
/**
@param pose the the pose to find the perp point of
@return if the pose does not intersect line it will return < 0
if the pose intersects the segment it will return the distance to
the intersection
**/
virtual double getPerpSquaredDist(const ArPose &pose) const
{
ArPose perpPose;
ArLine perpLine;
makeLinePerp(&pose, &perpLine);
if (!intersects(&perpLine, &perpPose))
return -1;
return (perpPose.squaredFindDistanceTo(pose));
}
/// Determine the intersection point between this line segment, and a perpendicular line passing through the given pose (i.e. projects the given pose onto this line segment.)
/**
* If there is no intersection, false is returned.
@param pose The X and Y components of this pose object indicate the point to project onto this line segment.
@param perpPoint The X and Y components of this pose object are set to indicate the intersection point
@return true if an intersection was found and perpPoint was modified, false otherwise.
@swigomit
**/
bool getPerpPoint(const ArPose &pose, ArPose *perpPoint) const
{
ArLine perpLine;
makeLinePerp(&pose, &perpLine);
return intersects(&perpLine, perpPoint);
}
/// Equality operator
virtual bool operator==(const ArLine &other) const
{
return ((fabs(myA - other.myA) <= ArMath::epsilon()) &&
(fabs(myB - other.myB) <= ArMath::epsilon()) &&
(fabs(myC - other.myC) <= ArMath::epsilon()));
}
/// Inequality operator
virtual bool operator!=(const ArLine &other) const
{
return ((fabs(myA - other.myA) > ArMath::epsilon()) ||
(fabs(myB - other.myB) > ArMath::epsilon()) ||
(fabs(myC - other.myC) > ArMath::epsilon()));
}
protected:
double myA, myB, myC;
};
/// Represents a line segment in two-dimensional space.
/** The segment is defined by the coordinates of each endpoint.
@ingroup UtilityClasses
*/
class ArLineSegment
{
public:
#ifndef SWIG
/** @swigomit */
ArLineSegment() {}
/** @brief Constructor with endpoints
* @swigomit
*/
ArLineSegment(double x1, double y1, double x2, double y2)
{ newEndPoints(x1, y1, x2, y2); }
#endif // SWIG
/// Constructor with endpoints as ArPose objects. Only X and Y components of the poses will be used.
ArLineSegment(ArPose pose1, ArPose pose2)
{ newEndPoints(pose1.getX(), pose1.getY(), pose2.getX(), pose2.getY()); }
virtual ~ArLineSegment() {}
/// Set new end points for this line segment
void newEndPoints(double x1, double y1, double x2, double y2)
{
myX1 = x1; myY1 = y1; myX2 = x2; myY2 = y2;
myLine.newParametersFromEndpoints(myX1, myY1, myX2, myY2);
}
/// Set new end points for this line segment
void newEndPoints(const ArPose& pt1, const ArPose& pt2)
{
newEndPoints(pt1.getX(), pt1.getY(), pt2.getX(), pt2.getY());
}
/// Get the first endpoint (X1, Y1)
ArPose getEndPoint1(void) const { return ArPose(myX1, myY1); }
/// Get the second endpoint of (X2, Y2)
ArPose getEndPoint2(void) const { return ArPose(myX2, myY2); }
/// Determine where a line intersects this line segment
/**
@param line Line to check for intersection against this line segment.
@param pose if the lines intersect, the X and Y components of this pose are set to the point of intersection.
@return true if they intersect, false if they do not
**/
bool intersects(const ArLine *line, ArPose *pose) const
{
ArPose intersection;
// see if it intersects, then make sure its in the coords of this line
if (myLine.intersects(line, &intersection) &&
linePointIsInSegment(&intersection))
{
pose->setPose(intersection);
return true;
}
else
return false;
}
/** @copydoc intersects(const ArLine *line, ArPose *pose) const */
bool intersects(ArLineSegment *line, ArPose *pose) const
{
ArPose intersection;
// see if it intersects, then make sure its in the coords of this line
if (myLine.intersects(line->getLine(), &intersection) &&
linePointIsInSegment(&intersection) &&
line->linePointIsInSegment(&intersection))
{
pose->setPose(intersection);
return true;
}
else
return false;
}
#ifndef SWIG
/// Determine the intersection point between this line segment, and a perpendicular line passing through the given pose (i.e. projects the given pose onto this line segment.)
/**
* If there is no intersection, false is returned.
@param pose The X and Y components of this pose object indicate the point to project onto this line segment.
@param perpPoint The X and Y components of this pose object are set to indicate the intersection point
@return true if an intersection was found and perpPoint was modified, false otherwise.
@swigomit
**/
bool getPerpPoint(const ArPose &pose, ArPose *perpPoint) const
{
ArLine perpLine;
myLine.makeLinePerp(&pose, &perpLine);
return intersects(&perpLine, perpPoint);
}
#endif
/** @copydoc getPerpPoint(const ArPose&, ArPose*) const
* (This version simply allows you to pass the first pose as a pointer, in
* time-critical situations where a full copy of the object would impact
* performance.)
*/
bool getPerpPoint(const ArPose *pose, ArPose *perpPoint) const
{
ArLine perpLine;
myLine.makeLinePerp(pose, &perpLine);
return intersects(&perpLine, perpPoint);
}
/// Calculate the distance from the given point to (its projection on) this line segment
/**
@param pose the the pose to find the perp point of
@return if the pose does not intersect segment it will return < 0
if the pose intersects the segment it will return the distance to
the intersection
**/
virtual double getPerpDist(const ArPose &pose) const
{
ArPose perpPose;
ArLine perpLine;
myLine.makeLinePerp(&pose, &perpLine);
if (!intersects(&perpLine, &perpPose))
return -1;
return (perpPose.findDistanceTo(pose));
}
/// Calculate the squared distance from the given point to (its projection on) this line segment
/**
@param pose the the pose to find the perp point of
@return if the pose does not intersect segment it will return < 0
if the pose intersects the segment it will return the distance to
the intersection
**/
virtual double getPerpSquaredDist(const ArPose &pose) const
{
ArPose perpPose;
ArLine perpLine;
myLine.makeLinePerp(&pose, &perpLine);
if (!intersects(&perpLine, &perpPose))
return -1;
return (perpPose.squaredFindDistanceTo(pose));
}
/// Gets the distance from this line segment to a point.
/**
* If the point can be projected onto this line segment (i.e. a
* perpendicular line can be drawn through the point), then
* return that distance. Otherwise, return the distance to the closest
* endpoint.
@param pose the pointer of the pose to find the distance to
**/
double getDistToLine(const ArPose &pose) const
{
ArPose perpPose;
ArLine perpLine;
myLine.makeLinePerp(&pose, &perpLine);
if (!intersects(&perpLine, &perpPose))
{
return ArUtil::findMin(
ArMath::roundInt(getEndPoint1().findDistanceTo(pose)),
ArMath::roundInt(getEndPoint2().findDistanceTo(pose)));
}
return (perpPose.findDistanceTo(pose));
}
/// Determines the length of the line segment
double getLengthOf() const
{
return ArMath::distanceBetween(myX1, myY1, myX2, myY2);
}
/// Determines the mid point of the line segment
ArPose getMidPoint() const
{
return ArPose(((myX1 + myX2) / 2.0),
((myY1 + myY2) / 2.0));
}
/// Gets the x coordinate of the first endpoint
double getX1(void) const { return myX1; }
/// Gets the y coordinate of the first endpoint
double getY1(void) const { return myY1; }
/// Gets the x coordinate of the second endpoint
double getX2(void) const { return myX2; }
/// Gets the y coordinate of the second endpoint
double getY2(void) const { return myY2; }
/// Gets the A line parameter (see ArLine)
double getA(void) const { return myLine.getA(); }
/// Gets the B line parameter (see ArLine)
double getB(void) const { return myLine.getB(); }
/// Gets the C line parameter (see ArLine)
double getC(void) const { return myLine.getC(); }
/// Internal function for seeing if a point on our line is within our segment
bool linePointIsInSegment(ArPose *pose) const
{
bool isVertical = (ArMath::fabs(myX1 - myX2) < ArMath::epsilon());
bool isHorizontal = (ArMath::fabs(myY1 - myY2) < ArMath::epsilon());
if (!isVertical || !isHorizontal) {
return (((isVertical) ||
(pose->getX() >= myX1 && pose->getX() <= myX2) ||
(pose->getX() <= myX1 && pose->getX() >= myX2)) &&
((isHorizontal) ||
(pose->getY() >= myY1 && pose->getY() <= myY2) ||
(pose->getY() <= myY1 && pose->getY() >= myY2)));
}
else { // single point segment
return ((ArMath::fabs(myX1 - pose->getX()) < ArMath::epsilon()) &&
(ArMath::fabs(myY1 - pose->getY()) < ArMath::epsilon()));
} // end else single point segment
}
const ArLine *getLine(void) const { return &myLine; }
/// Equality operator (for sets)
virtual bool operator==(const ArLineSegment& other) const
{
return ((fabs(myX1 - other.myX1) < ArMath::epsilon()) &&
(fabs(myY1 - other.myY1) < ArMath::epsilon()) &&
(fabs(myX2 - other.myX2) < ArMath::epsilon()) &&
(fabs(myY2 - other.myY2) < ArMath::epsilon()));
}
virtual bool operator!=(const ArLineSegment& other) const
{
return ((fabs(myX1 - other.myX1) > ArMath::epsilon()) ||
(fabs(myY1 - other.myY1) > ArMath::epsilon()) ||
(fabs(myX2 - other.myX2) > ArMath::epsilon()) ||
(fabs(myY2 - other.myY2) > ArMath::epsilon()));
}
/// Less than operator (for sets)
virtual bool operator<(const ArLineSegment& other) const
{
if (fabs(myX1 - other.myX1) > ArMath::epsilon()) {
return myX1 < other.myX1;
}
else if (fabs(myY1 - other.myY1) > ArMath::epsilon()) {
return myY1 < other.myY1;
}
if (fabs(myX2 - other.myX2) > ArMath::epsilon()) {
return myX2 < other.myX2;
}
else if (fabs(myY2 - other.myY2) > ArMath::epsilon()) {
return myY2 < other.myY2;
}
// Otherwise... all coords are equal
return false;
}
protected:
double myX1, myY1, myX2, myY2;
ArLine myLine;
};
/**
@brief Use for computing a running average of a number of elements
@ingroup UtilityClasses
*/
class ArRunningAverage
{
public:
/// Constructor, give it the number of elements to store to compute the average
AREXPORT ArRunningAverage(size_t numToAverage);
/// Destructor
AREXPORT ~ArRunningAverage();
/// Gets the average
AREXPORT double getAverage(void) const;
/// Adds a value to the average. An old value is discarded if the number of elements to average has been reached.
AREXPORT void add(double val);
/// Clears the average
AREXPORT void clear(void);
/// Gets the number of elements
AREXPORT size_t getNumToAverage(void) const;
/// Sets the number of elements
AREXPORT void setNumToAverage(size_t numToAverage);
/// Sets if this is using a the root mean square average or just the normal average
AREXPORT void setUseRootMeanSquare(bool useRootMeanSquare);
/// Gets if this is using a the root mean square average or just the normal average
AREXPORT bool getUseRootMeanSquare(void);
/// Gets the number of values currently averaged so far
AREXPORT size_t getCurrentNumAveraged(void);
protected:
size_t myNumToAverage;
double myTotal;
size_t myNum;
bool myUseRootMeanSquare;
std::list<double> myVals;
};
/// This is a class for computing a root mean square average of a number of elements
/// @ingroup UtilityClasses
class ArRootMeanSquareCalculator
{
public:
/// Constructor
AREXPORT ArRootMeanSquareCalculator();
/// Destructor
AREXPORT ~ArRootMeanSquareCalculator();
/// Gets the average
AREXPORT double getRootMeanSquare (void) const;
/// Adds a number
AREXPORT void add(int val);
/// Clears the average
AREXPORT void clear(void);
/// Sets the name
AREXPORT void setName(const char *name);
/// Gets the name
AREXPORT const char *getName(void);
/// Gets the num averaged
AREXPORT size_t getCurrentNumAveraged(void);
protected:
long long myTotal;
size_t myNum;
std::string myName;
};
//class ArStrCaseCmpOp : public std::binary_function <const std::string&, const std::string&, bool>
/// strcasecmp for sets
/// @ingroup UtilityClasses
struct ArStrCaseCmpOp
{
public:
bool operator() (const std::string &s1, const std::string &s2) const
{
return strcasecmp(s1.c_str(), s2.c_str()) < 0;
}
};
/// ArPose less than comparison for sets
/// @ingroup UtilityClasses
struct ArPoseCmpOp
{
public:
bool operator() (const ArPose &pose1, const ArPose &pose2) const
{
return (pose1 < pose2);
//return (pose1.getX() < pose2.getX() || pose1.getY() < pose2.getY() ||
// pose1.getTh() < pose2.getTh());
}
};
/// ArLineSegment less than comparison for sets
/// @ingroup UtilityClasses
struct ArLineSegmentCmpOp
{
public:
bool operator() (const ArLineSegment &line1,
const ArLineSegment &line2) const
{
return (line1 < line2);
//return (line1.getX1() < line2.getX1() || line1.getY1() < line2.getY1() ||
// line1.getX2() < line2.getX2() || line1.getY2() < line2.getY2());
}
};
#if !defined(WIN32) && !defined(SWIG)
/** @brief Switch to running the program as a background daemon (i.e. fork) (Only available in Linux)
@swigomit
@notwindows
@ingroup UtilityClasses
@ingroup OptionalClasses
*/
class ArDaemonizer
{
public:
/// Constructor that sets up for daemonizing if arg checking
AREXPORT ArDaemonizer(int *argc, char **argv, bool closeStdErrAndStdOut);
/// Destructor
AREXPORT ~ArDaemonizer();
/// Daemonizes if asked too by arguments
AREXPORT bool daemonize(void);
/// Daemonizes always
AREXPORT bool forceDaemonize(void);
/// Logs the options
AREXPORT void logOptions(void) const;
/// Returns if we're daemonized or not
bool isDaemonized(void) { return myIsDaemonized; }
protected:
ArArgumentParser myParser;
bool myIsDaemonized;
bool myCloseStdErrAndStdOut;
ArConstFunctorC<ArDaemonizer> myLogOptionsCB;
};
#endif // !win32 && !swig
/// Contains enumeration of four user-oriented priority levels (used primarily by ArConfig)
class ArPriority
{
public:
enum Priority
{
IMPORTANT, ///< Basic things that should be modified to suit
BASIC = IMPORTANT, ///< Basic things that should be modified to suit
FIRST_PRIORITY = IMPORTANT,
NORMAL, ///< Intermediate things that users may want to modify
INTERMEDIATE = NORMAL, ///< Intermediate things that users may want to modify
DETAILED, ///< Advanced items that probably shouldn't be modified
TRIVIAL = DETAILED, ///< Advanced items (alias for historic reasons)
ADVANCED = DETAILED, ///< Advanced items that probably shouldn't be modified
EXPERT, ///< Items that should be modified only by expert users or developers
FACTORY, ///< Items that should be modified at the factory, often apply to a robot model
CALIBRATION, ///< Items that apply to a particular hardware instance
LAST_PRIORITY = CALIBRATION ///< Last value in the enumeration
};
enum {
PRIORITY_COUNT = LAST_PRIORITY + 1 ///< Number of priority values
};
/// Returns the displayable text string for the given priority
AREXPORT static const char * getPriorityName(Priority priority);
/// Returns the priority value that corresponds to the given displayable text string
/**
* @param text the char * to be converted to a priority value
* @param ok an optional bool * set to true if the text was successfully
* converted; false if the text was not recognized as a priority
**/
AREXPORT static Priority getPriorityFromName(const char *text,
bool *ok = NULL);
protected:
/// Whether the map of priorities to display text has been initialized
static bool ourStringsInited;
/// Map of priorities to displayable text
static std::map<Priority, std::string> ourPriorityNames;
/// Map of displayable text to priorities
static std::map<std::string, ArPriority::Priority, ArStrCaseCmpOp> ourNameToPriorityMap;
/// Display text used when a priority's displayable text has not been defined
static std::string ourUnknownPriorityName;
};
/// holds information about ArStringInfo component strings (it's a helper class for other things)
/**
This class holds information for about different strings that are available
**/
class ArStringInfoHolder
{
public:
/// Constructor
ArStringInfoHolder(const char *name, ArTypes::UByte2 maxLength,
ArFunctor2<char *, ArTypes::UByte2> *functor)
{ myName = name; myMaxLength = maxLength; myFunctor = functor; }
/// Destructor
virtual ~ArStringInfoHolder() {}
/// Gets the name of this piece of info
const char *getName(void) { return myName.c_str(); }
/// Gets the maximum length of this piece of info
ArTypes::UByte2 getMaxLength(void) { return myMaxLength; }
/// Gets the function that will fill in this piece of info
ArFunctor2<char *, ArTypes::UByte2> *getFunctor(void) { return myFunctor; }
protected:
std::string myName;
ArTypes::UByte2 myMaxLength;
ArFunctor2<char *, ArTypes::UByte2> *myFunctor;
};
/// This class just holds some helper functions for the ArStringInfoHolder
class ArStringInfoHolderFunctions
{
public:
static void intWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<int> *functor, const char *format)
{ snprintf(buffer, bufferLen - 1, format, functor->invokeR());
buffer[bufferLen-1] = '\0'; }
static void doubleWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<double> *functor, const char *format)
{ snprintf(buffer, bufferLen - 1, format, functor->invokeR());
buffer[bufferLen-1] = '\0'; }
static void boolWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<bool> *functor, const char *format)
{ snprintf(buffer, bufferLen - 1, format,
ArUtil::convertBool(functor->invokeR()));
buffer[bufferLen-1] = '\0'; }
static void stringWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<const char *> *functor,
const char *format)
{ snprintf(buffer, bufferLen - 1, format, functor->invokeR());
buffer[bufferLen-1] = '\0'; }
static void cppStringWrapper(char *buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<std::string> *functor)
{
snprintf(buffer, bufferLen - 1, "%s", functor->invokeR().c_str());
buffer[bufferLen-1] = '\0';
}
static void unsignedLongWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<unsigned long> *functor, const char *format)
{ snprintf(buffer, bufferLen - 1, format, functor->invokeR());
buffer[bufferLen-1] = '\0'; }
static void longWrapper(char * buffer, ArTypes::UByte2 bufferLen,
ArRetFunctor<long> *functor, const char *format)
{ snprintf(buffer, bufferLen - 1, format, functor->invokeR());
buffer[bufferLen-1] = '\0'; }
};
/** @see ArCallbackList */
template<class GenericFunctor>
class ArGenericCallbackList
{
public:
/// Constructor
ArGenericCallbackList(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false)
{
myName = name;
mySingleShot = singleShot;
setLogLevel(logLevel);
std::string mutexName;
mutexName = "ArGenericCallbackList::";
mutexName += name;
mutexName += "::myDataMutex";
myDataMutex.setLogName(mutexName.c_str());
myLogging = true;
}
/// Destructor
virtual ~ArGenericCallbackList()
{
}
/// Adds a callback
void addCallback(GenericFunctor functor, int position = 50)
{
myDataMutex.lock();
myList.insert(
std::pair<int, GenericFunctor>(-position,
functor));
myDataMutex.unlock();
}
/// Removes a callback
void remCallback(GenericFunctor functor)
{
myDataMutex.lock();
typename std::multimap<int, GenericFunctor>::iterator it;
for (it = myList.begin(); it != myList.end(); it++)
{
if ((*it).second == functor)
{
myList.erase(it);
myDataMutex.unlock();
remCallback(functor);
return;
}
}
myDataMutex.unlock();
}
/// Sets the name
void setName(const char *name)
{
myDataMutex.lock();
myName = name;
myDataMutex.unlock();
}
#ifndef SWIG
/// Sets the name with formatting
/** @swigomit use setName() */
void setNameVar(const char *name, ...)
{
char arg[2048];
va_list ptr;
va_start(ptr, name);
vsnprintf(arg, sizeof(arg), name, ptr);
arg[sizeof(arg) - 1] = '\0';
va_end(ptr);
return setName(arg);
}
#endif
/// Sets the log level
void setLogLevel(ArLog::LogLevel logLevel)
{
myDataMutex.lock();
myLogLevel = logLevel;
myDataMutex.unlock();
}
/// Sets if its single shot
void setSingleShot(bool singleShot)
{
myDataMutex.lock();
mySingleShot = singleShot;
myDataMutex.unlock();
}
/// Enable or disable logging when invoking the list. Logging is enabled by default at the log level given in the constructor.
void setLogging(bool on) {
myLogging = on;
}
protected:
ArMutex myDataMutex;
ArLog::LogLevel myLogLevel;
std::string myName;
std::multimap<int, GenericFunctor> myList;
bool mySingleShot;
bool myLogging;
};
/** Stores a list of ArFunctor objects together.
invoke() will invoke each of the ArFunctor objects.
The functors added to the list must be pointers to the same ArFunctor subclass.
Use ArCallbackList for ArFunctor objects with no arguments.
Use ArCallbackList1 for ArFunctor1 objects with 1 argument.
Use ArCallbackList2 for ArFunctor2 objects with 2 arguments.
Use ArCallbackList3 for ArFunctor3 objects with 3 arguments.
Use ArCallbackListp for ArFunctor4 objects with 4 arguments.
Example: Declare a callback list for callbacks accepting one argument like this:
@code
ArCallbackList1<int> callbackList;
@endcode
then add a functor like this:
@code
ArFunctor1C<MyClass, int> func;
...
callbackList.addCallback(&func);
@endcode
then invoke it like this:
@code
callbackList.invoke(23);
@endcode
A "singleShot" flag may be set, in which case the ArFunctor objects are removed
from the list after being invoked.
This list is threadsafe: the list contains a mutex (ArMutex), which is locked when
modifying the list and when invoking the ArFunctor objects. Set singleShot
in the constructor or call setSingleShot().
Call setLogging() to enable more detailed logging including names of
ArFunctor objects being invoked (if the ArFunctor objects have been given
names.) Call setLogLevel() to select ArLog log level.
@ingroup UtilityClasses
**/
class ArCallbackList : public ArGenericCallbackList<ArFunctor *>
{
public:
/// Constructor
ArCallbackList(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false) :
ArGenericCallbackList<ArFunctor *>(name, logLevel, singleShot)
{
}
/// Destructor
virtual ~ArCallbackList()
{
}
/// Calls the callback list
void invoke(void)
{
myDataMutex.lock();
std::multimap<int, ArFunctor *>::iterator it;
ArFunctor *functor;
if(myLogging)
ArLog::log( myLogLevel, "%s: Starting calls to %d functors", myName.c_str(), myList.size());
for (it = myList.begin();
it != myList.end();
it++)
{
functor = (*it).second;
if (functor == NULL)
continue;
if(myLogging)
{
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(myLogLevel, "%s: Calling functor '%s' at %d",
myName.c_str(), functor->getName(), -(*it).first);
else
ArLog::log(myLogLevel, "%s: Calling unnamed functor at %d",
myName.c_str(), -(*it).first);
}
functor->invoke();
}
if(myLogging)
ArLog::log(myLogLevel, "%s: Ended calls", myName.c_str());
if (mySingleShot)
{
if(myLogging)
ArLog::log(myLogLevel, "%s: Clearing callbacks", myName.c_str());
myList.clear();
}
myDataMutex.unlock();
}
protected:
};
/** @copydoc ArCallbackList */
template<class P1>
class ArCallbackList1 : public ArGenericCallbackList<ArFunctor1<P1> *>
{
public:
/// Constructor
ArCallbackList1(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false) :
ArGenericCallbackList<ArFunctor1<P1> *>(name, logLevel, singleShot)
{
}
/// Destructor
virtual ~ArCallbackList1()
{
}
/// Calls the callback list
void invoke(P1 p1)
{
ArGenericCallbackList<ArFunctor1<P1> *>::myDataMutex.lock();
typename std::multimap<int, ArFunctor1<P1> *>::iterator it;
ArFunctor1<P1> *functor;
if(ArGenericCallbackList<ArFunctor1<P1> *>::myLogging)
ArLog::log(
ArGenericCallbackList<ArFunctor1<P1> *>::myLogLevel,
"%s: Starting calls to %d functors",
ArGenericCallbackList<ArFunctor1<P1> *>::myName.c_str(),
ArGenericCallbackList<ArFunctor1<P1> *>::myList.size());
for (it = ArGenericCallbackList<ArFunctor1<P1> *>::myList.begin();
it != ArGenericCallbackList<ArFunctor1<P1> *>::myList.end();
it++)
{
functor = (*it).second;
if (functor == NULL)
continue;
if(ArGenericCallbackList<ArFunctor1<P1> *>::myLogging)
{
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(ArGenericCallbackList<ArFunctor1<P1> *>::myLogLevel,
"%s: Calling functor '%s' at %d",
ArGenericCallbackList<ArFunctor1<P1> *>::myName.c_str(),
functor->getName(), -(*it).first);
else
ArLog::log(ArGenericCallbackList<ArFunctor1<P1> *>::myLogLevel,
"%s: Calling unnamed functor at %d",
ArGenericCallbackList<ArFunctor1<P1> *>::myName.c_str(),
-(*it).first);
}
functor->invoke(p1);
}
if(ArGenericCallbackList<ArFunctor1<P1> *>::myLogging)
ArLog::log(ArGenericCallbackList<ArFunctor1<P1> *>::myLogLevel, "%s: Ended calls", ArGenericCallbackList<ArFunctor1<P1> *>::myName.c_str());
if (ArGenericCallbackList<ArFunctor1<P1> *>::mySingleShot)
{
if(ArGenericCallbackList<ArFunctor1<P1> *>::myLogging)
ArLog::log(ArGenericCallbackList<ArFunctor1<P1> *>::myLogLevel,
"%s: Clearing callbacks",
ArGenericCallbackList<ArFunctor1<P1> *>::myName.c_str());
ArGenericCallbackList<ArFunctor1<P1> *>::myList.clear();
}
ArGenericCallbackList<ArFunctor1<P1> *>::myDataMutex.unlock();
}
protected:
};
/** @copydoc ArCallbackList */
template<class P1, class P2>
class ArCallbackList2 : public ArGenericCallbackList<ArFunctor2<P1, P2> *>
{
public:
typedef ArFunctor2<P1, P2> FunctorType;
typedef ArGenericCallbackList<FunctorType*> Super;
ArCallbackList2(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false) :
Super(name, logLevel, singleShot)
{
}
void invoke(P1 p1, P2 p2)
{
Super::myDataMutex.lock();
typename std::multimap<int, FunctorType*>::iterator it;
FunctorType *functor;
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Starting calls to %d functors", Super::myName.c_str(), Super::myList.size());
for (it = Super::myList.begin(); it != Super::myList.end(); ++it)
{
functor = (*it).second;
if (functor == NULL)
continue;
if(Super::myLogging)
{
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(Super::myLogLevel, "%s: Calling functor '%s' at %d", Super::myName.c_str(), functor->getName(), -(*it).first);
else
ArLog::log(Super::myLogLevel, "%s: Calling unnamed functor at %d", Super::myName.c_str(), -(*it).first);
}
functor->invoke(p1, p2);
}
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Ended calls", Super::myName.c_str());
if (Super::mySingleShot)
{
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Clearing callbacks", Super::myName.c_str()); Super::myList.clear();
}
Super::myDataMutex.unlock();
}
};
/** @copydoc ArCallbackList */
template<class P1, class P2, class P3>
class ArCallbackList3 : public ArGenericCallbackList<ArFunctor3<P1, P2, P3> *>
{
public:
typedef ArFunctor3<P1, P2, P3> FunctorType;
typedef ArGenericCallbackList<FunctorType*> Super;
ArCallbackList3(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false) :
Super(name, logLevel, singleShot)
{
}
void invoke(P1 p1, P2 p2, P3 p3)
{
Super::myDataMutex.lock();
typename std::multimap<int, FunctorType*>::iterator it;
FunctorType *functor;
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Starting calls to %d functors", Super::myName.c_str(), Super::myList.size());
for (it = Super::myList.begin(); it != Super::myList.end(); ++it)
{
functor = (*it).second;
if (functor == NULL)
continue;
if(Super::myLogging)
{
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(Super::myLogLevel, "%s: Calling functor '%s' at %d", Super::myName.c_str(), functor->getName(), -(*it).first);
else
ArLog::log(Super::myLogLevel, "%s: Calling unnamed functor at %d", Super::myName.c_str(), -(*it).first);
}
functor->invoke(p1, p2, p3);
}
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Ended calls", Super::myName.c_str());
if (Super::mySingleShot)
{
if(Super::myLogging)
ArLog::log(Super::myLogLevel, "%s: Clearing callbacks", Super::myName.c_str()); Super::myList.clear();
}
Super::myDataMutex.unlock();
}
};
/** @copydoc ArCallbackList */
template<class P1, class P2, class P3, class P4>
class ArCallbackList4 : public ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4>*>
{
public:
ArCallbackList4(const char *name = "",
ArLog::LogLevel logLevel = ArLog::Verbose,
bool singleShot = false) :
ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>(name, logLevel, singleShot)
{
}
virtual ~ArCallbackList4()
{
}
void invoke(P1 p1, P2 p2, P3 p3, P4 p4)
{
// references to members of parent class for clarity below
ArMutex &mutex = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::myDataMutex;
ArLog::LogLevel &loglevel = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::myLogLevel;
const char *name = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::myName.c_str();
std::multimap< int, ArFunctor4<P1, P2, P3, P4>* > &list = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::myList;
bool &singleshot = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::mySingleShot;
bool &logging = ArGenericCallbackList<ArFunctor4<P1, P2, P3, P4> *>::myLogging;
mutex.lock();
typename std::multimap<int, ArFunctor4<P1, P2, P3, P4> *>::iterator it;
ArFunctor4<P1, P2, P3, P4> *functor;
if(logging)
ArLog::log( loglevel, "%s: Starting calls to %d functors", name, list.size());
for (it = list.begin(); it != list.end(); ++it)
{
functor = (*it).second;
if (functor == NULL)
continue;
if(logging)
{
if (functor->getName() != NULL && functor->getName()[0] != '\0')
ArLog::log(loglevel, "%s: Calling functor '%s' (0x%x) at %d", name, functor->getName(), functor, -(*it).first);
else
ArLog::log(loglevel, "%s: Calling unnamed functor (0x%x) at %d", name, functor, -(*it).first);
}
functor->invoke(p1, p2, p3, p4);
}
if(logging)
ArLog::log(loglevel, "%s: Ended calls", name);
if (singleshot)
{
if(logging)
ArLog::log(loglevel, "%s: Clearing callbacks", name);
list.clear();
}
mutex.unlock();
}
};
#ifndef ARINTERFACE
#ifndef SWIG
/// @internal
class ArLaserCreatorHelper
{
public:
/// Creates an ArLMS2xx
static ArLaser *createLMS2xx(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArLMS2xx
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateLMS2xxCB(void);
/// Creates an ArUrg
static ArLaser *createUrg(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArUrg
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateUrgCB(void);
/// Creates an ArLMS1XX
static ArLaser *createLMS1XX(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArLMS1XX
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateLMS1XXCB(void);
/// Creates an ArUrg using SCIP 2.0
static ArLaser *createUrg_2_0(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArUrg
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateUrg_2_0CB(void);
/// Creates an ArS3Series
static ArLaser *createS3Series(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArS3Series
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateS3SeriesCB(void);
/// Creates an ArLMS5XX
static ArLaser *createLMS5XX(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArLMS5XX
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateLMS5XXCB(void);
/// Creates an ArTiM3XX
static ArLaser *createTiM3XX(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArTiM3XX
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateTiM3XXCB(void);
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateTiM551CB(void);
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateTiM561CB(void);
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateTiM571CB(void);
/// Creates an ArSZSeries
static ArLaser *createSZSeries(int laserNumber, const char *logPrefix);
/// Gets functor for creating an ArSZSeries
static ArRetFunctor2<ArLaser *, int, const char *> *getCreateSZSeriesCB(void);
protected:
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourLMS2xxCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourUrgCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourLMS1XXCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourUrg_2_0CB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourS3SeriesCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourLMS5XXCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourTiM3XXCB;
static ArGlobalRetFunctor2<ArLaser *, int, const char *> ourSZSeriesCB;
};
/// @internal
class ArBatteryMTXCreatorHelper
{
public:
/// Creates an ArBatteryMTX
static ArBatteryMTX *createBatteryMTX(int batteryNumber, const char *logPrefix);
/// Gets functor for creating an ArBatteryMTX
static ArRetFunctor2<ArBatteryMTX *, int, const char *> *getCreateBatteryMTXCB(void);
protected:
static ArGlobalRetFunctor2<ArBatteryMTX *, int, const char *> ourBatteryMTXCB;
};
/// @internal
class ArLCDMTXCreatorHelper
{
public:
/// Creates an ArLCDMTX
static ArLCDMTX *createLCDMTX(int lcdNumber, const char *logPrefix);
/// Gets functor for creating an ArLCDMTX
static ArRetFunctor2<ArLCDMTX *, int, const char *> *getCreateLCDMTXCB(void);
protected:
static ArGlobalRetFunctor2<ArLCDMTX *, int, const char *> ourLCDMTXCB;
};
/// @internal
class ArSonarMTXCreatorHelper
{
public:
/// Creates an ArSonarMTX
static ArSonarMTX *createSonarMTX(int sonarNumber, const char *logPrefix);
/// Gets functor for creating an ArSonarMTX
static ArRetFunctor2<ArSonarMTX *, int, const char *> *getCreateSonarMTXCB(void);
protected:
static ArGlobalRetFunctor2<ArSonarMTX *, int, const char *> ourSonarMTXCB;
};
#endif // SWIG
#endif // ARINTERFACE
#ifndef SWIG
/// @internal
class ArDeviceConnectionCreatorHelper
{
public:
/// Creates an ArSerialConnection
static ArDeviceConnection *createSerialConnection(
const char *port, const char *defaultInfo, const char *logPrefix);
/// Gets functor for creating an ArSerialConnection
static ArRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> *getCreateSerialCB(void);
/// Creates an ArTcpConnection
static ArDeviceConnection *createTcpConnection(
const char *port, const char *defaultInfo, const char *logPrefix);
/// Gets functor for creating an ArTcpConnection
static ArRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> *getCreateTcpCB(void);
/// Creates an ArSerialConnection for RS422
static ArDeviceConnection *createSerial422Connection(
const char *port, const char *defaultInfo, const char *logPrefix);
/// Gets functor for creating an ArSerialConnection
static ArRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> *getCreateSerial422CB(void);
/// Sets the success log level
static void setSuccessLogLevel(ArLog::LogLevel successLogLevel);
/// Sets the success log level
static ArLog::LogLevel setSuccessLogLevel(void);
protected:
/// Internal Create ArSerialConnection
static ArDeviceConnection *internalCreateSerialConnection(
const char *port, const char *defaultInfo, const char *logPrefix, bool is422);
static ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> ourSerialCB;
static ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> ourTcpCB;
static ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *,
const char *> ourSerial422CB;
static ArLog::LogLevel ourSuccessLogLevel;
};
#endif // SWIG
/// Class for finding robot bounds from the basic measurements
class ArPoseUtil
{
public:
AREXPORT static std::list<ArPose> findCornersFromRobotBounds(
double radius, double widthLeft, double widthRight,
double lengthFront, double lengthRear, bool fastButUnsafe);
AREXPORT static std::list<ArPose> breakUpDistanceEvenly(ArPose start, ArPose end,
int resolution);
};
/// class for checking if something took too long and logging it
class ArTimeChecker
{
public:
/// Constructor
AREXPORT ArTimeChecker(const char *name = "Unknown", int defaultMSecs = 100);
/// Destructor
AREXPORT virtual ~ArTimeChecker();
/// Sets the name
void setName(const char *name) { myName = name; }
/// Sets the default mSecs
void setDefaultMSecs(int defaultMSecs) { myMSecs = defaultMSecs; }
/// starts the check
AREXPORT void start(void);
/// checks, optionally with a subname (only one subname logged per cycle)
AREXPORT void check(const char *subName);
/// Finishes the check
AREXPORT void finish(void);
/// Gets the last time a check happened (a start counts as a check too)
ArTime getLastCheckTime() { return myLastCheck; }
protected:
std::string myName;
int myMSecs;
ArTime myStarted;
ArTime myLastCheck;
};
#endif // ARIAUTIL_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArRobotTypes.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARROBOTTYPES_H
#define ARROBOTTYPES_H
#include "ariaUtil.h"
#include "ArRobotParams.h"
/** @cond INCLUDE_INTERNAL_ROBOT_PARAM_CLASSES */
class ArRobotGeneric : public ArRobotParams
{
public:
AREXPORT ArRobotGeneric(const char *dir="");
AREXPORT virtual ~ArRobotGeneric() {}
};
class ArRobotAmigo : public ArRobotParams
{
public:
AREXPORT ArRobotAmigo(const char *dir="");
AREXPORT virtual ~ArRobotAmigo() {}
};
class ArRobotAmigoSh : public ArRobotParams
{
public:
AREXPORT ArRobotAmigoSh(const char *dir="");
AREXPORT virtual ~ArRobotAmigoSh() {}
};
class ArRobotAmigoShTim5xxWibox : public ArRobotAmigoSh
{
public:
AREXPORT ArRobotAmigoShTim5xxWibox(const char *dir="");
AREXPORT virtual ~ArRobotAmigoShTim5xxWibox() {}
};
class ArRobotP2AT : public ArRobotParams
{
public:
AREXPORT ArRobotP2AT(const char *dir="");
AREXPORT virtual ~ArRobotP2AT() {}
};
class ArRobotP2AT8 : public ArRobotParams
{
public:
AREXPORT ArRobotP2AT8(const char *dir="");
AREXPORT virtual ~ArRobotP2AT8() {}
};
class ArRobotP2AT8Plus : public ArRobotParams
{
public:
AREXPORT ArRobotP2AT8Plus(const char *dir="");
AREXPORT virtual ~ArRobotP2AT8Plus() {}
};
class ArRobotP2IT : public ArRobotParams
{
public:
AREXPORT ArRobotP2IT(const char *dir="");
AREXPORT virtual ~ArRobotP2IT() {}
};
class ArRobotP2DX : public ArRobotParams
{
public:
AREXPORT ArRobotP2DX(const char *dir="");
AREXPORT virtual ~ArRobotP2DX() {}
};
class ArRobotP2DXe : public ArRobotParams
{
public:
AREXPORT ArRobotP2DXe(const char *dir="");
AREXPORT virtual ~ArRobotP2DXe() {}
};
class ArRobotP2DF : public ArRobotParams
{
public:
AREXPORT ArRobotP2DF(const char *dir="");
AREXPORT virtual ~ArRobotP2DF() {}
};
class ArRobotP2D8 : public ArRobotParams
{
public:
AREXPORT ArRobotP2D8(const char *dir="");
AREXPORT virtual ~ArRobotP2D8() {}
};
class ArRobotP2D8Plus : public ArRobotParams
{
public:
AREXPORT ArRobotP2D8Plus(const char *dir="");
AREXPORT virtual ~ArRobotP2D8Plus() {}
};
class ArRobotP2CE : public ArRobotParams
{
public:
AREXPORT ArRobotP2CE(const char *dir="");
AREXPORT virtual ~ArRobotP2CE() {}
};
class ArRobotP2PP : public ArRobotParams
{
public:
AREXPORT ArRobotP2PP(const char *dir="");
AREXPORT virtual ~ArRobotP2PP() {}
};
class ArRobotP2PB : public ArRobotParams
{
public:
AREXPORT ArRobotP2PB(const char *dir="");
AREXPORT virtual ~ArRobotP2PB() {}
};
class ArRobotP3AT : public ArRobotParams
{
public:
AREXPORT ArRobotP3AT(const char *dir="");
AREXPORT virtual ~ArRobotP3AT() {}
};
class ArRobotP3DX : public ArRobotParams
{
public:
AREXPORT ArRobotP3DX(const char *dir="");
AREXPORT virtual ~ArRobotP3DX() {}
};
class ArRobotPerfPB : public ArRobotParams
{
public:
AREXPORT ArRobotPerfPB(const char *dir="");
AREXPORT virtual ~ArRobotPerfPB() {}
};
class ArRobotPerfPBPlus : public ArRobotParams
{
public:
AREXPORT ArRobotPerfPBPlus(const char *dir="");
AREXPORT virtual ~ArRobotPerfPBPlus() {}
};
class ArRobotPion1M : public ArRobotParams
{
public:
AREXPORT ArRobotPion1M(const char *dir="");
AREXPORT virtual ~ArRobotPion1M() {}
};
class ArRobotPion1X : public ArRobotParams
{
public:
AREXPORT ArRobotPion1X(const char *dir="");
AREXPORT virtual ~ArRobotPion1X() {}
};
class ArRobotPsos1M : public ArRobotParams
{
public:
AREXPORT ArRobotPsos1M(const char *dir="");
AREXPORT virtual ~ArRobotPsos1M() {}
};
class ArRobotPsos43M : public ArRobotParams
{
public:
AREXPORT ArRobotPsos43M(const char *dir="");
AREXPORT virtual ~ArRobotPsos43M() {}
};
class ArRobotPsos1X : public ArRobotParams
{
public:
AREXPORT ArRobotPsos1X(const char *dir="");
AREXPORT virtual ~ArRobotPsos1X() {}
};
class ArRobotPionAT : public ArRobotParams
{
public:
AREXPORT ArRobotPionAT(const char *dir="");
AREXPORT virtual ~ArRobotPionAT() {}
};
class ArRobotMapper : public ArRobotParams
{
public:
AREXPORT ArRobotMapper(const char *dir="");
AREXPORT virtual ~ArRobotMapper() {}
};
class ArRobotPowerBot : public ArRobotParams
{
public:
AREXPORT ArRobotPowerBot(const char *dir="");
AREXPORT virtual ~ArRobotPowerBot() {}
};
class ArRobotP3DXSH : public ArRobotParams
{
public:
AREXPORT ArRobotP3DXSH(const char *dir="");
AREXPORT virtual ~ArRobotP3DXSH() {}
};
class ArRobotP3ATSH : public ArRobotParams
{
public:
AREXPORT ArRobotP3ATSH(const char *dir="");
AREXPORT virtual ~ArRobotP3ATSH() {}
};
class ArRobotP3ATIWSH : public ArRobotParams
{
public:
AREXPORT ArRobotP3ATIWSH(const char *dir="");
AREXPORT virtual ~ArRobotP3ATIWSH() {}
};
class ArRobotPatrolBotSH : public ArRobotParams
{
public:
AREXPORT ArRobotPatrolBotSH(const char *dir="");
AREXPORT virtual ~ArRobotPatrolBotSH() {}
};
class ArRobotPeopleBotSH : public ArRobotParams
{
public:
AREXPORT ArRobotPeopleBotSH(const char *dir="");
AREXPORT virtual ~ArRobotPeopleBotSH() {}
};
class ArRobotPowerBotSH : public ArRobotParams
{
public:
AREXPORT ArRobotPowerBotSH(const char *dir="");
AREXPORT virtual ~ArRobotPowerBotSH() {}
};
class ArRobotWheelchairSH : public ArRobotParams
{
public:
AREXPORT ArRobotWheelchairSH(const char *dir="");
AREXPORT virtual ~ArRobotWheelchairSH() {}
};
class ArRobotPowerBotSHuARCS : public ArRobotParams
{
public:
AREXPORT ArRobotPowerBotSHuARCS(const char *dir="");
AREXPORT virtual ~ArRobotPowerBotSHuARCS() {}
};
class ArRobotSeekur : public ArRobotParams
{
public:
AREXPORT ArRobotSeekur(const char *dir="");
AREXPORT virtual ~ArRobotSeekur() {}
};
/// @since Aria 2.7.2
class ArRobotMT400 : public ArRobotParams
{
public:
AREXPORT ArRobotMT400(const char *dir="");
AREXPORT virtual ~ArRobotMT400() {}
};
/// @since Aria 2.7.2
class ArRobotResearchPB : public ArRobotParams
{
public:
AREXPORT ArRobotResearchPB(const char *dir="");
AREXPORT virtual ~ArRobotResearchPB() {}
};
/// @since Aria 2.7.2
class ArRobotSeekurJr : public ArRobotParams
{
public:
AREXPORT ArRobotSeekurJr(const char *dir="");
AREXPORT virtual ~ArRobotSeekurJr() {}
};
/// @since Aria 2.7.4
class ArRobotP3DXSH_lms1xx : public ArRobotP3DXSH
{
public:
AREXPORT ArRobotP3DXSH_lms1xx(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotP3ATSH_lms1xx : public ArRobotP3ATSH
{
public:
AREXPORT ArRobotP3ATSH_lms1xx(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotPeopleBotSH_lms1xx : public ArRobotPeopleBotSH
{
public:
AREXPORT ArRobotPeopleBotSH_lms1xx(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotP3DXSH_lms500 : public ArRobotP3DXSH
{
public:
AREXPORT ArRobotP3DXSH_lms500(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotP3ATSH_lms500 : public ArRobotP3ATSH
{
public:
AREXPORT ArRobotP3ATSH_lms500(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotPeopleBotSH_lms500 : public ArRobotPeopleBotSH
{
public:
AREXPORT ArRobotPeopleBotSH_lms500(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotPowerBotSH_lms500 : public ArRobotPowerBotSH
{
public:
AREXPORT ArRobotPowerBotSH_lms500(const char *dir="");
};
/// @since Aria 2.7.4
class ArRobotResearchPB_lms500 : public ArRobotResearchPB
{
public:
AREXPORT ArRobotResearchPB_lms500(const char *dir="");
};
/// @since Aria 2.8
class ArRobotPioneerLX : public ArRobotParams
{
public:
AREXPORT ArRobotPioneerLX(const char *dir="");
AREXPORT virtual ~ArRobotPioneerLX() {}
};
/** @endcond INCLUDE_INTERNAL_ROBOT_PARAM_CLASSES */
#endif // ARROBOTTYPES_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionDriveDistance.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System<gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONDRIVEDISTANCE_H
#define ARACTIONDRIVEDISTANCE_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArAction.h"
/// This action drives the robot specific distances
/**
This action naively drives a fixed distance. The action stops the
robot when it has travelled the appropriate distance. It
travels at 'speed' mm/sec.
You can give it a distance with setDistance(), cancel its movement
with cancelDistance(), and see if it got there with
haveAchievedDistance().
You can tell it to go backwards by calling setDistance with a
negative value.
This doesn't avoid obstacles or anything, you could add have an
limiting ArAction at a higher priority to try to do this (so you
don't smash things). (For truly intelligent navigation, see
the ARNL or SONARNL software libraries.)
@ingroup ActionClasses
**/
class ArActionDriveDistance : public ArAction
{
public:
AREXPORT ArActionDriveDistance(const char *name = "driveDistance",
double speed = 400, double deceleration = 200);
AREXPORT virtual ~ArActionDriveDistance();
/// Sees if the goal has been achieved
AREXPORT bool haveAchievedDistance(void);
/// Cancels the goal the robot has
AREXPORT void cancelDistance(void);
/// Sets a new goal and sets the action to go there
AREXPORT void setDistance(double distance, bool useEncoders = true);
/// Gets whether we're using the encoder position or the normal position
bool usingEncoders(void) { return myUseEncoders; }
/// Sets the speed the action will travel at (mm/sec)
void setSpeed(double speed = 400) { mySpeed = speed; }
/// Gets the speed the action will travel at (mm/sec)
double getSpeed(void) { return mySpeed; }
/// Sets the deceleration the action will use (mm/sec/sec)
void setDeceleration(double deceleration = 200)
{ myDeceleration = deceleration; }
/// Gets the deceleration the action will use (mm/sec/sec)
double getDeceleration(void) { return myDeceleration; }
/// Sets if we're printing or not
void setPrinting(bool printing) { myPrinting = printing; }
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
double myDistance;
bool myUseEncoders;
double mySpeed;
double myDeceleration;
ArActionDesired myDesired;
bool myPrinting;
double myLastVel;
double myDistTravelled;
ArPose myLastPose;
enum State
{
STATE_NO_DISTANCE,
STATE_ACHIEVED_DISTANCE,
STATE_GOING_DISTANCE
};
State myState;
};
#endif // ARACTIONDRIVE
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionLimiterRot.h | <filename>Aria/ArActionLimiterRot.h<gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONLIMITERROT_H
#define ARACTIONLIMITERROT_H
#include "ariaTypedefs.h"
#include "ArAction.h"
/// Action to limit the forwards motion of the robot based on range sensor readings
/**
This action uses the robot's range sensors (e.g. sonar, laser) to find a
maximum speed at which to travel
and will increase the deceleration so that the robot doesn't hit
anything. If it has to, it will trigger an estop to avoid a
collision.
Note that this cranks up the deceleration with a strong strength,
but it checks to see if there is already something decelerating
more strongly... so you can put these actions lower in the priority list so
things will play together nicely.
@ingroup ActionClasses
**/
class ArActionLimiterRot : public ArAction
{
public:
/// Constructor
AREXPORT ArActionLimiterRot(const char *name = "limitRot");
/// Destructor
AREXPORT virtual ~ArActionLimiterRot();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
/// Sets the parameters (don't use this if you're using the addToConfig)
AREXPORT void setParameters(bool checkRadius = false,
double inRadiusSpeed = 0);
/// Adds to the ArConfig given, in section, with prefix
AREXPORT void addToConfig(ArConfig *config, const char *section,
const char *prefix = NULL);
/// Sets if we're using locationDependent range devices or not
bool getUseLocationDependentDevices(void)
{ return myUseLocationDependentDevices; }
/// Sets if we're using locationDependent range devices or not
void setUseLocationDependentDevices(bool useLocationDependentDevices)
{ myUseLocationDependentDevices = useLocationDependentDevices; }
protected:
bool myCheckRadius;
double myInRadiusSpeed;
bool myUseLocationDependentDevices;
ArActionDesired myDesired;
};
#endif // ARACTIONSPEEDLIMITER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArBumpers.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARBUMPERS_H
#define ARBUMPERS_H
#include "ariaTypedefs.h"
#include "ArRangeDevice.h"
/// A class that treats the robot's bumpers as a range device.
/**
The class treats bumpers like a range device. When a bumper
is bumped, it reports the approximate position of the bump
in a buffer. The positions are kept current for a specified
length of time.
@ingroup DeviceClasses
*/
class ArBumpers : public ArRangeDevice
{
public:
AREXPORT ArBumpers(size_t currentBufferSize = 30,
size_t cumulativeBufferSize = 30,
const char *name = "bumpers",
int maxSecondsToKeepCurrent = 15,
double angleRange = 135);
AREXPORT virtual ~ArBumpers(void);
AREXPORT virtual void setRobot(ArRobot *robot);
AREXPORT void processReadings(void);
AREXPORT void addBumpToBuffer(int bumpValue, int whichBumper);
protected:
ArFunctorC<ArBumpers> myProcessCB;
ArRobot *myRobot;
int myBumpMask;
double myAngleRange;
};
#endif // ARBUMPERS_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArPTZ.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARPTZ_H
#define ARPTZ_H
#include "ariaTypedefs.h"
#include "ArFunctor.h"
#include "ArCommands.h"
#include "ArPTZConnector.h"
class ArRobot;
class ArBasePacket;
class ArRobotPacket;
class ArDeviceConnection;
/// Base class which handles the PTZ cameras
/**
This class is mainly concerned with making all the cameras look
the same for outgoing data, it is also set up to facilitate the
acquisition of incoming data but that is described in the
following paragraphs. There are two ways this can be used. The
first is the simplest and default behavior and should be used by
those whose cameras are attached to their robot's microcontroller,
a ArRobot pointer is passed in to the contructor, this is where
the commands will be sent to the robot via the robot's connection
which will then send it along over the second serial port. The
second way is to pass an ArDeviceConnection to
setDeviceConnection, if this is done commands will be sent along
the given serial port, this should ONLY be done if the camera is
attached straight to a serial port on the computer this program is
running on.
The next two paragraphs describe how to get data back from the
cameras, but this base class is set up so that by default it won't
try to get data back and assumes you're not trying to do that. If
you are trying to get data back the important functions are
packetHandler, robotPacketHandler and readPacket and you should
read the docs on those.
If the camera is attached to the robot (and you are thus using the
first method described in the first paragraph) then the only way
to get data back is to send an ArCommands::GETAUX, then set up a
robotPacketHandler for the AUX id and have it call the
packetHandler you set up in in the class.
If the camera is attached to the serial port on the computer (and
thus the second method described in the first paragraph was used)
then its more complicated... the default way is to just pass in an
ArDeviceConnection to setDeviceConnection and implement the
readPacket method (which MUST not block), and every time through
the robot loop readPacket (with the sensorInterpHandler) will be
called and any packets will be given to the packetHandler (which
you need to implement in your class) to be processed. The other
way to do this method is to pass both an ArDefaultConnection and
false to setDeviceConnection, this means the camera will not be
read at all by default, and you're on your own for reading the
data in (ie like your own thread).
@ingroup OptionalClasses
@ingroup DeviceClasses
@todo add functions (optional to implement): power on/off, isReady/isInitialized, slew
**/
class ArPTZ
{
public:
AREXPORT ArPTZ(ArRobot *robot);
/// Destructor
AREXPORT virtual ~ArPTZ();
/// Initializes the camera
AREXPORT virtual bool init(void) = 0;
/// Return name of this PTZ type
AREXPORT virtual const char *getTypeName() = 0;
/// Resets the camera
/**
This function will reset the camera to 0 0 pan tilt, and 0 zoom,
on some cameras that can get out of sync it may need to do more,
such as call init on it again.
**/
AREXPORT virtual void reset(void)
{ panTilt(0, 0); if (canZoom()) zoom(getMinZoom()); }
/// Pans to the given degrees. 0 is straight ahead, - is to the left, + to the right
virtual bool pan(double degrees)
{
if(myInverted) {
return pan_i(-degrees);
} else {
return pan_i(degrees);
}
}
/// Pans relative to current position by given degrees
virtual bool panRel(double degrees) { if(myInverted) return panRel_i(-degrees); else return panRel_i(degrees); }
/// Tilts to the given degrees. 0 is middle, - is downward, + is upwards.
virtual bool tilt(double degrees) { if(myInverted) return tilt_i(-degrees); else return tilt_i(degrees); }
/// Tilts relative to the current position by given degrees
virtual bool tiltRel(double degrees) { if(myInverted) return tiltRel_i(-degrees); else return tiltRel_i(degrees); }
/// Pans and tilts to the given degrees
virtual bool panTilt(double degreesPan, double degreesTilt) { if(myInverted) return panTilt_i(-degreesPan, -degreesTilt); else return panTilt_i(degreesPan, degreesTilt); }
/// Pans and tilts relatives to the current position by the given degrees
virtual bool panTiltRel(double degreesPan, double degreesTilt) { if(myInverted) return panTiltRel_i(-degreesPan, -degreesTilt); else return panTiltRel_i(degreesPan, degreesTilt); }
/// Returns true if camera can zoom and this class can control the zoom amount
AREXPORT virtual bool canZoom(void) const = 0;
/// Zooms to the given value
AREXPORT virtual bool zoom(int zoomValue) { return false; }
/// Zooms relative to the current value, by the given value
AREXPORT virtual bool zoomRel(int zoomValue) { return false; }
/** The angle the camera is panned to (or last commanded value sent, if unable to obtain real pan position)
@sa canGetRealPanTilt()
*/
virtual double getPan(void) const { if(myInverted) return -getPan_i(); else return getPan_i(); }
/** The angle the camera is tilted to (or last commanded value sent, if unable to obtain real pan position)
@sa canGetRealPanTilt()
*/
virtual double getTilt(void) const { if(myInverted) return -getTilt_i(); else return getTilt_i(); }
/** The amount the camera is zoomed to (or last commanded value sent,
if unable to obtain real pan position)
@sa canZoom();
@sa canGetZoom()
*/
AREXPORT virtual int getZoom(void) const { return 0; }
/// Whether getPan() hand getTilt() return the device's real position, or last commanded position.
AREXPORT virtual bool canGetRealPanTilt(void) const { return false; }
/// Whether getZoom() returns the device's real zoom amount, or last commanded zoom position.
AREXPORT virtual bool canGetRealZoom(void) const { return false; }
/// Gets the highest positive degree the camera can pan to (inverted if camera is inverted)
virtual double getMaxPosPan(void) const { if (myInverted) return -myMaxPosPan; else return myMaxPosPan; }
/// @copydoc getMaxPosPan()
double getMaxPan() const { return getMaxPosPan(); }
/// Gets the lowest negative degree the camera can pan to (inverted if camera is inverted)
virtual double getMaxNegPan(void) const { if (myInverted) return -myMaxNegPan; else return myMaxNegPan; }
/// @copydoc getMaxNegPan()
double getMinPan() const { return getMaxNegPan(); }
/// Gets the highest positive degree the camera can tilt to (inverted if camera is inverted)
virtual double getMaxPosTilt(void) const { if (myInverted) return -myMaxPosTilt; else return myMaxPosTilt; }
/// @copydoc getMaxPosTilt()
double getMaxTilt() const { return getMaxPosTilt(); }
/// Gets the lowest negative degree the camera can tilt to (inverted if camera is inverted)
virtual double getMaxNegTilt(void) const { if (myInverted) return -myMaxNegTilt; else return myMaxNegTilt; }
///@copydoc getMaxNegTilt()
double getMinTilt() const { return getMaxNegTilt(); }
/// Halt any pan/tilt movement, if device supports it
virtual bool haltPanTilt() { return false; };
/// Halt any zoom movement, if device supports that
virtual bool haltZoom() { return false; }
/// Can pan and tilt speed (slew rates) be set to move device?
virtual bool canPanTiltSlew() { return false; }
/// @copydoc canPanTiltSlew()
bool canSetSpeed() { return canPanTiltSlew(); }
/// Set pan slew rate (speed) (degrees/sec) if device supports it (see canPanTiltSlew())
virtual bool panSlew(double s) { return false; }
/// @copydoc panSlew()
bool setPanSpeed(double s) { return panSlew(s); }
/// Set tilt slew rate (speed) (degrees/sec) if device supports it (see canPanTiltSlew())
virtual bool tiltSlew(double s) { return false; }
/// @copydoc tiltSlew()
bool setTiltSpeed(double s) { return tiltSlew(s); }
/// Maximum pan speed (slew rate) (degrees/sec) if device supports, or 0 if not.
virtual double getMaxPanSpeed() { return 0.0; }
/// Maximum tilt speed (slew rate) (degrees/sec) if device supports it, or 0 if not.
virtual double getMaxTiltSpeed() { return 0.0; }
protected:
/// Versions of the pan and tilt limit accessors where inversion is not applied, for use by subclasses to check when given pan/tilt commands.
/// @todo limits checking should be done in ArPTZ pan(), tilt() and panTilt() public interface methods instead of in each implementation
//@{
virtual double getMaxPosPan_i(void) const { return myMaxPosPan; }
double getMaxPan_i() const { return getMaxPosPan_i(); }
virtual double getMaxPosTilt_i(void) const { return myMaxPosTilt; }
double getMinPan_i() const { return getMaxNegPan_i(); }
virtual double getMaxNegPan_i(void) const { return myMaxNegPan; }
double getMaxTilt_i() const { return getMaxPosTilt_i(); }
virtual double getMaxNegTilt_i(void) const { return myMaxNegTilt; }
double getMinTilt_i() const { return getMaxNegTilt_i(); }
//@}
public:
/// Gets the maximum value for the zoom on this camera
virtual int getMaxZoom(void) const { if (myInverted) return -myMaxZoom; else return myMaxZoom; }
/// Gets the lowest value for the zoom on this camera
virtual int getMinZoom(void) const { if (myInverted) return -myMinZoom; else return myMinZoom; }
/// Whether we can get the FOV (field of view) or not
virtual bool canGetFOV(void) { return false; }
/// Gets the field of view at maximum zoom
AREXPORT virtual double getFOVAtMaxZoom(void) { return 0; }
/// Gets the field of view at minimum zoom
AREXPORT virtual double getFOVAtMinZoom(void) { return 0; }
/// Set gain on camera, range of 1-100. Returns false if out of range
/// or if you can't set the gain on the camera
AREXPORT virtual bool setGain(double gain) const { return false; }
/// Get the gain the camera is set to. 0 if not supported
AREXPORT virtual double getGain(double gain) const { return 0; }
/// If the driver can set gain on the camera, or not
AREXPORT virtual bool canSetGain(void) const { return false; }
/// Set focus on camera, range of 1-100. Returns false if out of range
/// or if you can't set the focus on the camera
AREXPORT virtual bool setFocus(double focus) const { return false; }
/// Get the focus the camera is set to. 0 if not supported
AREXPORT virtual double getFocus(double focus) const { return 0; }
/// If the driver can set the focus on the camera, or not
AREXPORT virtual bool canSetFocus(void) const { return false; }
/// Disable/enable autofocus mode if possible. Return false if can't change autofocus mode.
AREXPORT virtual bool setAutoFocus(bool af = true) { return false; }
/// Set whether the camera is inverted (upside down). If true, pan and tilt axes will be reversed.
void setInverted(bool inv) { myInverted = inv; }
/// Get whether the camera is inverted (upside down). If true, pan and tilt axes will be reversed.
bool getInverted() { return myInverted; }
/// Sets the device connection to be used by this PTZ camera, if set
/// this camera will send commands via this connection, otherwise
/// its via robot aux. serial port (see setAuxPortt())
AREXPORT virtual bool setDeviceConnection(ArDeviceConnection *connection,
bool driveFromRobotLoop = true);
/// Gets the device connection used by this PTZ camera
AREXPORT virtual ArDeviceConnection *getDeviceConnection(void);
/// Sets the aux port on the robot to be used to communicate with this device
AREXPORT virtual bool setAuxPort(int auxPort);
/// Gets the port the device is set to communicate on
AREXPORT virtual int getAuxPort(void) { return myAuxPort; }
/// Reads a packet from the device connection, MUST NOT BLOCK
/**
This should read in a packet from the myConn connection and
return a pointer to a packet if there was on to read in, or NULL
if there wasn't one... this MUST not block if it is used with
the default mode of being driven from the sensorInterpHandler,
since that is on the robot loop.
@return packet read in, or NULL if there was no packet read
**/
AREXPORT virtual ArBasePacket *readPacket(void) { return NULL; }
/// Sends a given packet to the camera (via robot or serial port, depending)
AREXPORT virtual bool sendPacket(ArBasePacket *packet);
/// Handles a packet that was read from the device
/**
This should work for the robot packet handler or for packets read
in from readPacket (the joys of OO), but it can't deal with the
need to check the id on robot packets, so you should check the id
from robotPacketHandler and then call this one so that your stuff
can be used by both robot and serial port connections.
@param packet the packet to handle
@return true if this packet was handled (ie this knows what it
is), false otherwise
**/
AREXPORT virtual bool packetHandler(ArBasePacket *packet) { return false; }
/// Handles a packet that was read by the robot
/**
This handles packets read in from the robot, this function should
just check the ID of the robot packet and then return what
packetHandler thinks of the packet.
@param packet the packet to handle
@return true if the packet was handled (ie this konws what it is),
false otherwise
**/
AREXPORT virtual bool robotPacketHandler(ArRobotPacket *packet);
/// Internal, attached to robot, inits the camera when robot connects
AREXPORT virtual void connectHandler(void);
/// Internal, for attaching to the robots sensor interp to read serial port
AREXPORT virtual void sensorInterpHandler(void);
/// Return ArRobot object this PTZ is associated with. May be NULL
ArRobot *getRobot() { return myRobot; }
/// Set ArRobot object this PTZ is associated with. May be NULL
void setRobot(ArRobot* r) { myRobot = r; }
protected:
ArRobot *myRobot;
ArDeviceConnection *myConn;
ArFunctorC<ArPTZ> myConnectCB;
ArFunctorC<ArPTZ> mySensorInterpCB;
int myAuxPort;
ArCommands::Commands myAuxTxCmd;
ArCommands::Commands myAuxRxCmd;
ArRetFunctor1C<bool, ArPTZ, ArRobotPacket *> myRobotPacketHandlerCB;
bool myInverted;
double myMaxPosPan;
double myMaxNegPan;
double myMaxPosTilt;
double myMaxNegTilt;
int myMaxZoom;
int myMinZoom;
/// Subclasses call this to set extents (limits) returned by getMaxPosPan(), getMaxNegPan(), getMaxPosTilt(), getMaxNegTilt(), getMaxZoom(), and getMinZoom().
/// @since 2.7.6
void setLimits(double maxPosPan, double maxNegPan, double maxPosTilt, double maxNegTilt, int maxZoom = 0, int minZoom = 0)
{
myMaxPosPan = maxPosPan;
myMaxNegPan = maxNegPan;
myMaxPosTilt = maxPosTilt;
myMaxNegTilt = maxNegTilt;
myMaxZoom = maxZoom;
myMinZoom = minZoom;
}
/// Internal implementations by subclasses. Inverted is not applied in these functions, it is done in the public interface above.
/// Note, once execution enters one of these _i methods, then inversion has been
/// applied and no call should be made to any pan/tilt or max/min limit accessor
/// method that does not end in _i, or inversion will be applied again,
/// reversing it.
/// @since 2.7.6
//@{
AREXPORT virtual bool pan_i (double degrees) = 0;
AREXPORT virtual bool panRel_i(double degrees) = 0;
AREXPORT virtual bool tilt_i(double degrees) = 0;
AREXPORT virtual bool tiltRel_i (double degrees) = 0;
AREXPORT virtual bool panTilt_i(double degreesPan, double degreesTilt) = 0;
AREXPORT virtual bool panTiltRel_i(double degreesPan, double degreesTilt) = 0;
AREXPORT virtual double getPan_i(void) const = 0;
AREXPORT virtual double getTilt_i(void) const = 0;
//@}
};
#endif // ARPTZ_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArTaskState.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARTASKSTATE_H
#define ARTASKSTATE_H
/// Class with the different states a task can be in
/**
These are the defined states, if the state is anything other than is
defined here that is annotated (not running) the process will be run.
No one should have any of their own states less than the USER_START
state. People's own states should start at USER_START or at
USER_START plus a constant (so they can have different sets of states).
*/
class ArTaskState
{
public:
enum State
{
INIT = 0, ///< Initialized (running)
RESUME, ///< Resumed after being suspended (running)
ACTIVE, ///< Active (running)
SUSPEND, ///< Suspended (not running)
SUCCESS, ///< Succeeded and done (not running)
FAILURE, ///< Failed and done (not running)
USER_START = 20 ///< This is where the user states should start (they will all be run)
};
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArSimpleConnector.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System<gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSIMPLECONNECTOR_H
#define ARSIMPLECONNECTOR_H
#include "ariaTypedefs.h"
#include "ArSerialConnection.h"
#include "ArTcpConnection.h"
#include "ArArgumentBuilder.h"
#include "ArArgumentParser.h"
#include "ariaUtil.h"
#include "ArRobotConnector.h"
#include "ArLaserConnector.h"
class ArSick;
class ArRobot;
/// Legacy connector for robot and laser
/**
This is deprecated but is left in for compatibility with old code,
Instead use ArRobotConnector to set up ArRobot's connection to the robot, and
ArLaserConnector to set up connections with laser rangefinder devices.
@deprecated Use ArRobotConnector and ArLaserConnector instead
**/
class ArSimpleConnector
{
public:
/// Constructor that takes args from the main
AREXPORT ArSimpleConnector(int *argc, char **argv);
/// Constructor that takes argument builder
AREXPORT ArSimpleConnector(ArArgumentBuilder *arguments);
/// Constructor that takes argument parser
AREXPORT ArSimpleConnector(ArArgumentParser *parser);
/// Destructor
AREXPORT ~ArSimpleConnector(void);
/// Sets up the robot to be connected
AREXPORT bool setupRobot(ArRobot *robot);
/// Sets up the robot then connects it
AREXPORT bool connectRobot(ArRobot *robot);
/// Sets up the laser to be connected
AREXPORT bool setupLaser(ArSick *laser);
/// Sets up a second laser to be connected
AREXPORT bool setupSecondLaser(ArSick *laser);
/// Sets up a laser t obe connected (make sure you setMaxNumLasers)
AREXPORT bool setupLaserArbitrary(ArSick *laser,
int laserNumber);
/// Connects the laser synchronously (will take up to a minute)
AREXPORT bool connectLaser(ArSick *laser);
/// Connects the laser synchronously (will take up to a minute)
AREXPORT bool connectSecondLaser(ArSick *laser);
/// Connects the laser synchronously (make sure you setMaxNumLasers)
AREXPORT bool connectLaserArbitrary(ArSick *laser, int laserNumber);
/// Function to parse the arguments given in the constructor
AREXPORT bool parseArgs(void);
/// Function to parse the arguments given in an arbitrary parser
AREXPORT bool parseArgs(ArArgumentParser *parser);
/// Log the options the simple connector has
AREXPORT void logOptions(void) const;
/// Sets the number of possible lasers
AREXPORT void setMaxNumLasers(int maxNumLasers = 1);
protected:
/// Finishes the stuff the constructor needs to do
void finishConstructor(void);
ArArgumentParser *myParser;
bool myOwnParser;
ArRobotConnector *myRobotConnector;
ArLaserConnector *myLaserConnector;
};
#endif // ARSIMPLECONNECTOR_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Path/pathNode.h | <filename>Path/pathNode.h<gh_stars>0
/**
* @file pathNode.h
* @Author <NAME> (<EMAIL>)
* @date December 30th, 2020
* @brief PathNode struct declaration
*
*
* This file declares the PathNode declaration and all it's necessary
* pointers
*/
#ifndef _PATHNODE_
#define _PATHNODE_
#include <iostream>
#include "../Position/Pose.h"
struct Node {
Pose pose;
struct Node* next;
Node(Pose pose) {
this->next = NULL;
this->pose = pose;
}
};
#endif //! _PATHNODE_ |
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionMovementParameters.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONMOVEMENTPARAMTERS_H
#define ARACTIONMOVEMENTPARAMTERS_H
#include "ariaTypedefs.h"
#include "ArAction.h"
#include "ArMapObject.h"
/// This is a class for setting max velocities and accels and decels via ArConfig parameters (see addToConfig()) or manually (using setParameters())
/**
@ingroup ActionClasses
**/
class ArActionMovementParameters : public ArAction
{
public:
/// Constructor
AREXPORT ArActionMovementParameters(const char *name = "MovementParameters",
bool overrideFaster = true,
bool addLatVelIfAvailable = true);
/// Destructor
AREXPORT virtual ~ArActionMovementParameters();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
/// Sees if this action is enabled (separate from activating it)
AREXPORT bool isEnabled(void) { return myEnabled; }
/// Enables this action (separate from activating it)
AREXPORT void enable(void) { myEnabled = true; }
/// Enables this action in a way that'll work from the sector callbacks
AREXPORT void enableOnceFromSector(ArMapObject *mapObject)
{ myEnableOnce = true; }
/// Disables this action (separate from deactivating it)
AREXPORT void disable(void) { myEnabled = false; }
/// Sets the parameters (don't use this if you're using the addToConfig)
AREXPORT void setParameters(double maxVel = 0, double maxNegVel = 0,
double transAccel = 0, double transDecel = 0,
double rotVelMax = 0, double rotAccel = 0,
double rotDecel = 0, double latVelMax = 0,
double latAccel = 0, double latDecel = 0);
/// Adds to the ArConfig given, in section, with prefix
AREXPORT void addToConfig(ArConfig *config, const char *section,
const char *prefix = NULL);
protected:
bool myEnabled;
bool myEnableOnce;
bool myOverrideFaster;
bool myAddLatVelIfAvailable;
double myMaxVel;
double myMaxNegVel;
double myTransAccel;
double myTransDecel;
double myMaxRotVel;
double myRotAccel;
double myRotDecel;
double myMaxLatVel;
double myLatAccel;
double myLatDecel;
ArActionDesired myDesired;
};
#endif // ARACTIONMOVEMENTPARAMTERS_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArNMEAParser.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARNMEAPARSER_H
#define ARNMEAPARSER_H
#include "ariaTypedefs.h"
#include "ArFunctor.h"
#include "ariaUtil.h"
#include "ArDeviceConnection.h"
#include <string>
#include <vector>
/** @brief NMEA Parser
*
* Parses NMEA input data and calls callbacks for certain messages with message
* parts. NMEA is a standard output data protocol used by GPS devices and
* others (e.g. compass, altimiter, etc.) This class is used internally by ArNMEAParser and
* subclasses, and by ArTCMCompassDirect.
*/
class ArNMEAParser {
public:
/** @param name Used in log messages */
AREXPORT ArNMEAParser(const char *name = "NMEA Parser");
/** @brief Flags to indicates what the parse() method did.
* i.e. If nothing was done, then the
* result will be 0. To check a parse() return result @a result to see if data was updated, use
* (result & ParseUpdated). To check if there was an error, use (result &
* ParseError).
*/
enum {
ParseFinished = 1, ///< There was no data to parse
ParseError = 2, ///< There was an error
ParseData = 4, ///< Input was recieved and stored, but no complete messages were parsed
ParseUpdated = 8 ///< At least one complete message was parsed
} ParseFlags;
/** @brief Set whether checksum is ignored (default behavior is not to ignore it, and
* skip messages with incorrect checksums, and log a warning mesage) */
AREXPORT void setIgnoreChecksum(bool ignore) { ignoreChecksum = ignore; }
/** NMEA message, divided into parts. */
typedef std::vector<std::string> MessageVector;
/** Message data passed to handlers */
typedef struct {
/** The parts of the message, including initial message ID (but excluding
* checksum) */
ArNMEAParser::MessageVector* message;
/** Timestamp when the beginning of this message was recieved and parsing
* began. */
ArTime timeParseStarted;
/// Message ID (first word minus talker prefix)
std::string id;
/// Talker-ID prefix, may indicate type of receiver or what kind of GPS system is in use
std::string prefix;
} Message;
/** NMEA message handler type. */
typedef ArFunctor1<ArNMEAParser::Message> Handler;
/** Set a handler for an NMEA message. Mostly for internal use or to be used
* by related classes, but you could use for ususual or custom messages
* emitted by a device that you wish to be handled outside of the ArNMEAParser
* class.
* @param messageID ID of NMEA sentence/message, without two-letter "talker" prefix.
*/
AREXPORT void addHandler(const char *messageID, ArNMEAParser::Handler *handler);
AREXPORT void removeHandler(const char *messageID);
/* Read a chunk of input text from the given device connection and
* parse with parse(char*, int). The maximum amount of text read from the device
* connection is determined by the internal buffer size in this class
* (probably a few hundred bytes limit).
* @return a result code from ParseFlags
* @note You should only use one stream of data with ArNMEAParser, and in a
* continuous fashion, since it will store partially recieved messages for
* the next call to one of the parse() methods.
*/
AREXPORT int parse(ArDeviceConnection *dev);
/* Parse a chunk of input text. Call message handlers as complete NMEA
* messages are parsed. Parsing state is stored in this ArNMEAParser object.
* @return a result code from ParseFlags
*/
AREXPORT int parse(const char *buf, int n);
public:
/* Map of message identifiers to handler functors */
typedef std::map<std::string, ArNMEAParser::Handler*> HandlerMap;
private:
/* NMEA message handlers used by ArNMEAParser */
HandlerMap myHandlers;
std::map<std::string, std::string> myLastPrefix;
public:
const ArNMEAParser::HandlerMap& getHandlersRef() const { return myHandlers; }
private:
const char *myName;
/* NMEA scanner state.
* There are possabilities for opmitization here, such
* as just storing the read data in a buffer and handling
* each field as it is found in the buffer, or building
* a list of char* for each field pointing into the buffer
* instead of copying each field into a std::string in the
* currentMessage vector, etc. etc.
*/
const unsigned short MaxNumFields;
const unsigned short MaxFieldSize; // bytes
bool ignoreChecksum;
MessageVector currentMessage;
ArTime currentMessageStarted;
std::string currentField;
char checksumBuf[3];
short checksumBufOffset;
bool inChecksum;
bool inMessage;
char currentChecksum;
bool gotCR;
// Tools to update state
void beginMessage();
void endMessage();
void nextField();
void beginChecksum();
/* Data buffer used by handleInput(ArDeviceConnection*).
* This should be enough to hold several NMEA messages.
* Most NMEA messages should be less than 50 bytes or so;
* 256 then allows a minumum of 5 messages parsed per
* call to parse(arDeviceConnection*).)
*/
char myReadBuffer[256]; //[512];
};
#endif // ifdef ARNMEAPARSER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Path/Path.h | /**
* @file Path.h
* @Author <NAME> (<EMAIL>)
* @date December 30th, 2020
* @brief Path class declaration
*
*
* This file declares the Path class and all it's necessary functions
*/
#ifndef _PATH_
#define _PATH_
#include <iostream>
#include "pathNode.h"
#include "../Position/Pose.h"
using namespace std;
class Path
{
private:
Node* tail;
Node* head;
int number;
public:
Path();
~Path();
void addPose(Pose);
void print();
Pose& operator[](int);
int size();
Pose getPos(int);
bool removePos(int);
bool insert(int, Pose);
friend ostream& operator <<(ostream&, Path&);
friend istream& operator >>(istream&, Path&);
};
#endif //! _PATH_
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/wrapper_Functors.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARIA_wrapper_Functors_h
#define ARIA_wrapper_Functors_h
/* For Python, define ArFunctor subclasses to hold Python C library
* callable function objects. These are used internally by the
* wrapper library, and typemaps convert target-language function
* objects to these ArFunctor subclasses-- you only need to pass
* the function to Aria when in the C++ API you would pass a Functor.
*
* For Java, define subclasses of ArFunctor for various argument types,
* since you can't access template classes in Java. Then you can
* further subclass within Java and pass that object to Aria.
*/
#include "ArFunctor.h"
/* Functors for Python: */
#ifdef SWIGPYTHON
class ArPyFunctor : public virtual ArFunctor
{
protected:
PyObject* pyFunction;
public:
ArPyFunctor(PyObject* _m) : pyFunction(_m) {
Py_INCREF(pyFunction);
}
virtual void invoke() {
PyObject* r = PyObject_CallObject(pyFunction, NULL);
if(!r) {
fputs("** ArPyFunctor: Error calling Python function: ", stderr);
PyErr_Print();
}
}
virtual ~ArPyFunctor() {
Py_DECREF(pyFunction);
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
/* Return type could be generalized if we find a way to convert any Python type
* returned by the Python function to whatever the templatized return type is
* required by the C++ functor. This _Bool version just checks boolean value of
* return from python function.
*/
class ArPyRetFunctor_Bool :
public virtual ArRetFunctor<bool>,
public virtual ArPyFunctor
{
public:
ArPyRetFunctor_Bool(PyObject* _m) : ArRetFunctor<bool>(), ArPyFunctor(_m) {
}
virtual bool invokeR() {
PyObject* r = PyObject_CallObject(pyFunction, NULL);
if(!r) {
fputs("** ArPyRetFunctor_Bool: Error calling Python function: ", stderr);
PyErr_Print();
}
return(r == Py_True);
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
class ArPyFunctor1_String :
public virtual ArFunctor1<const char*>,
public virtual ArPyFunctor
{
public:
ArPyFunctor1_String(PyObject* _m) : ArFunctor1<const char*>(), ArPyFunctor(_m) {
}
virtual void invoke(const char* arg) {
if(!arg) {
Py_FatalError("ArPyFunctor1_String invoked with null argument!");
// TODO invoke with "None" value
return;
}
//printf("ArPyFunctor1_String invoked with \"%s\"\n", arg);
PyObject *s = PyString_FromString(arg);
if(!s) {
PyErr_Print();
Py_FatalError("ArPyFunctor1_String: Error converting argument to Python string value");
return;
}
PyObject* r = PyObject_CallFunctionObjArgs(pyFunction, s, NULL);
if(!r) {
fputs("** ArPyFunctor1_String: invoke: Error calling Python function: ", stderr);
PyErr_Print();
}
Py_DECREF(s);
}
virtual void invoke() {
fputs("** ArPyFunctor1_String: invoke: No argument supplied?", stderr);
Py_FatalError("ArPyFunctor1_String invoked with no arguments!");
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
#ifdef ARIA_WRAPPER
class ArPyPacketHandlerFunctor :
public virtual ArRetFunctor1<bool, ArRobotPacket*>,
public virtual ArPyFunctor
{
public:
ArPyPacketHandlerFunctor(PyObject* _m) : ArRetFunctor1<bool, ArRobotPacket*>(), ArPyFunctor(_m) {}
virtual bool invokeR(ArRobotPacket* pkt) {
if(!pkt) {
Py_FatalError("ArPyPacketHandlerFunctor invoked with null argument!");
return false;
}
PyObject *po = SWIG_NewPointerObj((void*)pkt, SWIGTYPE_p_ArRobotPacket, 0); //PyObject_FromPointer(arg);
PyObject *r = PyObject_CallFunctionObjArgs(this->pyFunction, po, NULL);
if(!r) {
fputs("** ArPyPacketHandlerFunctor: invoke: Error calling Python function: ", stderr);
PyErr_Print();
}
Py_DECREF(po);
return (r == Py_True);
}
virtual bool invokeR() {
fputs("** ArPyPacketHandlerFunctor: invokeR: No argument supplied", stderr);
Py_FatalError("ArPyPacketHandlerFunctor invoked with no arguments!");
return false;
}
virtual void invoke() {
fputs("** ArPyPacketHandlerFunctor: invoke: No argument supplied?", stderr);
Py_FatalError("ArPyPacketHandlerFunctor invoked with no arguments!");
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
#endif
// XXX TODO supply reference/pointer in constructor to Python library conversion function to convert to Python
// type (e.g. ...FromInt, FromLong, FromInt, etc.)
template <typename T1>
class ArPyFunctor1 :
public virtual ArFunctor1<T1>,
public virtual ArPyFunctor
{
public:
ArPyFunctor1(PyObject* pyfunc) : ArFunctor1<T1>(), ArPyFunctor(pyfunc) {
}
virtual void invoke(T1 arg) {
puts("ArPyFunctor1<> invoked");
fflush(stdout);
PyObject* r = PyObject_CallFunctionObjArgs(pyFunction, arg, NULL);
if(!r) {
fputs("** ArPyFunctor1: invoke: Error calling Python function: ", stderr);
PyErr_Print();
}
}
virtual void invoke() {
fputs("** ArPyFunctor1: invoke: No argument supplied?", stderr);
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
template <typename T1, typename T2>
class ArPyFunctor2 :
public virtual ArFunctor2<T1, T2>,
public virtual ArPyFunctor
{
public:
ArPyFunctor2(PyObject* _m) : ArFunctor2<T1, T2>(), ArPyFunctor(_m) {
}
virtual void invoke(T1 arg1, T2 arg2) {
PyObject* r = PyObject_CallFunctionObjArgs(pyFunction, arg1, arg2, NULL);
if(!r) {
fputs("** ArPyFunctor2: invoke: Error calling Python function: ", stderr);
PyErr_Print();
}
}
virtual void invoke() {
fputs("** ArPyFunctor2: invoke: No argument supplied?", stderr);
Py_FatalError("ArPyFunctor2 invoked with no arguments!");
}
virtual void invoke(T1 arg1) {
fputs("** ArPyFunctor2: invoke: No argument supplied?", stderr);
Py_FatalError("ArPyFunctor2 invoked with not enough arguments!");
}
virtual const char* getName() {
return (const char*) PyString_AsString(PyObject_Str(pyFunction));
}
};
#endif // PYTHON
#endif // wrapperFunctors.h
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArDeviceConnection.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARDEVICECONNECTION_H
#define ARDEVICECONNECTION_H
#include <string>
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArBasePacket.h"
/// Base class for device connections
/**
Base class for device connections, this is mostly for connections to the
robot or simulator but could also be used for a connection to a laser
or other device
Note that this is mostly a base class, so if you'll want to use one of the
classes which inherit from this one... also note that in those classes
is where you'll find setPort which sets the place the device connection
will try to connect to... the inherited classes also have an open which
returns more detailed information about the open attempt, and which takes
the parameters for where to connect
*/
class ArDeviceConnection
{
public:
/// constructor
AREXPORT ArDeviceConnection();
/// destructor also forces a close on the connection
AREXPORT virtual ~ArDeviceConnection();
/// Reads data from connection
/**
Reads data from connection
@param data pointer to a character array to read the data into
@param size maximum number of bytes to read
@param msWait read blocks for this many milliseconds (not at all for == 0)
@return number of bytes read, or -1 for failure
@see write, writePacket
*/
AREXPORT virtual int read(const char *data, unsigned int size,
unsigned int msWait = 0) = 0;
/// Writes data to connection
/**
Writes data to connection from a packet
@param packet pointer to a packet to write the data from
@return number of bytes written, or -1 for failure
@see read, write
*/
AREXPORT virtual int writePacket(ArBasePacket *packet)
{ if (packet == NULL || packet->getLength() == 0) return 0;
return write(packet->getBuf(), packet->getLength()); }
/// Writes data to connection
/**
Writes data to connection
@param data pointer to a character array to write the data from
@param size number of bytes to write
@return number of bytes read, or -1 for failure
@see read, writePacket
*/
AREXPORT virtual int write(const char *data, unsigned int size) = 0;
/// Gets the status of the connection, which is one of the enum status
/**
Gets the status of the connection, which is one of the enum status.
If you want to get a string to go along with the number, use
getStatusMessage
@return the status of the connection
@see getStatusMessage
*/
AREXPORT virtual int getStatus(void) = 0;
/// Gets the description string associated with the status
/**
@param messageNumber the int from getStatus you want the string for
@return the description associated with the status
@see getStatus
*/
AREXPORT const char *getStatusMessage(int messageNumber) const;
/// Opens the connection again, using the values from setLocation or
// a previous open
virtual bool openSimple(void) = 0;
/// Closes the connection
/**
@return whether the close succeeded or not
*/
virtual bool close(void) { return false; }
/// Gets the string of the message associated with opening the device
/**
Each class inherited from this one has an open method which returns 0
for success or an integer which can be passed into this function to
obtain a string describing the reason for failure
@param messageNumber the number returned from the open
@return the error description associated with the messageNumber
*/
AREXPORT virtual const char * getOpenMessage(int messageNumber) = 0;
enum Status {
STATUS_NEVER_OPENED = 1, ///< Never opened
STATUS_OPEN, ///< Currently open
STATUS_OPEN_FAILED, ///< Tried to open, but failed
STATUS_CLOSED_NORMALLY, ///< Closed by a close call
STATUS_CLOSED_ERROR ///< Closed because of error
};
/// Gets the time data was read in
/**
@param index looks like this is the index back in the number of bytes
last read in
@return the time the last read data was read in
*/
AREXPORT virtual ArTime getTimeRead(int index) = 0;
/// sees if timestamping is really going on or not
/** @return true if real timestamping is happening, false otherwise */
AREXPORT virtual bool isTimeStamping(void) = 0;
/// Gets the port name
AREXPORT const char *getPortName(void) const;
/// Gets the port type
AREXPORT const char *getPortType(void) const;
/// Sets the device type (what this is connecting to)
AREXPORT void setDeviceName(const char *deviceName);
/// Gets the device type (what this is connecting to)
AREXPORT const char *getDeviceName(void) const;
/// Notifies the device connection that the start of a packet is
/// trying to be read
AREXPORT void debugStartPacket(void);
/// Notifies the device connection that some bytes were read (should
/// call with 0 if it read but got no bytes)
AREXPORT void debugBytesRead(int bytesRead);
/// Notifies the device connection that the end of a packet was
/// read, which will cause log messages if set to do so
AREXPORT void debugEndPacket(bool goodPacket, int type = 0);
/// Makes all device connections so that they'll dump data
AREXPORT static bool debugShouldLog(bool shouldLog);
protected:
/// Sets the port name
AREXPORT void setPortName(const char *portName);
/// Sets the port type
AREXPORT void setPortType(const char *portType);
void buildStrMap(void);
static bool ourStrMapInited;
static ArStrMap ourStrMap;
std::string myDCPortName;
std::string myDCPortType;
std::string myDCDeviceName;
static bool ourDCDebugShouldLog;
static ArTime ourDCDebugFirstTime;
bool myDCDebugPacketStarted;
ArTime myDCDebugStartTime;
ArTime myDCDebugFirstByteTime;
ArTime myDCDebugLastByteTime;
int myDCDebugBytesRead;
int myDCDebugTimesRead;
long long myDCDebugNumGoodPackets;
long long myDCDebugNumBadPackets;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionConstantVelocity.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONCONSTANTVELOCITY_H
#define ARACTIONCONSTANTVELOCITY_H
#include "ariaTypedefs.h"
#include "ArAction.h"
/// Action for going straight at a constant velocity
/**
This action simply goes straight at a constant velocity.
@ingroup ActionClasses
*/
class ArActionConstantVelocity : public ArAction
{
public:
/// Constructor
AREXPORT ArActionConstantVelocity(const char *name = "Constant Velocity",
double velocity = 400);
/// Destructor
AREXPORT virtual ~ArActionConstantVelocity();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
double myVelocity;
ArActionDesired myDesired;
};
#endif // ARACTIONCONSTANTVELOCITY_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArLMS1XX.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARLMS1XX_H
#define ARLMS1XX_H
#include "ariaTypedefs.h"
#include "ArRobotPacket.h"
#include "ArLaser.h"
#include "ArFunctor.h"
/** @internal
Constructs packets for LMS1xx ASCII protocol.
The various ...ToBuf() methods select argument types and how
they are written as ascii strings, the protocol is space delimited not fixed
width values (as in other Packet implementations), so they don't imply number of bytes used in packet output.
*/
class ArLMS1XXPacket : public ArBasePacket
{
public:
/// Constructor
AREXPORT ArLMS1XXPacket();
/// Destructor
AREXPORT virtual ~ArLMS1XXPacket();
/// Gets the command type
AREXPORT const char *getCommandType(void);
/// Gets the command name
AREXPORT const char *getCommandName(void);
// only call finalizePacket before a send
AREXPORT virtual void finalizePacket(void);
AREXPORT virtual void resetRead(void);
/// Gets the time the packet was received at
AREXPORT ArTime getTimeReceived(void);
/// Sets the time the packet was received at
AREXPORT void setTimeReceived(ArTime timeReceived);
AREXPORT virtual void duplicatePacket(ArLMS1XXPacket *packet);
AREXPORT virtual void empty(void);
AREXPORT virtual void byteToBuf(ArTypes::Byte val);
AREXPORT virtual void byte2ToBuf(ArTypes::Byte2 val);
AREXPORT virtual void byte4ToBuf(ArTypes::Byte4 val);
AREXPORT virtual void uByteToBuf(ArTypes::UByte val);
AREXPORT virtual void uByte2ToBuf(ArTypes::UByte2 val);
AREXPORT virtual void uByte4ToBuf(ArTypes::UByte4 val);
AREXPORT virtual void strToBuf(const char *str);
AREXPORT virtual ArTypes::Byte bufToByte(void);
AREXPORT virtual ArTypes::Byte2 bufToByte2(void);
AREXPORT virtual ArTypes::Byte4 bufToByte4(void);
AREXPORT virtual ArTypes::UByte bufToUByte(void);
AREXPORT virtual ArTypes::UByte2 bufToUByte2(void);
AREXPORT virtual ArTypes::UByte4 bufToUByte4(void);
AREXPORT virtual void bufToStr(char *buf, int len);
// adds a raw char to the buf
AREXPORT virtual void rawCharToBuf(unsigned char c);
protected:
int deascii(char c);
ArTime myTimeReceived;
bool myFirstAdd;
char myCommandType[1024];
char myCommandName[1024];
};
/// Given a device connection it receives packets from the sick through it
/// @internal
class ArLMS1XXPacketReceiver
{
public:
/// Constructor with assignment of a device connection
AREXPORT ArLMS1XXPacketReceiver();
/// Destructor
AREXPORT virtual ~ArLMS1XXPacketReceiver();
/// Receives a packet from the robot if there is one available
AREXPORT ArLMS1XXPacket *receivePacket(unsigned int msWait = 0,
bool shortcut = false,
bool ignoreRemainders = false);
AREXPORT ArLMS1XXPacket *receiveTiMPacket(unsigned int msWait = 0,
bool shortcut = false,
bool ignoreRemainders = false);
/// Sets the device this instance receives packets from
AREXPORT void setDeviceConnection(ArDeviceConnection *conn);
/// Gets the device this instance receives packets from
AREXPORT ArDeviceConnection *getDeviceConnection(void);
// PS - added to pass info to this class
AREXPORT void setmyInfoLogLevel(ArLog::LogLevel infoLogLevel)
{ myInfoLogLevel = infoLogLevel; }
AREXPORT void setLaserModel(int laserModel)
{ myLaserModel = laserModel; }
AREXPORT void setmyName(const char *name )
{
strncpy(myName, name, sizeof(myName));
myName[sizeof(myName)-1] = '\0';
}
AREXPORT void setReadTimeout(int timeout )
{ myReadTimeout = timeout; }
protected:
ArDeviceConnection *myConn;
ArLMS1XXPacket myPacket;
enum State
{
STARTING, ///< Looking for beginning
DATA, ///< Read the data in a big whack
REMAINDER ///< Have extra data from reading in data
};
State myState;
char myName[1024];
unsigned int myNameLength;
char myReadBuf[100000];
int myReadCount;
int myReadTimeout;
int myLaserModel;
ArLog::LogLevel myInfoLogLevel;
};
/**
@since Aria 2.7.2
@see ArLaserConnector
Use ArLaserConnector to connect to a laser, determining type based on robot and program configuration parameters.
This is the ArLaser implementation for SICK LMS1xx, LMS5xx, TiM310/510
(aka TiM3xx), TiM551, TiM561, and TiM571 lasers. To use these lasers with ArLaserConnector, specify
the appropriate type in program configuration (lms1xx, lms5xx, tim3xx or
tim510, tim551, tim561, tim571).
*/
class ArLMS1XX : public ArLaser
{
public:
enum LaserModel
{
LMS1XX,
LMS5XX,
TiM3XX,
TiM551,
TiM561,
TiM571
};
/// Constructor
AREXPORT ArLMS1XX(int laserNumber,
const char *name,
LaserModel laserModel);
/// Destructor
AREXPORT ~ArLMS1XX();
AREXPORT virtual bool blockingConnect(void);
// specific init routine per laser
AREXPORT virtual bool lms5xxConnect(void);
AREXPORT virtual bool lms1xxConnect(void);
AREXPORT virtual bool timConnect(void);
AREXPORT virtual bool asyncConnect(void);
AREXPORT virtual bool disconnect(void);
AREXPORT virtual bool isConnected(void) { return myIsConnected; }
AREXPORT virtual bool isTryingToConnect(void)
{
if (myStartConnect)
return true;
else if (myTryingToConnect)
return true;
else
return false;
}
/// Logs the information about the sensor
AREXPORT void log(void);
protected:
AREXPORT virtual void laserSetName(const char *name);
AREXPORT virtual void * runThread(void *arg);
AREXPORT virtual void setRobot(ArRobot *robot);
AREXPORT ArLMS1XXPacket *sendAndRecv(
ArTime timeout, ArLMS1XXPacket *sendPacket, const char *recvName);
void sensorInterp(void);
void failedToConnect(void);
void clear(void);
/// @return true if message contents matches checksum, false otherwise.
bool validateCheckSum(ArLMS1XXPacket *packet);
LaserModel myLaserModel;
enum LaserModelFamily
{
LMS,
TiM,
};
LaserModelFamily myLaserModelFamily;
bool myIsConnected;
bool myTryingToConnect;
bool myStartConnect;
int myScanFreq;
int myVersionNumber;
int myDeviceNumber;
int mySerialNumber;
int myDeviceStatus1;
int myDeviceStatus2;
int myMessageCounter;
int myScanCounter;
int myPowerUpDuration;
int myTransmissionDuration;
int myInputStatus1;
int myInputStatus2;
int myOutputStatus1;
int myOutputStatus2;
int myReserved;
int myScanningFreq;
int myMeasurementFreq;
int myNumberEncoders;
int myNumChans16Bit;
int myNumChans8Bit;
int myFirstReadings;
int myYear;
int myMonth;
int myMonthDay;
int myHour;
int myMinute;
int mySecond;
int myUSec;
ArLog::LogLevel myLogLevel;
ArLMS1XXPacketReceiver myReceiver;
ArMutex myPacketsMutex;
ArMutex myDataMutex;
std::list<ArLMS1XXPacket *> myPackets;
ArFunctorC<ArLMS1XX> mySensorInterpTask;
ArRetFunctorC<bool, ArLMS1XX> myAriaExitCB;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArResolver.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARRESOLVER_H
#define ARRESOLVER_H
#include "ariaTypedefs.h"
#include "ArActionDesired.h"
#include <string>
class ArAction;
class ArRobot;
/// Resolves a list of actions and returns what to do
/**
ArResolver::resolve() is the function that ArRobot
calls with the action list in order
to produce a combined ArActionDesired object from them, according to
the subclass's particular algorithm or policy.
*/
class ArResolver
{
public:
/// Constructor
typedef std::multimap<int, ArAction *> ActionMap;
ArResolver(const char *name, const char * description = "")
{ myName = name; myDescription = description; }
/// Desturctor
virtual ~ArResolver() {};
/// Figure out a single ArActionDesired from a list of ArAction s
virtual ArActionDesired *resolve(ActionMap *actions, ArRobot *robot,
bool logActions = false) = 0;
/// Gets the name of the resolver
virtual const char *getName(void) const { return myName.c_str(); }
/// Gets the long description fo the resolver
virtual const char *getDescription(void) const { return myDescription.c_str(); }
protected:
std::string myName;
std::string myDescription;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionColorFollow.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONCOLORFOLLOW_H
#define ARACTIONCOLORFOLLOW_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArFunctor.h"
#include "ArAction.h"
#include "ArACTS.h"
#include "ArPTZ.h"
/// ArActionColorFollow is an action that moves the robot toward the
/// largest ACTS blob that appears in it's current field of view.
/// @ingroup ActionClasses
class ArActionColorFollow : public ArAction
{
public:
// Constructor
AREXPORT ArActionColorFollow(const char *name,
ArACTS_1_2 *acts,
ArPTZ *camera,
double speed = 200,
int width = 160,
int height = 120);
// Destructor
AREXPORT virtual ~ArActionColorFollow(void);
// The action
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
// Set the ACTS channel that we want to get blob info out of
AREXPORT bool setChannel(int channel);
// Set the camera that we will be controlling
AREXPORT void setCamera(ArPTZ *camera);
// Toggle whether we should try to acquire a blob
// if one cannot be seen
AREXPORT void setAcquire(bool acquire);
// Stop moving alltogether
AREXPORT void stopMovement(void);
// Start moving
AREXPORT void startMovement(void);
// Return the channel that we are looking for blobs on
AREXPORT int getChannel();
// Return whether or not we are trying to acquire a blob
// if we cannot see one
AREXPORT bool getAcquire();
// Return whether or not we are moving
AREXPORT bool getMovement();
// Return whether or not we can see a target
AREXPORT bool getBlob();
// The state of the action
enum TargetState
{
NO_TARGET, // There is no target in view
TARGET // There is a target in view
};
// The state of movement
enum MoveState
{
FOLLOWING, // Following a blob
ACQUIRING, // Searching for a blob
STOPPED // Sitting still
};
// The last seen location of the blob
enum LocationState
{
LEFT, // The blob is on the left side of the screen
RIGHT, // The blob is on the right side of the screen
CENTER // The blob is relatively close to the center
};
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
ArActionDesired myDesired;
ArACTS_1_2 *myActs;
ArPTZ *myCamera;
ArTime myLastSeen;
TargetState myState;
MoveState myMove;
LocationState myLocation;
bool myAcquire;
bool killMovement;
int myChannel;
int myMaxTime;
int myHeight;
int myWidth;
double mySpeed;
};
#endif // ARACTIONCOLORFOLLOW_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArPTZConnector.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARPTZCONNECTOR_H
#define ARPTZCONNECTOR_H
#include <string>
#include <vector>
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArFunctor.h"
#include "ArRobotParams.h"
#include "ariaInternal.h"
class ArArgumentParser;
class ArPTZ;
class ArRobot;
/**
* @brief Factory for creating and configuring interfaces for pan/tilt units or camera
* pan/tilt/zoom control based on robot parameter file and command-line arguments.
*
* First, create an ArPTZConnector object before
* calling Aria::parseArgs(). After connecting to the robot, call
* Aria::parseArgs() to check arguments and parameters from the parameter
* file(s). Then, call connect() to connect to all configured and enabled PTZs. To get
* access to a PTZ objects, use getPTZ(int i) and getNumPTZs(), or getPTZs().
* ArPTZ provides an interface to functions that most PTZ implementations
* (ArPTZ subclasses) implement. Some PTZ implementations have additional
* features. Use those subclasse directly to use these additional features
* (use dynamic_cast to cast an ArPTZ pointer to a subclass pointer, if
* possible.)
*
* ArPTZConnector has built in support for all the PTZ types with support
* included in the ARIA library, and other libraries or programs may register
* new types as well. (For example, the ArVideo library contains support for
* additional camera PTZ types.)
*
* The following command-line arguments are checked:
* @verbinclude ArPTZConnector_options
*
* PTZs are 0-indexed internally in this class, however, argument names,
* parameter names and log messages displayed to users are 1-indexed.
@ingroup OptionalClasses
@ingroup DeviceClasses
@since 2.7.6
*/
class ArPTZConnector {
public:
/* @arg robot In some cases the robot connection is used to communicate with
* devices via auxilliary serial connections, so this robot interface is used.
* May be NULL. */
AREXPORT ArPTZConnector(ArArgumentParser* argParser, ArRobot *robot = NULL);
AREXPORT ~ArPTZConnector();
/** For each PTZ specified in program arguments, and in robot parameters with
* PTZAutoConnect set to true, create the
* appropriate PTZ object (based on type name) and connect to it.
@return false on first error, true if all PTZ connections were successful.
*/
AREXPORT bool connect();
/** @copydoc connect() */
bool connectPTZs() { return connect(); }
/** @return number of PTZ objects that were created and connected to. */
size_t getNumPTZs() const { return myConnectedPTZs.size(); }
/** @return a specific PTZ object that was connected by connect() or
* connectPTZs(), or NULL if none exists. These are 0-indexed. */
ArPTZ* getPTZ(size_t i = 0) const
{
if(i >= myConnectedPTZs.size()) return NULL;
return myConnectedPTZs[i];
}
/** @copydoc getPTZ(size_t) */
ArPTZ* findPTZ(size_t i) const { return getPTZ(i); }
/** @return list of connected PTZs.
0-indexed. Pointers in the vector may be NULL if no parameters or command
line arguments were given for them or that PTZ was disabled. These should be
skipped when iterating on this list and not accessed.
*/
std::vector<ArPTZ*> getPTZs() const {
return myConnectedPTZs;
}
/** Arguments passed to function are PTZ index, parameters, parser (may be
* null) and robot object (may be null) */
typedef ArRetFunctor4<ArPTZ*, size_t, ArPTZParams, ArArgumentParser*, ArRobot*> PTZCreateFunc;
typedef ArGlobalRetFunctor4<ArPTZ*, size_t, ArPTZParams, ArArgumentParser*, ArRobot*> GlobalPTZCreateFunc;
/** Register a new PTZ type. Aria::init() registers PTZ types built in to
* ARIA. ArVideo::init() registers new PTZ types implemented in the ArVideo
* library. You may also add any new PTZ types you create.
*/
AREXPORT static void registerPTZType(const std::string& typeName, ArPTZConnector::PTZCreateFunc* func);
/** Change limit on number of PTZ devices.
* You must call this
* before creating an ArPTZConnector, parsing command line arguments, connecting
* to a robot or loading a parameter file, or using ArPTZconnecor to connect to
* PTZ devices.
*/
void setMaxNumPTZs(size_t n)
{
Aria::setMaxNumPTZs(n);
}
size_t getMaxNumPTZs()
{
return Aria::getMaxNumPTZs();
}
/** Return robot that PTZs are or will be attached to (may be NULL) */
ArRobot *getRobot() { return myRobot; }
protected:
bool parseArgs();
bool parseArgs(ArArgumentParser *parser);
bool parseArgsFor(ArArgumentParser *parser, int which);
AREXPORT void logOptions() const;
void populateRobotParams(ArRobotParams *params);
ArArgumentParser *myArgParser;
ArRobot *myRobot;
ArRetFunctorC<bool, ArPTZConnector> myParseArgsCallback;
ArConstFunctorC<ArPTZConnector> myLogOptionsCallback;
static std::map< std::string, PTZCreateFunc* > ourPTZCreateFuncs;
ArFunctor1C<ArPTZConnector, ArRobotParams*> myPopulateRobotParamsCB;
std::vector<ArPTZParams> myParams; ///< copied from ArRobotParams (via myRobot), then in connect() parameters given from command line arguments (myArguments) are merged in.
std::vector<ArPTZParams> myArguments; ///< from program command-line options (via the parseArgs() callback called by Aria::parseArgs())
//std::vector<ArPTZParams> myConfiguredPTZs; ///< if connecting to a PTZ, its parameters are copied here from myParams and myArguments
//static size_t ourMaxNumPTZs;
std::vector<ArPTZ*> myConnectedPTZs; ///< ArPTZ objects created and initialized in connect().
};
#endif // ifdef ARPTZCONNECTOR_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArLineFinder.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSICKLINEFINDER_H
#define ARSICKLINEFINDER_H
#include "ariaTypedefs.h"
#include "ArRangeDevice.h"
#include "ariaUtil.h"
#include <vector>
class ArLineFinderSegment;
class ArConfig;
/** This class finds lines out of any range device with raw readings (lasers for instance)
@ingroup OptionalClasses
@ingroup UtilityClasses
*/
class ArLineFinder
{
public:
/// Constructor
AREXPORT ArLineFinder(ArRangeDevice *dev);
/// Destructor
AREXPORT virtual ~ArLineFinder();
#ifndef SWIG
/// Finds the lines and returns a pointer to ArLineFinder's map of them
/** @swigomit */
AREXPORT std::map<int, ArLineFinderSegment *> *getLines(void);
/// Finds the lines, but then returns a pointer to ArLineFinder's map of the points that AREN'T in lines
/** @swigomit */
AREXPORT std::map<int, ArPose> *getNonLinePoints(void);
#endif
/// Finds the lines, then copies @b pointers to them them into a new set
AREXPORT std::set<ArLineFinderSegment*> getLinesAsSet();
/// Finds the lines, and then copies the points that AREN'T in the lines into a new set
AREXPORT std::set<ArPose> getNonLinePointsAsSet();
/// Gets the robot pose at which the data from the range device (provided in
/// constructor) was received
ArPose getLinesTakenPose(void) { return myPoseTaken; }
/// Logs all the points and lines from the last getLines
AREXPORT void saveLast(void);
/// Gets the lines, then prints them
AREXPORT void getLinesAndSaveThem(void);
/// Whether to print verbose information about line decisions
void setVerbose(bool verbose) { myPrinting = verbose; }
/// Whether to print verbose information about line decisions
bool getVerbose(void) { return myPrinting; }
/// Sets some parameters for line creation
void setLineCreationParams(int minLineLen = 40, int minLinePoints = 2)
{ myMakingMinLen = minLineLen; myMakingMinPoints = minLinePoints; }
/// Sets some parameters for combining two possible lines into one line.
void setLineCombiningParams(int angleTol = 30, int linesCloseEnough = 75)
{ myCombiningAngleTol = angleTol;
myCombiningLinesCloseEnough = linesCloseEnough; }
/// Filter out lines based on line length or number of points in the line.
void setLineFilteringParams(int minPointsInLine = 3, int minLineLength = 75)
{ myFilteringMinPointsInLine = minPointsInLine;
myFilteringMinLineLength = minLineLength; }
/// Don't let lines happen that have points not close to it
void setLineValidParams(int maxDistFromLine = 30,
int maxAveDistFromLine = 20)
{ myValidMaxDistFromLine = maxDistFromLine;
myValidMaxAveFromLine = maxAveDistFromLine; }
/** Sets a maximum distance for points to be included in the same line. If
points are greater than this distance apart, then they will not be
considered in the same line. If this value is 0, then there is no
maximum-distance condition and points will be considered part of a line no
matter how far apart.
*/
void setMaxDistBetweenPoints(int maxDistBetweenPoints = 0)
{ myMaxDistBetweenPoints = maxDistBetweenPoints; }
/// Add this ArLineFinder's parameters to the given ArConfig object.
AREXPORT void addToConfig(ArConfig *config,
const char *section);
protected:
// where the readings were taken
ArPose myPoseTaken;
// our points
std::map<int, ArPose> *myPoints;
std::map<int, ArLineFinderSegment *> *myLines;
std::map<int, ArPose> *myNonLinePoints;
// fills up the myPoints variable from sick laser
AREXPORT void fillPointsFromLaser(void);
// fills up the myLines variable from the myPoints
AREXPORT void findLines(void);
// cleans the lines and puts them into myLines
AREXPORT bool combineLines();
// takes two segments and sees if it can average them
AREXPORT ArLineFinderSegment *averageSegments(ArLineFinderSegment *line1,
ArLineFinderSegment *line2);
// removes lines that don't have enough points added in
AREXPORT void filterLines();
bool myFlippedFound;
bool myFlipped;
int myValidMaxDistFromLine;
int myValidMaxAveFromLine;
int myMakingMinLen;
int myMakingMinPoints;
int myCombiningAngleTol;
int myCombiningLinesCloseEnough;
int myFilteringMinPointsInLine;
int myFilteringMinLineLength;
int myMaxDistBetweenPoints;
double mySinMultiplier;
bool myPrinting;
ArRangeDevice *myRangeDevice;
};
/// Class for ArLineFinder to hold more info than an ArLineSegment
class ArLineFinderSegment : public ArLineSegment
{
public:
ArLineFinderSegment() {}
ArLineFinderSegment(double x1, double y1, double x2, double y2,
int numPoints = 0, int startPoint = 0, int endPoint = 0)
{ newEndPoints(x1, y1, x2, y2, numPoints, startPoint, endPoint); }
virtual ~ArLineFinderSegment() {}
void newEndPoints(double x1, double y1, double x2, double y2,
int numPoints = 0, int startPoint = 0, int endPoint = 0)
{
ArLineSegment::newEndPoints(x1, y1, x2, y2);
myLineAngle = ArMath::atan2(y2 - y1, x2 - x1);
myLength = ArMath::distanceBetween(x1, y1, x2, y2);
myNumPoints = numPoints;
myStartPoint = startPoint;
myEndPoint = endPoint;
myAveDistFromLine = 0;
}
double getLineAngle(void) { return myLineAngle; }
double getLength(void) { return myLength; }
int getNumPoints(void) { return myNumPoints; }
int getStartPoint(void) { return myStartPoint; }
int getEndPoint(void) { return myEndPoint; }
void setAveDistFromLine(double aveDistFromLine)
{ myAveDistFromLine = aveDistFromLine; }
double getAveDistFromLine(void) { return myAveDistFromLine; }
protected:
double myLineAngle;
double myLength;
int myNumPoints;
int myStartPoint;
int myEndPoint;
double myAveDistFromLine;
};
#endif // ARSICKLINEFINDER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArStringInfoGroup.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSTRINGINFOGROUP_H
#define ARSTRINGINFOGROUP_H
#include "ariaUtil.h"
#include "ArMutex.h"
#include <string>
#include <set>
#include <list>
/**
This class takes callbacks from different classes that want this
string information and then lets you just add the information here
instead of to each individual class.
@ingroup OptionalClasses
**/
class ArStringInfoGroup
{
public:
/// Constructor
AREXPORT ArStringInfoGroup();
/// Destructor
AREXPORT virtual ~ArStringInfoGroup();
/// Adds a string to the list in the raw format
AREXPORT bool addString(const char *name, ArTypes::UByte2 maxLen,
ArFunctor2<char *, ArTypes::UByte2> *functor);
/// Adds an int to the list in the helped way
AREXPORT bool addStringInt(const char *name, ArTypes::UByte2 maxLen,
ArRetFunctor<int> *functor,
const char *format = "%d");
/// Adds a double to the list in the helped way
AREXPORT bool addStringDouble(const char *name, ArTypes::UByte2 maxLen,
ArRetFunctor<double> *functor,
const char *format = "%g");
/// Adds a bool to the list in the helped way
AREXPORT bool addStringBool(const char *name, ArTypes::UByte2 maxLen,
ArRetFunctor<bool> *functor,
const char *format = "%s");
/// Adds a string to the list in the helped way
AREXPORT bool addStringString(const char *name, ArTypes::UByte2 maxLen,
ArRetFunctor<const char *> *functor,
const char *format = "%s");
/// Adds a std::string to the list. std::string::c_str() will be used to
AREXPORT bool addStringString(const char *name, ArTypes::UByte2 maxLen,
ArRetFunctor<std::string> *functor);
/// Adds an int to the list in the helped way
AREXPORT bool addStringUnsignedLong(const char *name,
ArTypes::UByte2 maxLen,
ArRetFunctor<unsigned long> *functor,
const char *format = "%lu");
/// Adds an int to the list in the helped way
AREXPORT bool addStringLong(const char *name,
ArTypes::UByte2 maxLen,
ArRetFunctor<long> *functor,
const char *format = "%ld");
/// This is the function to add a callback to be called by addString
AREXPORT void addAddStringCallback(
ArFunctor3<const char *, ArTypes::UByte2,
ArFunctor2<char *, ArTypes::UByte2> *> *functor,
ArListPos::Pos position = ArListPos::LAST);
protected:
ArMutex myDataMutex;
std::set<std::string, ArStrCaseCmpOp> myAddedStrings;
std::list<ArFunctor3<const char *, ArTypes::UByte2,
ArFunctor2<char *, ArTypes::UByte2> *> *> myAddStringCBList;
};
#endif // ARSTRINGINFOHELPER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionGotoStraight.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONGOTOSTRAIGHT_H
#define ARACTIONGOTOSTRAIGHT_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArAction.h"
/// This action goes to a given ArPose very naively
/**
This action naively drives straight towards a given ArPose. The
action stops the robot when it has travelled the distance that that
pose is away. It travels at 'speed' mm/sec.
You can give it a new goal pose with setGoal(), cancel its movement
with cancelGoal(), and see if it got there with haveAchievedGoal().
For arguments to the goals and encoder goals you can tell it to go
backwards by calling them with the backwards parameter true. If
you set the justDistance to true it will only really care about
having driven the distance, if false it'll try to get to the spot
you wanted within close distance.
This doesn't avoid obstacles or anything, you could add have an obstacle
avoidance ArAction at a higher priority to try to do this. (For
truly intelligent navigation, see the ARNL and SONARNL software libraries.)
@ingroup ActionClasses
**/
class ArActionGotoStraight : public ArAction
{
public:
AREXPORT ArActionGotoStraight(const char *name = "goto",
double speed = 400);
AREXPORT virtual ~ArActionGotoStraight();
/// Sees if the goal has been achieved
AREXPORT bool haveAchievedGoal(void);
/// Cancels the goal the robot has
AREXPORT void cancelGoal(void);
/// Sets a new goal and sets the action to go there
AREXPORT void setGoal(ArPose goal, bool backwards = false,
bool justDistance = true);
/// Sets the goal in a relative way
AREXPORT void setGoalRel(double dist, double deltaHeading,
bool backwards = false, bool justDistance = true);
/// Gets the goal the action has
ArPose getGoal(void) { return myGoal; }
/// Gets whether we're using the encoder goal or the normal goal
bool usingEncoderGoal(void) { return myUseEncoderGoal; }
/// Sets a new goal and sets the action to go there
AREXPORT void setEncoderGoal(ArPose encoderGoal, bool backwards = false,
bool justDistance = true);
/// Sets the goal in a relative way
AREXPORT void setEncoderGoalRel(double dist, double deltaHeading,
bool backwards = false,
bool justDistance = true);
/// Gets the goal the action has
ArPose getEncoderGoal(void) { return myEncoderGoal; }
/// Sets the speed the action will travel to the goal at (mm/sec)
void setSpeed(double speed) { mySpeed = speed; }
/// Gets the speed the action will travel to the goal at (mm/sec)
double getSpeed(void) { return mySpeed; }
/// Sets how close we have to get if we're not in just distance mode
void setCloseDist(double closeDist = 100) { myCloseDist = closeDist; }
/// Gets how close we have to get if we're not in just distance mode
double getCloseDist(void) { return myCloseDist; }
/// Sets whether we're backing up there or not (set in the setGoals)
bool getBacking(void) { return myBacking; }
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
ArPose myGoal;
bool myUseEncoderGoal;
ArPose myEncoderGoal;
double mySpeed;
bool myBacking;
ArActionDesired myDesired;
bool myPrinting;
double myDist;
double myCloseDist;
bool myJustDist;
double myDistTravelled;
ArPose myLastPose;
enum State
{
STATE_NO_GOAL,
STATE_ACHIEVED_GOAL,
STATE_GOING_TO_GOAL
};
State myState;
};
#endif // ARACTIONGOTO
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArMapComponents.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
/*! \file ArMapComponents.h
* \brief Contains the set of component classes used to implement Aria maps.
* \date 06/27/08
* \author <NAME>
*
* The ArMap class (defined in ArMap.h) is composed of several smaller
* classes that are defined in this header file. These include:
*
* - ArMapScan: An implementation of the ArMapScanInterface. This
* contains all of the data related to the sensed obstacles (i.e.
* data points and lines). An instance of this class is created
* for each scan type that is defined in the map.
*
* - ArMapObjects: An implementation of the ArMapObjectsInterface.
* This stores all of the map objects for the Aria map.
*
* - ArMapInfo: An implementation of the ArMapInfoInterface. This
* contains all of the info (ArArgumentBuilder) tags defined for
* the map, including MapInfo, TaskInfo, and RouteInfo.
*
* - ArMapSupplement: An implementation of the ArMapSupplementInterface.
* This is a repository for all of the extra data that does not fit
* into any of the above categories.
*
* - ArMapSimple: The RealSubject of the ArMap Proxy. This implements
* the ArMapInterface and is an aggregate of all of the above map
* components.
*
* The following "diagram" illustrates the basic hierarchy:
*
* <pre>
*
* ________ArMapSupplementInterface________
* ^ ^
* | ________ArMapInfoInterface________ |
* | ^ ^ |
* | | __ArMapObjectsInterface___ | |
* | | ^ ^ | |
* | | | ArMapScanInterface | | |
* | | | ^ ^ | | |
* | | | | | | | |
* ArMapInterface | | | |
* ^ (extends) | | | | (extends)
* | | | | |
* | | | | |
* ArMapSimple +----------> ArMapScan | | |
* | (contains) | | |
* +-----------> ArMapObjects | |
* | | |
* +------------------> ArMapInfo |
* | |
* +----------------> ArMapSupplement
*
* </pre>
* @see ArMapInterface
* @see ArMap
**/
#ifndef ARMAPCOMPONENTS_H
#define ARMAPCOMPONENTS_H
#include "ArMapInterface.h"
class ArMapChangeDetails;
class ArMapFileLineSet;
class ArFileParser;
class ArMD5Calculator;
// ============================================================================
// ArMapScan
// ============================================================================
/// The map data related to the sensable obstacles in the environment.
/**
* ArMapScan encapsulates the data for a particular sensor that is generated
* during the scanning process (i.e. during the creation of a .2d file).
* The class's primary attributes are the points and line segments that
* were detected during the scan. It contains methods to get and set these
* coordinates, and to read and write the data from and to a file.
* <p>
* The <code>scanType</code> parameters identify the sensor used for scanning.
* The parameter is used in the constructor, but it is generally disregarded
* in the other methods. (The method signatures are defined in
* ArMapScanInterface, which is also implemented by ArMap. The map provides
* access to the scan data for all of the sensors -- and therefore uses the
* <code>scanType</code> parameters. This interface was chosen in order
* to maintain backwards compatibility with the original map.)
* <p>
* If the scanType is specified, then it is used as a prefix to the DATA and
* LINES tags that are contained in the map file.
**/
class ArMapScan : public ArMapScanInterface
{
public:
/// Constructor
/**
* Creates a new map scan object for the specified scan type.
* @param scanType the const char * identifier of the scan; must be
* non-NULL and must not contain whitespaces
**/
AREXPORT ArMapScan(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
/// Copy constructor
AREXPORT ArMapScan(const ArMapScan &other);
/// Assignment operator
AREXPORT ArMapScan &operator=(const ArMapScan &other);
/// Destructor
AREXPORT virtual ~ArMapScan();
// --------------------------------------------------------------------------
// ArMapScanInterface Methods
// --------------------------------------------------------------------------
AREXPORT virtual const char *getDisplayString
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual std::vector<ArPose> *getPoints
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual std::vector<ArLineSegment> *getLines
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getMinPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getMaxPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual int getNumPoints(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual bool isSortedPoints(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE) const;
AREXPORT virtual void setPoints(const std::vector<ArPose> *points,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
bool isSortedPoints = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual ArPose getLineMinPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getLineMaxPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual int getNumLines(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual bool isSortedLines(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE) const;
AREXPORT virtual void setLines(const std::vector<ArLineSegment> *lines,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
bool isSortedLines = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual int getResolution(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual void setResolution(int resolution,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeScanToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual void writePointsToFunctor
(ArFunctor2<int, std::vector<ArPose> *> *functor,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArFunctor1<const char *> *keywordFunctor = NULL);
AREXPORT virtual void writeLinesToFunctor
(ArFunctor2<int, std::vector<ArLineSegment> *> *functor,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArFunctor1<const char *> *keywordFunctor = NULL);
AREXPORT virtual bool addToFileParser(ArFileParser *fileParser);
AREXPORT virtual bool remFromFileParser(ArFileParser *fileParser);
AREXPORT virtual bool readDataPoint( char *line);
AREXPORT virtual bool readLineSegment( char *line);
AREXPORT virtual void loadDataPoint(double x, double y);
AREXPORT virtual void loadLineSegment(double x1, double y1, double x2, double y2);
// --------------------------------------------------------------------------
// Other Methods
// --------------------------------------------------------------------------
/// Resets the scan data, clearing all points and line segments
AREXPORT virtual void clear();
/// Combines the given other scan with this one.
/**
* @param other the ArMapScan * to be united with this one
* @param isIncludeDataPointsAndLines a bool set to true if the other scan's
* data points and lines should be copied to this scan; if false, then only
* the summary (bounding box, counts, etc) information is copied.
**/
AREXPORT virtual bool unite(ArMapScan *other,
bool isIncludeDataPointsAndLines = false);
/// Returns the time at which the scan data was last changed.
AREXPORT virtual ArTime getTimeChanged() const;
// TODO: Which of these need to be in the ArMapScanInterface?
/// Returns the unique string identifier of the associated scan type.
AREXPORT virtual const char *getScanType() const;
/// Returns the keyword that designates the scan's data points in the map file.
AREXPORT virtual const char *getPointsKeyword() const;
/// Returns the keyword that designates the scan's data lines in the map file.
AREXPORT virtual const char *getLinesKeyword() const;
/// Writes the scan's data points (and introductory keyword) to the given functor.
AREXPORT virtual void writePointsToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
/// Writes the scan's data lines (and introductory keyword) to the given functor.
AREXPORT virtual void writeLinesToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
/// Adds the handlers for the data points and lines keywords to the given file parser.
/**
* These handlers are "extra" because they are added after all of the summary
* keyword have been parsed.
**/
AREXPORT virtual bool addExtraToFileParser(ArFileParser *fileParser,
bool isAddLineHandler);
/// Removes the handlers for the data points and lines keywords from the given file parser.
AREXPORT virtual bool remExtraFromFileParser(ArFileParser *fileParser);
protected:
/// Writes the list of data lines to the given functor.
/**
* @param functor the ArFunctor1<const char *> * to which to write the
* data lines
* @param lines the vector of ArLineSegments to be written to the functor
* @param endOfLineChars an optional string to be appended to the end of
* each text line written to the functor
* @param scanType the unique string identifier of the scan type associated
* with the data lines
**/
AREXPORT virtual void writeLinesToFunctor
(ArFunctor1<const char *> *functor,
const std::vector<ArLineSegment> &lines,
const char *endOfLineChars,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
// Function to read the minimum pos
bool handleMinPos(ArArgumentBuilder *arg);
// Function to read the maximum pos
bool handleMaxPos(ArArgumentBuilder *arg);
// Function to read the number of points
bool handleNumPoints(ArArgumentBuilder *arg);
// Function to read whether the points are sorted
bool handleIsSortedPoints(ArArgumentBuilder *arg);
// Function to read the line minimum pos
bool handleLineMinPos(ArArgumentBuilder *arg);
// Function to read the line maximum pos
bool handleLineMaxPos(ArArgumentBuilder *arg);
// Function to read the number of lines
bool handleNumLines(ArArgumentBuilder *arg);
// Function to read whether the lines are sorted
bool handleIsSortedLines(ArArgumentBuilder *arg);
// Function to handle the resolution
bool handleResolution(ArArgumentBuilder *arg);
/// Callback to handle the Display string.
bool handleDisplayString(ArArgumentBuilder *arg);
// Function to snag the map points (mainly for the getMap over the network)
bool handlePoint(ArArgumentBuilder *arg);
// Function to snag the line segments (mainly for the getMap over the network)
bool handleLine(ArArgumentBuilder *arg);
/// Adds the specified argument handler to the given file parser.
bool addHandlerToFileParser(ArFileParser *fileParser,
const char *keyword,
ArRetFunctor1<bool, ArArgumentBuilder *> *handler);
/// Returns the keyword prefix for this scan type.
const char *getKeywordPrefix() const;
/// Parses a pose from the given arguments.
bool parsePose(ArArgumentBuilder *arg,
const char *keyword,
ArPose *poseOut);
/// Parses an integer from the given text line.
bool parseNumber(char *line,
size_t lineLen,
size_t *charCountOut,
int *numOut) const;
/// Parses whitespace from the given text line.
bool parseWhitespace(char *line,
size_t lineLen,
size_t *charCountOut) const;
private:
/// Constant appended to the end of each scan data text line.
static const char *EOL_CHARS;
protected:
/// The unique string identifier of this scan type.
std::string myScanType;
/// Whether this is a special summary of the other scans.
bool myIsSummaryScan;
/// The prefix prepended to the output log file messages.
std::string myLogPrefix;
/// The prefix prepended to the map file keywords (e.g. DATA and LINES)
std::string myKeywordPrefix;
/// The keyword that designates this scan's data points in the map file.
std::string myPointsKeyword;
/// The keyword that designates this scan's data lines in the map file.
std::string myLinesKeyword;
/// Time that this scan data was last modified.
ArTime myTimeChanged;
/// Displayable text for this scan type.
std::string myDisplayString;
/// Number of data points in the scan.
int myNumPoints;
/// Number of data lines in the scan.
int myNumLines;
/// Resolution of the data points (in mm).
int myResolution;
/// Maximum x/y values of all of the data points in the scan.
ArPose myMax;
/// Minimum x/y values of all of the data points in the scan.
ArPose myMin;
/// Maximum x/y values of all of the data lines in the scan.
ArPose myLineMax;
/// Minimum x/y values of all of the data lines in the scan.
ArPose myLineMin;
/// Whether the data points in myPoints have been sorted in ascending order.
bool myIsSortedPoints;
/// Whether the data lines in myLines have been sorted in ascending order.
bool myIsSortedLines;
/// List of data points contained in this scan data.
std::vector<ArPose> myPoints;
/// List of data lines contained in this scan data.
std::vector<ArLineSegment> myLines;
/// Callback to parse the minimum poise from the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myMinPosCB;
/// Callback to parse the maximum pose from the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myMaxPosCB;
/// Callback to parse whether the points in the map file have been sorted.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myIsSortedPointsCB;
/// Callback to parse the number of data points in the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myNumPointsCB;
/// Callback to parse the minimum line pose from the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myLineMinPosCB;
/// Callback to parse the maximum line pose from the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myLineMaxPosCB;
/// Callback to parse whether the lines in the map file have been sorted.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myIsSortedLinesCB;
/// Callback to parse the number of data lines in the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myNumLinesCB;
/// Callback to parse the resolution in the map file.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myResolutionCB;
/// Callback to parse the displayable text for this scan type.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myDisplayStringCB;
/// Callback to parse a data point.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myPointCB;
/// Callback to parse a data line.
ArRetFunctor1C<bool, ArMapScan, ArArgumentBuilder *> myLineCB;
}; // end class ArMapScan
// ============================================================================
// ArMapObjects
// ============================================================================
/// The collection of map objects that are contained in an Aria map.
/**
* ArMapObjects contains a list of objects defined in an Aria map. There are
* two basic classes of objects: user-defined objects such as goals and
* forbidden areas; and, special data objects that are usually automatically
* generated during the scanning process.
**/
class ArMapObjects : public ArMapObjectsInterface
{
public :
/// Default keyword that prefixes each map object line in the map file
AREXPORT static const char *DEFAULT_KEYWORD;
/// Constructor
/**
* @param keyword the char * keyword that prefixes each map object line in
* the map file
**/
AREXPORT ArMapObjects(const char *keyword = "Cairn:");
/// Copy constructor
AREXPORT ArMapObjects(const ArMapObjects &other);
/// Assignment operator
AREXPORT ArMapObjects &operator=(const ArMapObjects &other);
/// Destructor
AREXPORT virtual ~ArMapObjects();
// ---------------------------------------------------------------------------
// ArMapObjectsInterface Methods
// ---------------------------------------------------------------------------
AREXPORT virtual ArMapObject *findFirstMapObject(const char *name,
const char *type,
bool isIncludeWithHeading = false);
AREXPORT virtual ArMapObject *findMapObject(const char *name,
const char *type = NULL,
bool isIncludeWithHeading = false);
AREXPORT virtual std::list<ArMapObject *> findMapObjectsOfType
(const char *type,
bool isIncludeWithHeading = false);
AREXPORT virtual std::list<ArMapObject *> *getMapObjects(void);
AREXPORT virtual void setMapObjects(const std::list<ArMapObject *> *mapObjects,
bool isSortedObjects = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT void writeObjectListToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
// ---------------------------------------------------------------------------
// Other Methods
// ---------------------------------------------------------------------------
/// Clears the map objects and deletes them.
AREXPORT virtual void clear();
/// Adds the keyword and handler for the map objects to the given file parser.
AREXPORT virtual bool addToFileParser(ArFileParser *fileParser);
/// Removes the keyword and handler for the map objects from the given file parser.
AREXPORT virtual bool remFromFileParser(ArFileParser *fileParser);
/// Returns the time at which the map objects were last changed.
AREXPORT virtual ArTime getTimeChanged() const;
protected:
// Function to handle the cairns
bool handleMapObject(ArArgumentBuilder *arg);
/// Sorts the given list of map objects in order of increasing object pose.
void sortMapObjects(std::list<ArMapObject *> *mapObjects);
/// Writes the map objects to the given ArMapFileLineSet.
void createMultiSet(ArMapFileLineSet *multiSet);
/// Writes the given ArMapFileLineSet to the output log with the specified prefix.
void logMultiSet(const char *prefix,
ArMapFileLineSet *multiSet);
protected:
/// Time at which the map objects were last changed.
ArTime myTimeChanged;
/// Whether the myMapObjects list has been sorted in increasing (pose) order.
bool myIsSortedObjects;
/// Keyword that prefixes each map object in the map file.
std::string myKeyword;
/// List of map objects contained in the Aria map.
std::list<ArMapObject *> myMapObjects;
/// Callback to parse the map object from the map file.
ArRetFunctor1C<bool, ArMapObjects, ArArgumentBuilder *> myMapObjectCB;
}; // end class ArMapObjects
// ============================================================================
// ArMapInfo
// ============================================================================
/// A container for the various "info" tags in an Aria map.
/**
* ArMapInfo is an implementation of ArMapInfoInterface that provides access
* to a collection of "info" arguments (such as MapInfo and RouteInfo). An Aria
* map may have one or more categories of info, each implemented by an ordered
* list of ArArgumentBuilder's.
*
* Info types are currently identified by a unique integer. The default types
* are defined in ArMapInfoInterface::InfoType, but applications may define
* additional types. (See ArMapInfo::ArMapInfo(int*, char**, size_t))
**/
class ArMapInfo : public ArMapInfoInterface
{
public:
/// Contructor
/**
* @param infoNameList an array of the char * keywords for each of the
* standard ArMapInfo::InfoType's; if NULL, then the default keywords are
* used
* @param infoNameCount the size_t length of the infoNameList array
* @param keywordPrefix optional prefix to add to keywords.
**/
AREXPORT ArMapInfo(const char **infoNameList = NULL,
size_t infoNameCount = 0,
const char *keywordPrefix = NULL);
/// Copy contructor
AREXPORT ArMapInfo(const ArMapInfo &other);
/// Assignment operator
AREXPORT ArMapInfo &operator=(const ArMapInfo &other);
/// Destructor
AREXPORT virtual ~ArMapInfo();
// ---------------------------------------------------------------------------
// ArMapInfoInterface Methods
// ---------------------------------------------------------------------------
AREXPORT virtual std::list<ArArgumentBuilder *> *getInfo(const char *infoName);
AREXPORT virtual std::list<ArArgumentBuilder *> *getInfo(int infoType);
AREXPORT virtual std::list<ArArgumentBuilder *> *getMapInfo(void);
AREXPORT virtual int getInfoCount() const;
AREXPORT virtual std::list<std::string> getInfoNames() const;
AREXPORT virtual bool setInfo(const char *infoName,
const std::list<ArArgumentBuilder *> *infoList,
ArMapChangeDetails *changeDetails);
AREXPORT virtual bool setInfo(int infoType,
const std::list<ArArgumentBuilder *> *infoList,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual bool setMapInfo(const std::list<ArArgumentBuilder *> *mapInfo,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual const char *getInfoName(int infoType);
AREXPORT virtual void writeInfoToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
// ---------------------------------------------------------------------------
// Other Methods
// ---------------------------------------------------------------------------
/// Clears all info arguments and deletes them.
AREXPORT virtual void clear();
/// Adds handlers for all of the info types to the given file parser.
AREXPORT virtual bool addToFileParser(ArFileParser *fileParser);
/// Removes handlers for all of the info types from the given file parser.
AREXPORT virtual bool remFromFileParser(ArFileParser *fileParser);
/// Returns the time at which the info were last changed.
AREXPORT virtual ArTime getTimeChanged() const;
protected:
/// Processes the given argument for the specified info.
bool handleInfo(ArArgumentBuilder *arg);
/// Give ArMapSimple access to the createMultiSet() and setChanged() methods
friend class ArMapSimple;
/// Writes the specified info arguments to the given ArMapFileLineSet.
/**
* @param infoName unique identifier for the info to be written
* @param multiSet the ArMapFileLineSet * to which to write the info;
* must be non-NULL
* @param changeDetails the ArMapChangeDetails * that specifies the
* parent/child relationship amongst info lines
* @see ArMapChangeDetails::isChildArg
**/
void createMultiSet(const char *infoName,
ArMapFileLineSet *multiSet,
ArMapChangeDetails *changeDetails);
/// Basically updates the timeChanged to now.
void setChanged();
/// Populates this object with the default info names / keywords
void setDefaultInfoNames();
protected:
struct ArMapInfoData {
ArMapInfo *myParent;
int myType;
std::string myKeyword;
std::list<ArArgumentBuilder *> myInfo;
ArRetFunctor1C<bool, ArMapInfo, ArArgumentBuilder *> *myInfoCB;
ArMapInfoData(ArMapInfo *parent,
const char *name = NULL,
int type = -1);
~ArMapInfoData();
ArMapInfoData(ArMapInfo *parent,
const ArMapInfoData &other);
ArMapInfoData &operator=(const ArMapInfoData &other);
}; // end struct ArMapInfoData
typedef std::map<std::string, ArMapInfoData *, ArStrCaseCmpOp> ArInfoNameToDataMap;
AREXPORT ArMapInfoData *findData(const char *infoName);
AREXPORT ArMapInfoData *findDataByKeyword(const char *keyword);
/// Time at which the info was last changed
ArTime myTimeChanged;
// Sigh... In retrospect, this should have been structured differently
// and we probably should've used a string for the info identifier...
/// Number of info types contained in this collection
int myNumInfos;
std::string myPrefix;
std::map<int, std::string> myInfoTypeToNameMap;
ArInfoNameToDataMap myInfoNameToDataMap;
std::map<std::string, std::string, ArStrCaseCmpOp> myKeywordToInfoNameMap;
}; // end class ArMapInfo
// ============================================================================
// ArMapSupplement
// ============================================================================
/// Supplemental data associated with an Aria map.
/**
* ArMapSupplement is a repository for extra, miscellaneous data that is
* associated with an Aria map but which does not fit neatly into any of the
* other components.
**/
class ArMapSupplement : public ArMapSupplementInterface
{
public:
/// Constructor
AREXPORT ArMapSupplement();
/// Copy constructor
AREXPORT ArMapSupplement(const ArMapSupplement &other);
/// Assignment operator
AREXPORT ArMapSupplement &operator=(const ArMapSupplement &other);
/// Destructor
AREXPORT virtual ~ArMapSupplement();
// --------------------------------------------------------------------------
// ArMapSupplementInterface Methods
// --------------------------------------------------------------------------
AREXPORT virtual bool hasOriginLatLongAlt();
AREXPORT virtual ArPose getOriginLatLong();
AREXPORT virtual double getOriginAltitude();
AREXPORT virtual void setOriginLatLongAlt(bool hasOriginLatLong,
const ArPose &originLatLong,
double altitude,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeSupplementToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
// --------------------------------------------------------------------------
// Other Methods
// --------------------------------------------------------------------------
/// Resets the map supplement to its default values.
AREXPORT virtual void clear();
/// Adds handlers for all of the supplement keywords to the given file parser.
AREXPORT virtual bool addToFileParser(ArFileParser *fileParser);
/// Removes handlers for all of the supplement keywords from the given file parser.
AREXPORT virtual bool remFromFileParser(ArFileParser *fileParser);
/// Returns the time at which the supplement data were last changed.
AREXPORT virtual ArTime getTimeChanged() const;
protected:
// Function to get the origin lat long altitude
bool handleOriginLatLongAlt(ArArgumentBuilder *arg);
private:
/// Constant appended to the end of each supplement text line.
static const char *EOL_CHARS;
protected:
/// Time at which the supplement was last changed
ArTime myTimeChanged;
/// Whether the supplement data contains latitude/longitude information for the origin
bool myHasOriginLatLongAlt;
/// The latitude/longitude of the origin; only if myHasOriginLatLongAlt is true
ArPose myOriginLatLong;
/// The altitude (in m) of the origin; only if myHasOriginLatLongAlt is true
double myOriginAltitude;
/// Callback that parses the origin latitude/longitude/altitude information
ArRetFunctor1C<bool, ArMapSupplement, ArArgumentBuilder *> myOriginLatLongAltCB;
}; // end class ArMapSupplement
// =============================================================================
// ArMapSimple
// =============================================================================
/// Comparator used to sort scan data types in a case-insensitive manner.
struct ArDataTagCaseCmpOp
{
public:
bool operator() (const std::string &s1, const std::string &s2) const
{
size_t s1Len = s1.length();
size_t s2Len = s2.length();
if (s1Len < s2Len) {
return strncasecmp(s1.c_str(), s2.c_str(), s1Len) < 0;
}
else {
return strncasecmp(s1.c_str(), s2.c_str(), s2Len) < 0;
}
}
}; // end struct ArDataTagCaseCmpOp
/// Type definition for a map of scan types to scan data.
typedef std::map<std::string, ArMapScan *, ArStrCaseCmpOp> ArTypeToScanMap;
/// Type definition for a map of data tags to scan types
typedef std::map<std::string, std::string, ArDataTagCaseCmpOp> ArDataTagToScanTypeMap;
/// Simple map that can be read from and written to a file
/**
* ArMapSimple is the real subject of the ArMap proxy. Functionally, it is identical
* to the ArMap, @b except that it is not well-suited for for loading from a file at
* runtime and therefore doesn't provide any hooks into the Aria config. In general,
* ArMap should be used instead. The exception to this rule may be in off-line
* authoring tools where error checking can be performed at a higher level.
**/
class ArMapSimple : public ArMapInterface
{
public:
/// Constructor
/**
* @param baseDirectory the name of the directory in which to search for map
* files that are not fully qualified
* @param tempDirectory the name of the directory in which to write temporary
* files when saving a map; if NULL, then the map file is written directly.
* Note that using a temp file reduces the risk that the map will be corrupted
* if the application crashes.
* @param overrideMutexName an optional name to be used for the map object's
* mutex; useful for debugging when multiple maps are active
**/
AREXPORT ArMapSimple(const char *baseDirectory = "./",
const char *tempDirectory = NULL,
const char *overrideMutexName = NULL);
/// Copy constructor
AREXPORT ArMapSimple(const ArMapSimple &other);
/// Assignment operator
AREXPORT ArMapSimple &operator=(const ArMapSimple &other);
/// Destructor
AREXPORT virtual ~ArMapSimple(void);
AREXPORT virtual void clear();
AREXPORT virtual bool set(ArMapInterface *other);
AREXPORT virtual ArMapInterface *clone();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Scan Types Methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual std::list<std::string> getScanTypes() const;
AREXPORT virtual bool setScanTypes(const std::list<std::string> &scanTypeList);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Locking / Semaphore Method
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual int lock();
AREXPORT virtual int tryLock();
AREXPORT virtual int unlock();
// ---------------------------------------------------------------------------
// ArMapInfoInterface
// ---------------------------------------------------------------------------
AREXPORT virtual std::list<ArArgumentBuilder *> *getInfo(const char *infoName);
AREXPORT virtual std::list<ArArgumentBuilder *> *getInfo(int infoType);
AREXPORT virtual std::list<ArArgumentBuilder *> *getMapInfo(void);
AREXPORT virtual int getInfoCount() const;
AREXPORT virtual std::list<std::string> getInfoNames() const;
AREXPORT virtual bool setInfo(const char *infoName,
const std::list<ArArgumentBuilder *> *infoList,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual bool setInfo(int infoType,
const std::list<ArArgumentBuilder *> *infoList,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual bool setMapInfo(const std::list<ArArgumentBuilder *> *mapInfo,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeInfoToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
AREXPORT virtual const char *getInfoName(int infoType);
// ---------------------------------------------------------------------------
// ArMapObjectsInterface
// ---------------------------------------------------------------------------
AREXPORT virtual ArMapObject *findFirstMapObject(const char *name,
const char *type,
bool isIncludeWithHeading = false);
AREXPORT virtual ArMapObject *findMapObject(const char *name,
const char *type = NULL,
bool isIncludeWithHeading = false);
AREXPORT virtual std::list<ArMapObject *> findMapObjectsOfType
(const char *type,
bool isIncludeWithHeading = false);
AREXPORT virtual std::list<ArMapObject *> *getMapObjects(void);
AREXPORT virtual void setMapObjects(const std::list<ArMapObject *> *mapObjects,
bool isSortedObjects = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeObjectListToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
// ---------------------------------------------------------------------------
// ArMapSupplementInterface
// ---------------------------------------------------------------------------
AREXPORT virtual bool hasOriginLatLongAlt();
AREXPORT virtual ArPose getOriginLatLong();
AREXPORT virtual double getOriginAltitude();
AREXPORT virtual void setOriginLatLongAlt
(bool hasOriginLatLong,
const ArPose &originLatLong,
double altitude,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeSupplementToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
// ---------------------------------------------------------------------------
// ArMapScanInterface
// ---------------------------------------------------------------------------
AREXPORT virtual const char *getDisplayString
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual std::vector<ArPose> *getPoints
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getMinPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getMaxPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual int getNumPoints(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual bool isSortedPoints(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE) const;
AREXPORT virtual void setPoints(const std::vector<ArPose> *points,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
bool isSortedPoints = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual std::vector<ArLineSegment> *getLines
(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getLineMinPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual ArPose getLineMaxPose(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual int getNumLines(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual bool isSortedLines(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE) const;
AREXPORT virtual void setLines(const std::vector<ArLineSegment> *lines,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
bool isSortedLines = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual int getResolution(const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual void setResolution(int resolution,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual void writeScanToFunctor
(ArFunctor1<const char *> *functor,
const char *endOfLineChars,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE);
AREXPORT virtual void writePointsToFunctor
(ArFunctor2<int, std::vector<ArPose> *> *functor,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArFunctor1<const char *> *keywordFunctor = NULL);
AREXPORT virtual void writeLinesToFunctor
(ArFunctor2<int, std::vector<ArLineSegment> *> *functor,
const char *scanType = ARMAP_DEFAULT_SCAN_TYPE,
ArFunctor1<const char *> *keywordFunctor = NULL);
AREXPORT virtual bool addToFileParser(ArFileParser *fileParser);
AREXPORT virtual bool remFromFileParser(ArFileParser *fileParser);
AREXPORT virtual bool readDataPoint( char *line);
AREXPORT virtual bool readLineSegment( char *line);
/** Public for ArQClientMapProducer **/
AREXPORT virtual void loadDataPoint(double x, double y);
AREXPORT virtual void loadLineSegment(double x1, double y1, double x2, double y2);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Map Changed / Callback Methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual void mapChanged(void);
AREXPORT virtual void addMapChangedCB(ArFunctor *functor,
int position = 50);
AREXPORT virtual void remMapChangedCB(ArFunctor *functor);
AREXPORT virtual void addPreMapChangedCB(ArFunctor *functor,
int position = 50);
AREXPORT virtual void remPreMapChangedCB(ArFunctor *functor);
AREXPORT virtual void setMapChangedLogLevel(ArLog::LogLevel level);
AREXPORT virtual ArLog::LogLevel getMapChangedLogLevel(void);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Persistence
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual void writeToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
AREXPORT virtual void writeObjectsToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars,
bool isOverrideAsSingleScan = false,
const char *maxCategory = NULL);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// File I/O Methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual void addPreWriteFileCB(ArFunctor *functor,
ArListPos::Pos position = ArListPos::LAST);
AREXPORT virtual void remPreWriteFileCB(ArFunctor *functor);
AREXPORT virtual void addPostWriteFileCB(ArFunctor *functor,
ArListPos::Pos position = ArListPos::LAST);
AREXPORT virtual void remPostWriteFileCB(ArFunctor *functor);
AREXPORT virtual bool readFile(const char *fileName,
char *errorBuffer = NULL,
size_t errorBufferLen = 0,
unsigned char *md5DigestBuffer = NULL,
size_t md5DigestBufferLen = 0);
AREXPORT virtual bool writeFile(const char *fileName,
bool internalCall = false,
unsigned char *md5DigestBuffer = NULL,
size_t md5DigestBufferLen = 0,
time_t fileTimestamp = -1);
#ifndef SWIG
/// @swigomit
AREXPORT virtual struct stat getReadFileStat() const;
#endif
AREXPORT virtual bool getMapId(ArMapId *mapIdOut,
bool isInternalCall = false);
AREXPORT virtual bool calculateChecksum(unsigned char *md5DigestBuffer,
size_t md5DigestBufferLen);
AREXPORT virtual const char *getBaseDirectory(void) const;
AREXPORT virtual void setBaseDirectory(const char *baseDirectory);
AREXPORT virtual const char *getTempDirectory(void) const;
AREXPORT virtual void setTempDirectory(const char *tempDirectory);
AREXPORT virtual std::string createRealFileName(const char *fileName);
AREXPORT virtual const char *getFileName(void) const;
AREXPORT virtual void setSourceFileName(const char *sourceName,
const char *fileName,
bool isInternalCall = false);
AREXPORT virtual bool refresh();
virtual void setIgnoreEmptyFileName(bool ignore);
virtual bool getIgnoreEmptyFileName(void);
virtual void setIgnoreCase(bool ignoreCase = false);
virtual bool getIgnoreCase(void);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Inactive Section
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual ArMapInfoInterface *getInactiveInfo();
AREXPORT virtual ArMapObjectsInterface *getInactiveObjects();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Child Objects Section
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual ArMapObjectsInterface *getChildObjects();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Miscellaneous
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual ArArgumentBuilder *findMapObjectParams(const char *mapObjectName);
AREXPORT virtual bool setMapObjectParams(const char *mapObjectName,
ArArgumentBuilder *params,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT virtual std::list<ArArgumentBuilder *> *getRemainder();
AREXPORT virtual void setQuiet(bool isQuiet);
AREXPORT bool parseLine(char *line);
AREXPORT void parsingComplete(void);
AREXPORT bool isLoadingDataStarted();
AREXPORT bool isLoadingLinesAndDataStarted();
// ---------------------------------------------------------------------
#ifndef SWIG
/// Searches the given CairnInfo list for an entry that matches the given mapObject.
/**
* The CairnInfo list stores the parameter information (if any) for map
* objects. If a map object is removed (or activated), then the CairnInfo
* must also be updated.
* @param mapObjectName the ArMapObject for which to find the parameters
* @param cairnInfoList the list of ArArgumentBuilder *'s that contain the
* map object parameters (also may be set to the inactive section)
* @return iterator that points to the parameter information for the map
* object, or cairnInfoList.end() if not found
**/
AREXPORT static std::list<ArArgumentBuilder *>::iterator findMapObjectParamInfo
(const char *mapObjectName,
std::list<ArArgumentBuilder*> &cairnInfoList);
#endif
protected:
AREXPORT bool setInactiveInfo(const char *infoName,
const std::list<ArArgumentBuilder *> *infoList,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT void setInactiveObjects(const std::list<ArMapObject *> *mapObjects,
bool isSortedObjects = false,
ArMapChangeDetails *changeDetails = NULL);
AREXPORT void setChildObjects(const std::list<ArMapObject *> *mapObjects,
bool isSortedObjects = false,
ArMapChangeDetails *changeDetails = NULL);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/// Callback that handles the different types of map categories (e.g. 2D-Map, 2D-Map-Ex)
/**
* This method replaces the old handle2DMap method. It determines which category
* was detected and sets the myMapCategory attribute accordingly.
* @param arg a pointer to the parsed ArArgumentBuilder; no arguments are expected
**/
bool handleMapCategory(ArArgumentBuilder *arg);
/// Callback that handles the Sources keyword
/**
* @param arg a pointer to the parsed ArArgumentBuilder; a list of string scan type
* arguments are expected
**/
bool handleSources(ArArgumentBuilder *arg);
/// Callback that handles the different types of data introductions (e.g. DATA, LINES)
/**
* This method replaces the old handleData and handleLines methods. It determines
* which keyword was detected and updates the myLoadingDataTag and myLoadingScan
* attributes accordingly.
* @param arg a pointer to the parsed ArArgumentBuilder; no arguments are expected
**/
bool handleDataIntro(ArArgumentBuilder *arg);
bool handleRemainder(ArArgumentBuilder *arg);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/// Returns the ArMapScan for the specified scan type.
AREXPORT virtual ArMapScan *getScan(const char *scanType) const;
/// Sets up the map to contain teh specified scan types.
/**
* Any scans which are currently in the map are cleared and removed.
* This method is not virtual because it is called by the constructor.
* @param scanTypeList a list of the scan type string identifiers to be
* created; the list must be non-empty and must not contain duplicates;
* if the list contains more than one entry, then they all must be
* non-empty
* @return bool true if the scans were successfully created; false otherwise
**/
bool createScans(const std::list<std::string> &scanTypeList);
/// Adds all of the map's scan types to the current file parser.
/**
* This method calls addToFileParser() on each of the map's scans. It also
* adds handlers for each of the scans' data point and line introduction
* keywords.
* @return bool true if the scans were successfully added to the current
* file parser
**/
bool addScansToParser();
/// Removes all of the map's scan types from the current file parser.
bool remScansFromParser(bool isRemovePointsAndLinesKeywords = true);
AREXPORT void writeScanTypesToFunctor(ArFunctor1<const char *> *functor,
const char *endOfLineChars);
AREXPORT ArTime findMaxMapScanTimeChanged();
AREXPORT ArMapScan *findScanWithDataKeyword(const char *myLoadingDataTag,
bool *isLineDataTagOut);
AREXPORT void updateSummaryScan();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AREXPORT virtual const char *getMapCategory();
AREXPORT virtual void updateMapCategory(const char *updatedInfoName = NULL);
AREXPORT virtual bool mapInfoContains(const char *arg0Text);
AREXPORT bool isDataTag(const char *line);
AREXPORT void reset();
AREXPORT void updateMapFileInfo(const char *realFileName);
AREXPORT static int getNextFileNumber();
AREXPORT void invokeCallbackList(std::list<ArFunctor*> *cbList);
AREXPORT void addToCallbackList(ArFunctor *functor,
ArListPos::Pos position,
std::list<ArFunctor*> *cbList);
AREXPORT void remFromCallbackList(ArFunctor *functor,
std::list<ArFunctor*> *cbList);
protected:
// static const char *ourDefaultInactiveInfoNames[INFO_COUNT];
static int ourTempFileNumber;
static ArMutex ourTempFileNumberMutex;
// lock for our data
ArMutex myMutex;
std::list<std::string> myMapCategoryList;
std::string myMapCategory;
ArMD5Calculator *myChecksumCalculator;
std::string myBaseDirectory;
std::string myFileName;
struct stat myReadFileStat;
std::list<ArFunctor*> myPreWriteCBList;
std::list<ArFunctor*> myPostWriteCBList;
bool myIsWriteToTempFile;
std::string myTempDirectory;
ArMapId myMapId;
ArFileParser *myLoadingParser;
// std::string myConfigParam;
bool myIgnoreEmptyFileName;
bool myIgnoreCase;
ArMapChangedHelper *myMapChangedHelper;
/***
// things for our config
bool myConfigProcessedBefore;
char myConfigMapName[MAX_MAP_NAME_LENGTH];
***/
bool myLoadingGotMapCategory;
// TODO: Need to change for multi scans
bool myLoadingDataStarted;
bool myLoadingLinesAndDataStarted;
ArMapInfo * const myMapInfo;
ArMapObjects * const myMapObjects;
ArMapSupplement * const myMapSupplement;
std::list<std::string> myScanTypeList;
ArTypeToScanMap myTypeToScanMap;
ArMapScan * mySummaryScan;
ArDataTagToScanTypeMap myDataTagToScanTypeMap;
std::string myLoadingDataTag;
ArMapScan * myLoadingScan;
ArMapInfo * const myInactiveInfo;
ArMapObjects * const myInactiveObjects;
ArMapObjects * const myChildObjects;
std::map<std::string, ArArgumentBuilder *, ArStrCaseCmpOp> myMapObjectNameToParamsMap;
/// List of map file lines that were not recognized
std::list<ArArgumentBuilder *> myRemainderList;
ArTime myTimeMapInfoChanged;
ArTime myTimeMapObjectsChanged;
ArTime myTimeMapScanChanged;
ArTime myTimeMapSupplementChanged;
// callbacks
ArRetFunctor1C<bool, ArMapSimple, ArArgumentBuilder *> myMapCategoryCB;
ArRetFunctor1C<bool, ArMapSimple, ArArgumentBuilder *> mySourcesCB;
ArRetFunctor1C<bool, ArMapSimple, ArArgumentBuilder *> myDataIntroCB;
// Handler for unrecognized lines
ArRetFunctor1C<bool, ArMapSimple, ArArgumentBuilder *> myRemCB;
bool myIsQuiet;
bool myIsReadInProgress;
bool myIsCancelRead;
}; // end class ArMapSimple
/// ---------------------------------------------------------------------------
#endif // ARMAPCOMPONENTS_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArSensorReading.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSENSORREADING_H
#define ARSENSORREADING_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArTransform.h"
/// Used to convert and store data from and/or about a range sensor
/** This class holds sensor information and a sensor reading position and other
data
(X,Y location of the reading (typically in robot's global coordinate system) plus a counter and timestamp for that reading,
position of the robot when the reading was taken, and other information).
This class can optionally be used to only store information about the sensor, but no reading
data, in which case the range (getRange()) will be -1, and the counter
(getCounterTaken()) value will be 0, and isNew() will return false as well.
The ignoreThisReading() indicates whether applications should ignore the
data or not. (Used to disable sensors data in robot and application
configuration.)
Typical use is to create an ArSensorReading object representing an indidiual
sensor that can sense distance (range) in one direction, or a set of
ArSensorReadings corresponding to the set of range data returned by a sensor
that provides multiple range measurements (e.g. most scanning laser
rangefinders provide a set of readings, each at different angles but from the
same measurement origin point. The ArRangeDevice subclasses for laser
rangefinders in ARIA use a set of ArSensorReading objects to store and convert
the raw range data read from the laser rangefinder device, then those are used
to update the "raw", "current" and other ArRangeBuffer objects in
ArRangeDevice.)
Provide the position and orientation of the sensor reading relative to the
center of the robot in the ArSensorReading constructor, or call
resetSensorPosition() to change.
Update data in an ArSensorReading object by calling newData(). The range
value provided will be projected to a local cartesian cooridate based on the
ArSensorReadings sensor position on the robot as supplied in the constructor or call to
resetSensorPosition(), and alrso transformed a global coordinate system based on a supplied
transform (usually this is the robot's global coordinate system using
ArRobot::getToGlobalTransform()). An incrementing counter must also be provided, and
a timestamp. The counter is used to check for updated data (by this class
and other classes using ArSensorReading objects), so it should
increment when data is updated. The timestamp may be used by other classes
to determine age of data.
*/
class ArSensorReading
{
public:
/// Constructor, the three args are the physical location of the sensor
AREXPORT ArSensorReading(double xPos = 0.0, double yPos = 0.0, double thPos = 0.0);
/// Copy constructor
AREXPORT ArSensorReading(const ArSensorReading & reading);
/// Assignment operator
AREXPORT ArSensorReading &operator=(const ArSensorReading &reading);
/// Destructor
AREXPORT virtual ~ArSensorReading();
/// Gets the range from sensor of the reading
/**
@return the distance to the reading from the sensor itself
*/
unsigned int getRange(void) const { return myRange; }
/// Given the counter from the robot, it returns whether the reading is new
/**
@param counter the counter from the robot at the current time
@return true if the reading was taken on the current loop
@see getCounter
*/
bool isNew(unsigned int counter) const { return counter == myCounterTaken; }
/// Gets the X location of the sensor reading
double getX(void) const { return myReading.getX(); }
/// Gets the Y location of the sensor reading
double getY(void) const { return myReading.getY(); }
/// Gets the position of the reading
/// @return the position of the reading (ie where the sonar pinged back)
ArPose getPose(void) const { return myReading; }
/// Gets the X location of the sensor reading in local coords
double getLocalX(void) const { return myLocalReading.getX(); }
/// Gets the Y location of the sensor reading
double getLocalY(void) const { return myLocalReading.getY(); }
/// Gets the position of the reading
/// @return the position of the reading (ie the obstacle where the sonar pinged back)
ArPose getLocalPose(void) const { return myLocalReading; }
/** Gets the pose of the robot at which the reading was taken
@sa getEncoderPoseTaken()
@sa getTimeTaken()
@sa ArRobot::getPose()
*/
ArPose getPoseTaken(void) const { return myReadingTaken; }
/** Gets the robot's encoder pose the reading was taken at
@sa getPoseTaken()
@sa ArRobot::getEncoderPose()
*/
ArPose getEncoderPoseTaken(void) const { return myEncoderPoseTaken; }
/** Gets the X location of the sonar on the robot
@sa getSensorPosition()
*/
double getSensorX(void) const { return mySensorPos.getX(); }
/** Gets the Y location of the sensor on the robot
@sa getsensorPosition()
*/
double getSensorY(void) const { return mySensorPos.getY(); }
/** Gets the heading of the sensor on the robot
@sa getsensorPosition()
*/
double getSensorTh(void) const { return mySensorPos.getTh(); }
/// Gets whether this reading should be ignore or not. e.g. the sensor
/// encountered an error or did not actually detect anything.
bool getIgnoreThisReading(void) const { return myIgnoreThisReading; }
/// Gets the extra int with this reading
/**
Some range devices provide extra device-dependent information
with each reading. What that means depends on the range device,
if a range device doesn't give the meaning in its constructor
description then it has no meaning at all.
Note that for all laser like devices this should be a value
between 0 - 255 which is the measure of reflectance. It should
be 0 if that device doesn't measure reflectance (the default).
**/
int getExtraInt(void) const { return myExtraInt; }
/// Gets the sensor's position on the robot
/**
@return the position of the sensor on the robot
*/
ArPose getSensorPosition(void) const { return mySensorPos; }
/// Gets the cosine component of the heading of the sensor reading
double getSensorDX(void) const { return mySensorCos; }
/// Gets the sine component of the heading of the sensor reading
double getSensorDY(void) const { return mySensorSin; }
/** Gets the X locaiton of the robot when the reading was received
@sa getPoseTaken()
*/
double getXTaken(void) const { return myReadingTaken.getX(); }
/** Gets the Y location of the robot when the reading was received
@sa getPoseTaken()
*/
double getYTaken(void) const { return myReadingTaken.getY(); }
/** Gets the th (heading) of the robot when the reading was received
@sa getPoseTaken()
*/
double getThTaken(void) const { return myReadingTaken.getTh(); }
/// Gets the counter from when the reading arrived
/**
@return the counter from the robot when the sonar reading was taken
@see isNew
*/
unsigned int getCounterTaken(void) const { return myCounterTaken; }
ArTime getTimeTaken(void) const { return myTimeTaken; }
/**
Update data.
@param range Sensed distance. Will be projected to a global X,Y position based on the sensor position and @a robotPose
@param robotPose Robot position in global coordinates space when the sensor data was received.
@param encoderPose Robot encoder-only position in global coordinate space when the sensor data was received.
@param trans Transform reading position from robot-local coordinate system.
For example, pass result of ArRobot::getToGlobalTransform() transform to robot's global
coordinate system.
@param counter an incrementing counter used to check for updated data (by this class
and other classes using ArSensorReading objects)
@param timeTaken System time when this measurement was taken or received.
@param ignoreThisReading Set the "ignore" flag for this reading. Data is stored but applications (e.g. navigation) may use this flag to ignore some sensor readings based on robot or user configuration.
@param extraInt extra device-specific data. @see getExtraInt()
*/
AREXPORT void newData(int range, ArPose robotPose, ArPose encoderPose,
ArTransform trans, unsigned int counter,
ArTime timeTaken, bool ignoreThisReading = false,
int extraInt = 0);
/**
@copydoc newData(int, ArPose, ArPose, ArTransform, unsigned int, ArTime, bool, int)
*/
AREXPORT void newData(int sx, int sy, ArPose robotPose,
ArPose encoderPose,
ArTransform trans,
unsigned int counter,
ArTime timeTaken,
bool ignoreThisReading = false,
int extraInt = 0);
/// Resets the sensors idea of its physical location on the robot
AREXPORT void resetSensorPosition(double xPos, double yPos, double thPos,
bool forceComputation = false);
/// Sets that we should ignore this reading
AREXPORT void setIgnoreThisReading(bool ignoreThisReading)
{ myIgnoreThisReading = ignoreThisReading; }
/// Sets the extra int
AREXPORT void setExtraInt(int extraInt)
{ myExtraInt = extraInt; }
/// Applies a transform to the reading position, and where it was taken
/// @internal
AREXPORT void applyTransform(ArTransform trans);
/// Applies a transform to the encoder pose taken
/// @internal
AREXPORT void applyEncoderTransform(ArTransform trans);
/// Whether a transform to this reading's position was applied (An adjustment
/// transform due to robot position and motion, etc. is normally initiated
/// automatically by the range device class which is providing this sensor
/// reading.)
AREXPORT bool getAdjusted(void) { return myAdjusted; }
/// Applies a transform to the reading position, and where it was taken
/// @internal
AREXPORT void setAdjusted(bool adjusted) { myAdjusted = adjusted; }
protected:
unsigned int myCounterTaken;
ArPose myReading;
ArPose myLocalReading;
ArPose myReadingTaken;
ArPose myEncoderPoseTaken;
ArPose mySensorPos;
double mySensorCos, mySensorSin;
double myDistToCenter;
double myAngleToCenter;
int myRange;
ArTime myTimeTaken;
bool myIgnoreThisReading;
int myExtraInt;
bool myAdjusted;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Sensors/RangeSensor.h | /**
* @file RangeSensor.h
* @Author <NAME>
* @date January, 2021
* @brief RangeSensor Declaration
*
*
* This file includes the RangeSensor class declaration and whole it's necessary functions
*/
#ifndef RANGE_SENSOR_H
#define RANGE_SENSOR_H
#include "../API/PioneerRobotAPI.h"
class RangeSensor
{
public:
RangeSensor(PioneerRobotAPI*robot, float range[],int n) {
robotAPI = robot;
ranges = new float[n];
ranges = range;
}
virtual float getRange(int)=0;
virtual float getMax(int&)=0;
virtual float getMin(int&)=0;
virtual void updateSensor(float[])=0;
virtual float operator[](int)=0;
virtual float getAngle(int)=0;
virtual float getClosestRange(float, float, float&)=0;
private:
float *ranges;
PioneerRobotAPI* robotAPI;
};
#endif //!RANGE_SENSOR_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArFunctor.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARFUNCTOR_H
#define ARFUNCTOR_H
#include "ariaTypedefs.h"
#include "ariaOSDef.h"
#include <stdarg.h>
#include <stdio.h>
/// An object which allows storing a generalized reference to a method with an object instance to call later (used for callback functions)
/**
Functors are meant to encapsulate the idea of a pointer to a function
which is a member of a class. To use a pointer to a member function,
you must have a C style function pointer, 'void(Class::*)()', and a
pointer to an instance of the class in which the function is a member
of. This is because all non-static member functions must have a 'this'
pointer. If they dont and if the member function uses any member data
or even other member functions it will not work right and most likely
crash. This is because the 'this' pointer is not the correct value
and is most likely a random uninitialized value. The virtue of static
member functions is that they do not require a 'this' pointer to be run.
But the compiler will never let you access any member data or functions
from within a static member function.
Because of the design of C++ never allowed for encapsulating these two
pointers together into one language supported construct, this has to be
done by hand. For conviences sake, there are functors (ArGlobalFunctor,
ArGlobalRetFunctor) which take a pure C style function pointer
(a non-member function). This is in case you want to use a functor that
refers to a global C style function.
Aria makes use of functors by using them as callback functions. Since
Aria is programmed using the object oriented programming paradigm, all
the callback functions need to be tied to an object and a particular
instance. Thus the need for functors. Most of the use of callbacks simply
take an ArFunctor, which is the base class for all the functors. This
class only has the ability to invoke a functor. All the derivitave
functors have the ability to invoke the correct function on the correct
object.
Because functions have different signatures because they take different
types of parameters and have different number of parameters, templates
were used to create the functors. These are the base classes for the
functors. These classes encapsulate everything except for the class
type that the member function is a member of. This allows someone to
accept a functor of type ArFunctor1<int> which has one parameter of type
'int'. But they never have to know that the function is a member function
of class 'SomeUnknownType'. These classes are:
ArFunctor, ArFunctor1, ArFunctor2, ArFunctor3
ArRetFunctor, ArRetFunctor1, ArRetFunctor2, ArRetFunctor3
These 8 functors are the only thing a piece of code that wants a functor
will ever need. But these classes are abstract classes and can not be
instantiated. On the other side, the piece of code that wants to be
called back will need the functor classes that know about the class type.
These functors are:
ArFunctorC, ArFunctor1C, ArFunctor2C, ArFunctor3C
ArRetFunctorC, ArRetFunctor1C, ArRetFunctor2C, ArRetFunctor3C
These functors are meant to be instantiated and passed of to a piece of
code that wants to use them. That piece of code should only know the
functor as one of the functor classes without the 'C' in it.
Note that you can create these FunctorC instances with default
arguments that are then used when the invoke is called without those
arguments... These are quite useful since if you have a class that
expects an ArFunctor you can make an ArFunctor1C with default
arguments and pass it as an ArFunctor... and it will get called with
that default argument, this is useful for having multiple functors
use the same function with different arguments and results (just
takes one functor each).
Functors now have a getName() method, this is useful as an aid to debugging,
allowing you to display the name of some functor being used.
@javanote You can subclass ArFunctor and override invoke().
@see @ref functorExample.cpp
@ingroup ImportantClasses
**/
class ArFunctor
{
public:
/// Destructor
virtual ~ArFunctor() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Gets the name of the functor
virtual const char *getName(void) { return myName.c_str(); }
/// Sets the name of the functor
virtual void setName(const char *name) { myName = name; }
#ifndef SWIG
/// Sets the name of the functor with formatting
/** @swigomit use setName() */
virtual void setNameVar(const char *name, ...)
{
char arg[2048];
va_list ptr;
va_start(ptr, name);
vsnprintf(arg, sizeof(arg), name, ptr);
arg[sizeof(arg) - 1] = '\0';
va_end(ptr);
return setName(arg);
}
#endif
protected:
std::string myName;
};
/// Base class for functors with 1 parameter
/**
This is the base class for functors with 1 parameter. Code that has a
reference to a functor that takes 1 parameter should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
*/
template<class P1>
class ArFunctor1 : public ArFunctor
{
public:
/// Destructor
virtual ~ArFunctor1() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) = 0;
};
/// Base class for functors with 2 parameters
/**
This is the base class for functors with 2 parameters. Code that has a
reference to a functor that takes 2 parameters should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2>
class ArFunctor2 : public ArFunctor1<P1>
{
public:
/// Destructor
virtual ~ArFunctor2() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) = 0;
};
/// Base class for functors with 3 parameters
/**
This is the base class for functors with 3 parameters. Code that has a
reference to a functor that takes 3 parameters should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3>
class ArFunctor3 : public ArFunctor2<P1, P2>
{
public:
/// Destructor
virtual ~ArFunctor3() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) = 0;
};
/// Base class for functors with 4 parameters
/**
This is the base class for functors with 4 parameters. Code that has a
reference to a functor that takes 4 parameters should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3, class P4>
class ArFunctor4 : public ArFunctor3<P1, P2, P3>
{
public:
/// Destructor
virtual ~ArFunctor4() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) = 0;
};
/// Base class for functors with 4 parameters
/**
This is the base class for functors with 4 parameters. Code that has a
reference to a functor that takes 4 parameters should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3, class P4, class P5>
class ArFunctor5 : public ArFunctor4<P1, P2, P3, P4>
{
public:
/// Destructor
virtual ~ArFunctor5() {}
/// Invokes the functor
virtual void invoke(void) = 0;
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) = 0;
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) = 0;
};
/// Base class for functors with a return value
/**
This is the base class for functors with a return value. Code that has a
reference to a functor that returns a value should use this class
name. This allows the code to know how to invoke the functor without
knowing which class the member function is in.
For an overall description of functors, see ArFunctor.
@javanote To create the equivalent of ArRetFunctor<bool>, you can
subclass <code>ArRetFunctor_Bool</code> and override <code>invoke(bool)</code>
*/
template<class Ret>
class ArRetFunctor : public ArFunctor
{
public:
/// Destructor
virtual ~ArRetFunctor() {}
/// Invokes the functor
virtual void invoke(void) {invokeR();}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
};
/// Base class for functors with a return value with 1 parameter
/**
This is the base class for functors with a return value and take 1
parameter. Code that has a reference to a functor that returns a value
and takes 1 parameter should use this class name. This allows the code
to know how to invoke the functor without knowing which class the member
function is in.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1>
class ArRetFunctor1 : public ArRetFunctor<Ret>
{
public:
/// Destructor
virtual ~ArRetFunctor1() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) = 0;
};
/// Base class for functors with a return value with 2 parameters
/**
This is the base class for functors with a return value and take 2
parameters. Code that has a reference to a functor that returns a value
and takes 2 parameters should use this class name. This allows the code
to know how to invoke the functor without knowing which class the member
function is in.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2>
class ArRetFunctor2 : public ArRetFunctor1<Ret, P1>
{
public:
/// Destructor
virtual ~ArRetFunctor2() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) = 0;
};
/// Base class for functors with a return value with 3 parameters
/**
This is the base class for functors with a return value and take 3
parameters. Code that has a reference to a functor that returns a value
and takes 3 parameters should use this class name. This allows the code
to know how to invoke the functor without knowing which class the member
function is in.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3>
class ArRetFunctor3 : public ArRetFunctor2<Ret, P1, P2>
{
public:
/// Destructor
virtual ~ArRetFunctor3() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) = 0;
};
/// Base class for functors with a return value with 4 parameters
/**
This is the base class for functors with a return value and take 4
parameters. Code that has a reference to a functor that returns a value
and takes 4 parameters should use this class name. This allows the code
to know how to invoke the functor without knowing which class the member
function is in.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3, class P4>
class ArRetFunctor4 : public ArRetFunctor3<Ret, P1, P2, P3>
{
public:
/// Destructor
virtual ~ArRetFunctor4() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4) = 0;
};
/// Base class for functors with a return value with 5 parameters
/**
This is the base class for functors with a return value and take 5
parameters. Code that has a reference to a functor that returns a value
and takes 5 parameters should use this class name. This allows the code
to know how to invoke the functor without knowing which class the member
function is in.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3, class P4, class P5>
class ArRetFunctor5 : public ArRetFunctor4<Ret, P1, P2, P3, P4>
{
public:
/// Destructor
virtual ~ArRetFunctor5() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4) = 0;
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) = 0;
};
//////
//////
//////
//////
//////
//////
////// ArFunctors for global functions. C style function pointers.
//////
//////
//////
//////
//////
//////
#ifndef SWIG
/// Functor for a global function with no parameters
/**
This is a class for global functions. This ties a C style function
pointer into the functor class hierarchy as a convience. Code that
has a reference to this class and treat it as an ArFunctor can use
it like any other functor.
For an overall description of functors, see ArFunctor.
@swigomit
*/
class ArGlobalFunctor : public ArFunctor
{
public:
/// Constructor
ArGlobalFunctor() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor(void (*func)(void)) : myFunc(func) {}
/// Destructor
virtual ~ArGlobalFunctor() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)();}
protected:
void (*myFunc)(void);
};
/// Functor for a global function with 1 parameter
/**
This is a class for global functions which take 1 parameter. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class P1>
class ArGlobalFunctor1 : public ArFunctor1<P1>
{
public:
/// Constructor
ArGlobalFunctor1() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor1(void (*func)(P1)) :
myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalFunctor1(void (*func)(P1), P1 p1) :
myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArGlobalFunctor1() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)(myP1);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(*myFunc)(p1);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
void (*myFunc)(P1);
P1 myP1;
};
/// Functor for a global function with 2 parameters
/**
This is a class for global functions which take 2 parameters. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2>
class ArGlobalFunctor2 : public ArFunctor2<P1, P2>
{
public:
/// Constructor
ArGlobalFunctor2() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor2(void (*func)(P1, P2)) :
myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalFunctor2(void (*func)(P1, P2), P1 p1) :
myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalFunctor2(void (*func)(P1, P2), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArGlobalFunctor2() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)(myP1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(*myFunc)(p1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(*myFunc)(p1, p2);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
void (*myFunc)(P1, P2);
P1 myP1;
P2 myP2;
};
/// Functor for a global function with 3 parameters
/**
This is a class for global functions which take 3 parameters. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3>
class ArGlobalFunctor3 : public ArFunctor3<P1, P2, P3>
{
public:
/// Constructor
ArGlobalFunctor3() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor3(void (*func)(P1, P2, P3)) :
myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalFunctor3(void (*func)(P1, P2, P3), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalFunctor3(void (*func)(P1, P2, P3), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalFunctor3(void (*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArGlobalFunctor3() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(*myFunc)(p1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(*myFunc)(p1, p2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(*myFunc)(p1, p2, p3);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
void (*myFunc)(P1, P2, P3);
P1 myP1;
P2 myP2;
P3 myP3;
};
/// Functor for a global function with 4 parameters
/**
This is a class for global functions which take 4 parameters. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3, class P4>
class ArGlobalFunctor4 : public ArFunctor4<P1, P2, P3, P4>
{
public:
/// Constructor
ArGlobalFunctor4() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor4(void (*func)(P1, P2, P3, P4)) :
myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalFunctor4(void (*func)(P1, P2, P3, P4), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalFunctor4(void (*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalFunctor4(void (*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArGlobalFunctor4(void (*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArGlobalFunctor4() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(*myFunc)(p1, p2, p3, p4);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
void (*myFunc)(P1, P2, P3, P4);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a global function with 5 parameters
/**
This is a class for global functions which take 5 parameters. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class P1, class P2, class P3, class P4, class P5>
class ArGlobalFunctor5 : public ArFunctor5<P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArGlobalFunctor5() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5)) :
myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArGlobalFunctor5(void (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArGlobalFunctor5() {}
/// Invokes the functor
virtual void invoke(void) {(*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {(*myFunc)(p1, p2, p3, p4, p5);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
void (*myFunc)(P1, P2, P3, P4, P5);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P5 myP5;
};
#endif // Omitting ArGlobalFunctor from Swig
//////
//////
//////
//////
//////
//////
////// ArFunctors for global functions, C style function pointers with return
////// return values.
//////
//////
//////
//////
//////
//////
#ifndef SWIG
/// Functor for a global function with return value
/**
This is a class for global functions which return a value. This ties
a C style function pointer into the functor class hierarchy as a
convience. Code that has a reference to this class and treat it as
an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret>
class ArGlobalRetFunctor : public ArRetFunctor<Ret>
{
public:
/// Constructor
ArGlobalRetFunctor() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor(Ret (*func)(void)) : myFunc(func) {}
/// Destructor
virtual ~ArGlobalRetFunctor() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)();}
protected:
Ret (*myFunc)(void);
};
/// Functor for a global function with 1 parameter and return value
/**
This is a class for global functions which take 1 parameter and return
a value. This ties a C style function pointer into the functor class
hierarchy as a convience. Code that has a reference to this class
and treat it as an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1>
class ArGlobalRetFunctor1 : public ArRetFunctor1<Ret, P1>
{
public:
/// Constructor
ArGlobalRetFunctor1() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor1(Ret (*func)(P1)) :
myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalRetFunctor1(Ret (*func)(P1), P1 p1) :
myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArGlobalRetFunctor1() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)(myP1);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (*myFunc)(p1);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
Ret (*myFunc)(P1);
P1 myP1;
};
/// Functor for a global function with 2 parameters and return value
/**
This is a class for global functions which take 2 parameters and return
a value. This ties a C style function pointer into the functor class
hierarchy as a convience. Code that has a reference to this class
and treat it as an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2>
class ArGlobalRetFunctor2 : public ArRetFunctor2<Ret, P1, P2>
{
public:
/// Constructor
ArGlobalRetFunctor2() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor2(Ret (*func)(P1, P2)) :
myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalRetFunctor2(Ret (*func)(P1, P2), P1 p1) :
myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalRetFunctor2(Ret (*func)(P1, P2), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArGlobalRetFunctor2() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)(myP1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (*myFunc)(p1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (*myFunc)(p1, p2);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
Ret (*myFunc)(P1, P2);
P1 myP1;
P2 myP2;
};
/// Functor for a global function with 2 parameters and return value
/**
This is a class for global functions which take 2 parameters and return
a value. This ties a C style function pointer into the functor class
hierarchy as a convience. Code that has a reference to this class
and treat it as an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3>
class ArGlobalRetFunctor3 : public ArRetFunctor3<Ret, P1, P2, P3>
{
public:
/// Constructor
ArGlobalRetFunctor3() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor3(Ret (*func)(P1, P2, P3)) :
myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalRetFunctor3(Ret (*func)(P1, P2, P3), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalRetFunctor3(Ret (*func)(P1, P2, P3), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalRetFunctor3(Ret (*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArGlobalRetFunctor3() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (*myFunc)(p1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (*myFunc)(p1, p2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) {return (*myFunc)(p1, p2, p3);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
Ret (*myFunc)(P1, P2, P3);
P1 myP1;
P2 myP2;
P3 myP3;
};
/// Functor for a global function with 4 parameters and return value
/**
This is a class for global functions which take 4 parameters and return
a value. This ties a C style function pointer into the functor class
hierarchy as a convience. Code that has a reference to this class
and treat it as an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3, class P4>
class ArGlobalRetFunctor4 : public ArRetFunctor4<Ret, P1, P2, P3, P4>
{
public:
/// Constructor
ArGlobalRetFunctor4() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor4(Ret (*func)(P1, P2, P3, P4)) :
myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalRetFunctor4(Ret (*func)(P1, P2, P3, P4), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalRetFunctor4(Ret (*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalRetFunctor4(Ret (*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArGlobalRetFunctor4(Ret (*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArGlobalRetFunctor4() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) {return (*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4) {return (*myFunc)(p1, p2, p3, p4);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
Ret (*myFunc)(P1, P2, P3, P4);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a global function with 4 parameters and return value
/**
This is a class for global functions which take 4 parameters and return
a value. This ties a C style function pointer into the functor class
hierarchy as a convience. Code that has a reference to this class
and treat it as an ArFunctor can use it like any other functor.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class P1, class P2, class P3, class P4, class P5>
class ArGlobalRetFunctor5 : public ArRetFunctor5<Ret, P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArGlobalRetFunctor5() {}
/// Constructor - supply function pointer
/**
@param func global function pointer
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5)) :
myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5), P1 p1) :
myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/**
@param func global function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArGlobalRetFunctor5(Ret (*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArGlobalRetFunctor5() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3) {return (*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4) {return (*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {return (*myFunc)(p1, p2, p3, p4, p5);}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
Ret (*myFunc)(P1, P2, P3, P4, P5);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P5 myP5;
};
#endif // omitting ArGlobalRetFunctor from SWIG
//////
//////
//////
//////
//////
//////
////// ArFunctors for member functions
//////
//////
//////
//////
//////
//////
/// Functor for a member function
/**
This is a class for member functions. This class contains the knowledge
on how to call a member function on a particular instance of a class.
This class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T>
class ArFunctorC : public ArFunctor
{
public:
/// Constructor
ArFunctorC() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctorC(T &obj, void (T::*func)(void)) : myObj(&obj), myFunc(func) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctorC(T *obj, void (T::*func)(void)) : myObj(obj), myFunc(func) {}
/// Destructor
virtual ~ArFunctorC() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)();}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
protected:
T *myObj;
void (T::*myFunc)(void);
};
/// Functor for a member function with 1 parameter
/**
This is a class for member functions which take 1 parameter. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T, class P1>
class ArFunctor1C : public ArFunctor1<P1>
{
public:
/// Constructor
ArFunctor1C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor1C(T &obj, void (T::*func)(P1)) :
myObj(&obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor1C(T &obj, void (T::*func)(P1), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor1C(T *obj, void (T::*func)(P1)) :
myObj(obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor1C(T *obj, void (T::*func)(P1), P1 p1) :
myObj(obj), myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArFunctor1C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
T *myObj;
void (T::*myFunc)(P1);
P1 myP1;
};
/// Functor for a member function with 2 parameters
/**
This is a class for member functions which take 2 parameters. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T, class P1, class P2>
class ArFunctor2C : public ArFunctor2<P1, P2>
{
public:
/// Constructor
ArFunctor2C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor2C(T &obj, void (T::*func)(P1, P2)) :
myObj(&obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor2C(T &obj, void (T::*func)(P1, P2), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor2C(T &obj, void (T::*func)(P1, P2), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor2C(T *obj, void (T::*func)(P1, P2)) :
myObj(obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor2C(T *obj, void (T::*func)(P1, P2), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor2C(T *obj, void (T::*func)(P1, P2), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArFunctor2C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2);
P1 myP1;
P2 myP2;
};
/// Functor for a member function with 3 parameters
/**
This is a class for member functions which take 3 parameters. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T, class P1, class P2, class P3>
class ArFunctor3C : public ArFunctor3<P1, P2, P3>
{
public:
/// Constructor
ArFunctor3C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor3C(T &obj, void (T::*func)(P1, P2, P3)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor3C(T &obj, void (T::*func)(P1, P2, P3), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor3C(T &obj, void (T::*func)(P1, P2, P3), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor3C(T &obj, void (T::*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor3C(T *obj, void (T::*func)(P1, P2, P3)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor3C(T *obj, void (T::*func)(P1, P2, P3), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor3C(T *obj, void (T::*func)(P1, P2, P3), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor3C(T *obj, void (T::*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArFunctor3C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3);
P1 myP1;
P2 myP2;
P3 myP3;
};
/// Functor for a member function with 4 parameters
/**
This is a class for member functions which take 4 parameters. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T, class P1, class P2, class P3, class P4>
class ArFunctor4C : public ArFunctor4<P1, P2, P3, P4>
{
public:
/// Constructor
ArFunctor4C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArFunctor4C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(myObj->*myFunc)(p1, p2, p3, p4);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3, P4);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a member function with 5 parameters
/**
This is a class for member functions which take 5 parameters. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class T, class P1, class P2, class P3, class P4, class P5>
class ArFunctor5C : public ArFunctor5<P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArFunctor5C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArFunctor5C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(myObj->*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {(myObj->*myFunc)(p1, p2, p3, p4, p5);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3, P4, P5);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P5 myP5;
};
//////
//////
//////
//////
//////
//////
////// ArFunctors for member functions with return values
//////
//////
//////
//////
//////
//////
/// Functor for a member function with return value
/**
This is a class for member functions which return a value. This class
contains the knowledge on how to call a member function on a particular
instance of a class. This class should be instantiated by code that
wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T>
class ArRetFunctorC : public ArRetFunctor<Ret>
{
public:
/// Constructor
ArRetFunctorC() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctorC(T &obj, Ret (T::*func)(void)) : myObj(&obj), myFunc(func) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctorC(T *obj, Ret (T::*func)(void)) : myObj(obj), myFunc(func) {}
/// Destructor - supply function pointer
virtual ~ArRetFunctorC() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)();}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
protected:
T *myObj;
Ret (T::*myFunc)(void);
};
/// Functor for a member function with return value and 1 parameter
/**
This is a class for member functions which take 1 parameter and return
a value. This class contains the knowledge on how to call a member
function on a particular instance of a class. This class should be
instantiated by code that wishes to pass off a functor to another
piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T, class P1>
class ArRetFunctor1C : public ArRetFunctor1<Ret, P1>
{
public:
/// Constructor
ArRetFunctor1C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor1C(T &obj, Ret (T::*func)(P1)) :
myObj(&obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor1C(T &obj, Ret (T::*func)(P1), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor1C(T *obj, Ret (T::*func)(P1)) :
myObj(obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor1C(T *obj, Ret (T::*func)(P1), P1 p1) :
myObj(obj), myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArRetFunctor1C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
T *myObj;
Ret (T::*myFunc)(P1);
P1 myP1;
};
/// Functor for a member function with return value and 2 parameters
/**
This is a class for member functions which take 2 parameters and return
a value. This class contains the knowledge on how to call a member
function on a particular instance of a class. This class should be
instantiated by code that wishes to pass off a functor to another
piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T, class P1, class P2>
class ArRetFunctor2C : public ArRetFunctor2<Ret, P1, P2>
{
public:
/// Constructor
ArRetFunctor2C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor2C(T &obj, Ret (T::*func)(P1, P2)) :
myObj(&obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor2C(T &obj, Ret (T::*func)(P1, P2), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor2C(T &obj, Ret (T::*func)(P1, P2), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor2C(T *obj, Ret (T::*func)(P1, P2)) :
myObj(obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor2C(T *obj, Ret (T::*func)(P1, P2), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor2C(T *obj, Ret (T::*func)(P1, P2), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArRetFunctor2C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2);
P1 myP1;
P2 myP2;
};
/// Functor for a member function with return value and 3 parameters
/**
This is a class for member functions which take 3 parameters and return
a value. This class contains the knowledge on how to call a member
function on a particular instance of a class. This class should be
instantiated by code that wishes to pass off a functor to another
piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T, class P1, class P2, class P3>
class ArRetFunctor3C : public ArRetFunctor3<Ret, P1, P2, P3>
{
public:
/// Constructor
ArRetFunctor3C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArRetFunctor3C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3);}
/// Set the 'this' pointer
/**
@param obj object to call function on
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj object to call function on
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3);
P1 myP1;
P2 myP2;
P3 myP3;
};
// Start 4
/// Functor for a member function with return value and 4 parameters
/**
This is a class for member functions which take 4 parameters and return
a value. This class contains the knowledge on how to call a member
function on a particular instance of a class. This class should be
instantiated by code that wishes to pass off a functor to another
piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T, class P1, class P2, class P3, class P4>
class ArRetFunctor4C : public ArRetFunctor4<Ret, P1, P2, P3, P4>
{
public:
/// Constructor
ArRetFunctor4C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArRetFunctor4C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4)
{return (myObj->*myFunc)(p1, p2, p3, p4);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3, P4);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a member function with return value and 4 parameters
/**
This is a class for member functions which take 4 parameters and return
a value. This class contains the knowledge on how to call a member
function on a particular instance of a class. This class should be
instantiated by code that wishes to pass off a functor to another
piece of code.
For an overall description of functors, see ArFunctor.
*/
template<class Ret, class T, class P1, class P2, class P3, class P4, class P5>
class ArRetFunctor5C : public ArRetFunctor5<Ret, P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArRetFunctor5C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5)) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func member function pointer
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5)) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArRetFunctor5C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4)
{return (myObj->*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
{return (myObj->*myFunc)(p1, p2, p3, p4, p5);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3, P4, P5);
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P4 myP5;
};
/// Swig doesn't like the const functors
#ifndef SWIG
//////
//////
//////
//////
//////
//////
////// ArFunctors for const member functions
//////
//////
//////
//////
//////
//////
/// Functor for a const member function
/**
This is a class for const member functions. This class contains the
knowledge on how to call a const member function on a particular
instance of a class. This class should be instantiated by code
that wishes to pass off a functor to another piece of code.
For an overall description of functors, see ArFunctor.
@swigomit
*/
template<class T>
class ArConstFunctorC : public ArFunctor
{
public:
/// Constructor
ArConstFunctorC() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctorC(T &obj, void (T::*func)(void) const) : myObj(&obj), myFunc(func) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctorC(T *obj, void (T::*func)(void) const) : myObj(obj), myFunc(func) {}
/// Destructor
virtual ~ArConstFunctorC() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)();}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
protected:
T *myObj;
void (T::*myFunc)(void) const;
};
/// Functor for a const member function with 1 parameter
/**
This is a class for const member functions which take 1
parameter. This class contains the knowledge on how to call a const
member function on a particular instance of a class. This class
should be instantiated by code that wishes to pass off a functor to
another piece of code.
For an overall description of functors, see ArFunctor. */
template<class T, class P1>
class ArConstFunctor1C : public ArFunctor1<P1>
{
public:
/// Constructor
ArConstFunctor1C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor1C(T &obj, void (T::*func)(P1) const) :
myObj(&obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor1C(T &obj, void (T::*func)(P1) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor1C(T *obj, void (T::*func)(P1) const) :
myObj(obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor1C(T *obj, void (T::*func)(P1) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArConstFunctor1C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
T *myObj;
void (T::*myFunc)(P1) const;
P1 myP1;
};
/// Functor for a const member function with 2 parameters
/**
This is a class for const member functions which take 2
parameters. This class contains the knowledge on how to call a
const member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class T, class P1, class P2>
class ArConstFunctor2C : public ArFunctor2<P1, P2>
{
public:
/// Constructor
ArConstFunctor2C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor2C(T &obj, void (T::*func)(P1, P2) const) :
myObj(&obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor2C(T &obj, void (T::*func)(P1, P2) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor2C(T &obj, void (T::*func)(P1, P2) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor2C(T *obj, void (T::*func)(P1, P2) const) :
myObj(obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor2C(T *obj, void (T::*func)(P1, P2) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor2C(T *obj, void (T::*func)(P1, P2) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArConstFunctor2C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2) const;
P1 myP1;
P2 myP2;
};
/// Functor for a const member function with 3 parameters
/**
This is a class for const member functions which take 3
parameters. This class contains the knowledge on how to call a
const member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class T, class P1, class P2, class P3>
class ArConstFunctor3C : public ArFunctor3<P1, P2, P3>
{
public:
/// Constructor
ArConstFunctor3C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor3C(T &obj, void (T::*func)(P1, P2, P3) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor3C(T &obj, void (T::*func)(P1, P2, P3) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor3C(T &obj, void (T::*func)(P1, P2, P3) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor3C(T &obj, void (T::*func)(P1, P2, P3) const, P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor3C(T *obj, void (T::*func)(P1, P2, P3) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor3C(T *obj, void (T::*func)(P1, P2, P3) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor3C(T *obj, void (T::*func)(P1, P2, P3) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor3C(T *obj, void (T::*func)(P1, P2, P3) const, P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArConstFunctor3C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3) const;
P1 myP1;
P2 myP2;
P3 myP3;
};
/// Functor for a const member function with 4 parameters
/**
This is a class for const member functions which take 4
parameters. This class contains the knowledge on how to call a
const member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class T, class P1, class P2, class P3, class P4>
class ArConstFunctor4C : public ArFunctor4<P1, P2, P3, P4>
{
public:
/// Constructor
ArConstFunctor4C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstFunctor4C(T &obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstFunctor4C(T *obj, void (T::*func)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArConstFunctor4C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(myObj->*myFunc)(p1, p2, p3, p4);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3, P4) const;
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a const member function with 4 parameters
/**
This is a class for const member functions which take 4
parameters. This class contains the knowledge on how to call a
const member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class T, class P1, class P2, class P3, class P4, class P5>
class ArConstFunctor5C : public ArFunctor5<P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArConstFunctor5C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArConstFunctor5C(T &obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArConstFunctor5C(T *obj, void (T::*func)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArConstFunctor5C() {}
/// Invokes the functor
virtual void invoke(void) {(myObj->*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
*/
virtual void invoke(P1 p1) {(myObj->*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual void invoke(P1 p1, P2 p2) {(myObj->*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3) {(myObj->*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4) {(myObj->*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual void invoke(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {(myObj->*myFunc)(p1, p2, p3, p4, p5);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
T *myObj;
void (T::*myFunc)(P1, P2, P3, P4, P5) const;
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P4 myP5;
};
//////
//////
//////
//////
//////
//////
////// ArFunctors for const member functions with return values
//////
//////
//////
//////
//////
//////
/// Functor for a const member function with return value
/**
This is a class for const member functions which return a
value. This class contains the knowledge on how to call a const
member function on a particular instance of a class. This class
should be instantiated by code that wishes to pass off a functor to
another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T>
class ArConstRetFunctorC : public ArRetFunctor<Ret>
{
public:
/// Constructor
ArConstRetFunctorC() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctorC(T &obj, Ret (T::*func)(void) const) : myObj(&obj), myFunc(func) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctorC(T *obj, Ret (T::*func)(void) const) : myObj(obj), myFunc(func) {}
/// Destructor - supply function pointer
virtual ~ArConstRetFunctorC() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)();}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
protected:
T *myObj;
Ret (T::*myFunc)(void) const;
};
/// Functor for a const member function with return value and 1 parameter
/**
This is a class for const member functions which take 1 parameter
and return a value. This class contains the knowledge on how to
call a member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T, class P1>
class ArConstRetFunctor1C : public ArRetFunctor1<Ret, P1>
{
public:
/// Constructor
ArConstRetFunctor1C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor1C(T &obj, Ret (T::*func)(P1) const) :
myObj(&obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor1C(T &obj, Ret (T::*func)(P1) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor1C(T *obj, Ret (T::*func)(P1) const) :
myObj(obj), myFunc(func), myP1() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor1C(T *obj, Ret (T::*func)(P1) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1) {}
/// Destructor
virtual ~ArConstRetFunctor1C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
protected:
T *myObj;
Ret (T::*myFunc)(P1) const;
P1 myP1;
};
/// Functor for a const member function with return value and 2 parameters
/**
This is a class for const member functions which take 2 parameters
and return a value. This class contains the knowledge on how to
call a member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T, class P1, class P2>
class ArConstRetFunctor2C : public ArRetFunctor2<Ret, P1, P2>
{
public:
/// Constructor
ArConstRetFunctor2C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor2C(T &obj, Ret (T::*func)(P1, P2) const) :
myObj(&obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor2C(T &obj, Ret (T::*func)(P1, P2) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor2C(T &obj, Ret (T::*func)(P1, P2) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor2C(T *obj, Ret (T::*func)(P1, P2) const) :
myObj(obj), myFunc(func), myP1(), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor2C(T *obj, Ret (T::*func)(P1, P2) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor2C(T *obj, Ret (T::*func)(P1, P2) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2) {}
/// Destructor
virtual ~ArConstRetFunctor2C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2) const;
P1 myP1;
P2 myP2;
};
/// Functor for a const member function with return value and 3 parameters
/**
This is a class for const member functions which take 3 parameters
and return a value. This class contains the knowledge on how to
call a member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T, class P1, class P2, class P3>
class ArConstRetFunctor3C : public ArRetFunctor3<Ret, P1, P2, P3>
{
public:
/// Constructor
ArConstRetFunctor3C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor3C(T &obj, Ret (T::*func)(P1, P2, P3) const, P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor3C(T *obj, Ret (T::*func)(P1, P2, P3) const, P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3) {}
/// Destructor
virtual ~ArConstRetFunctor3C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3) const;
P1 myP1;
P2 myP2;
P3 myP3;
};
// Start 4
/// Functor for a const member function with return value and 4 parameters
/**
This is a class for const member functions which take 4 parameters
and return a value. This class contains the knowledge on how to
call a member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T, class P1, class P2, class P3, class P4>
class ArConstRetFunctor4C : public ArRetFunctor4<Ret, P1, P2, P3, P4>
{
public:
/// Constructor
ArConstRetFunctor4C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstRetFunctor4C(T &obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstRetFunctor4C(T *obj, Ret (T::*func)(P1, P2, P3, P4) const, P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4) {}
/// Destructor
virtual ~ArConstRetFunctor4C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3, myP4);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4)
{return (myObj->*myFunc)(p1, p2, p3, p4);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3, P4) const;
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
};
/// Functor for a const member function with return value and 5 parameters
/**
This is a class for const member functions which take 5 parameters
and return a value. This class contains the knowledge on how to
call a member function on a particular instance of a class. This
class should be instantiated by code that wishes to pass off a
functor to another piece of code.
For an overall description of functors, see ArFunctor. */
template<class Ret, class T, class P1, class P2, class P3, class P4, class P5>
class ArConstRetFunctor5C : public ArRetFunctor5<Ret, P1, P2, P3, P4, P5>
{
public:
/// Constructor
ArConstRetFunctor5C() {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const) :
myObj(&obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1) :
myObj(&obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArConstRetFunctor5C(T &obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(&obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Constructor - supply function pointer
/**
@param obj object to call function on
@param func const member function pointer
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const) :
myObj(obj), myFunc(func), myP1(), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1) :
myObj(obj), myFunc(func), myP1(p1), myP2(), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3, P4 p4) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5() {}
/// Constructor - supply function pointer, default parameters
/**
@param obj object to call function on
@param func const member function pointer
@param p1 default first parameter
@param p2 default second parameter
@param p3 default third parameter
@param p4 default fourth parameter
@param p5 default fifth parameter
*/
ArConstRetFunctor5C(T *obj, Ret (T::*func)(P1, P2, P3, P4, P5) const, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) :
myObj(obj), myFunc(func), myP1(p1), myP2(p2), myP3(p3), myP4(p4), myP5(p5) {}
/// Destructor
virtual ~ArConstRetFunctor5C() {}
/// Invokes the functor with return value
virtual Ret invokeR(void) {return (myObj->*myFunc)(myP1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
*/
virtual Ret invokeR(P1 p1) {return (myObj->*myFunc)(p1, myP2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2) {return (myObj->*myFunc)(p1, p2, myP3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 second parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3)
{return (myObj->*myFunc)(p1, p2, p3, myP4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4)
{return (myObj->*myFunc)(p1, p2, p3, p4, myP5);}
/// Invokes the functor with return value
/**
@param p1 first parameter
@param p2 second parameter
@param p3 third parameter
@param p4 fourth parameter
@param p5 fifth parameter
*/
virtual Ret invokeR(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
{return (myObj->*myFunc)(p1, p2, p3, p4, p5);}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T *obj) {myObj=obj;}
/// Set the 'this' pointer
/**
@param obj the 'this' pointer
*/
virtual void setThis(T &obj) {myObj=&obj;}
/// Set the default parameter
/**
@param p1 default first parameter
*/
virtual void setP1(P1 p1) {myP1=p1;}
/// Set the default 2nd parameter
/**
@param p2 default second parameter
*/
virtual void setP2(P2 p2) {myP2=p2;}
/// Set the default third parameter
/**
@param p3 default third parameter
*/
virtual void setP3(P3 p3) {myP3=p3;}
/// Set the default fourth parameter
/**
@param p4 default fourth parameter
*/
virtual void setP4(P4 p4) {myP4=p4;}
/// Set the default fifth parameter
/**
@param p5 default fifth parameter
*/
virtual void setP5(P5 p5) {myP5=p5;}
protected:
T *myObj;
Ret (T::*myFunc)(P1, P2, P3, P4, P5) const;
P1 myP1;
P2 myP2;
P3 myP3;
P4 myP4;
P5 myP5;
};
#endif // omitting Const functors from SWIG
#endif // ARFUNCTOR_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionIRs.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONIRS_H
#define ARACTIONIRS_H
#include "ariaTypedefs.h"
#include "ArAction.h"
#include "ArRobotParams.h"
#include <vector>
/// Action to back up if short-range IR sensors trigger
/**
* If the robot has front-mounted binary (triggered/not triggered) IR sensors,
* this action will respond to a sensor trigger by backing up and perhaps
* turning, similar to bumpers. This action assumes that if an IR triggers, the
* robot caused it by moving forward into or under an obstacle, and backing up
* is a good reaction.
* @ingroup ActionClasses
*/
class ArActionIRs : public ArAction
{
public:
/// Constructor
AREXPORT ArActionIRs(const char *name = "IRs",
double backOffSpeed = 100, int backOffTime = 5000,
int turnTime = 3000, bool setMaximums = false);
/// Destructor
AREXPORT virtual ~ArActionIRs();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual void setRobot(ArRobot *robot);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
ArActionDesired myDesired;
bool mySetMaximums;
double myBackOffSpeed;
int myBackOffTime;
int myTurnTime;
int myStopTime;
bool myFiring;
double mySpeed;
double myHeading;
ArTime myStartBack;
ArTime stoppedSince;
ArRobotParams myParams;
std::vector<int> cycleCounters;
};
#endif // ARACTIONIRS
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArLMS2xx.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARLMS2XX_H
#define ARLMS2XX_H
#include "ariaTypedefs.h"
#include "ArLMS2xxPacket.h"
#include "ArLMS2xxPacketReceiver.h"
#include "ArRobotPacket.h"
#include "ArLaser.h"
#include "ArFunctor.h"
#include "ArCondition.h"
/// Interface to a SICK LMS-200 laser range device
/**
* This class processes incoming data from a SICK LMS-200
* laser rangefinding device in a background thread, and provides
* it through the standard ArRangeDevice API, to be used via ArRobot
* (see ArRobot::addRangeDevice()), used by an ArAction, or used directly.
*
* An ArSick instance must be connected to the laser through a serial port
* (or simulator): the typical procedure is to allow your ArSimpleConnector
* to configure the laser based on the robot connection type and command
* line parameters; then initiate the ArSick background thread; and finally
* connect ArSick to the laser device.
* For example:
* @code
* ArRobot robot;
* ArSick laser;
* ArSimpleConnector connector(...);
* ...
* Setup the simple connector and connect to the robot --
* see the example programs.
* ...
* connector.setupLaser(&laser);
* laser.runAsync();
* if(!laser.blockingConnect())
* {
* // Error...
* ...
* }
* ...
* @endcode
*
* The most important methods in this class are the constructor, runAsync(),
* blockingConnect(), getSensorPosition(), isConnected(), addConnectCB(),
* asyncConnect(), configure(), in addition to the ArRangeDevice interface.
*
* @note The "extra int" on the raw readings returned by
* ArRangeDevice::getRawReadings() is like other laser
* devices and is the reflectance value, if enabled, ranging between 0 and 255.
*
* ArLMS2xx uses the following buffer parameters by default (see ArRangeDevice
* documentation):
* <dl>
* <dt>MinDistBetweenCurrent <dd>50 mm
* <dt>MaxDistToKeepCumulative <dd>6000 mm
* <dt>MinDistBetweenCumulative <dd>200 mm
* <dt>MaxSecondsToKeepCumulative <dd>30 sec
* <dt>MaxINsertDistCumulative <dd>3000 mm
* </dl>
* The current buffer is replaced for each new set of readings.
*
* @since 2.7.0
**/
class ArLMS2xx : public ArLaser
{
public:
/// Constructor
AREXPORT ArLMS2xx(int laserNumber,
const char *name = "lms2xx",
bool appendLaserNumberToName = true);
/// Destructor
AREXPORT virtual ~ArLMS2xx();
/// Connect to the laser while blocking
AREXPORT virtual bool blockingConnect(void);
/// Connect to the laser asyncronously
AREXPORT bool asyncConnect(void);
/// Disconnect from the laser
AREXPORT virtual bool disconnect(void);
/// Sees if this is connected to the laser
AREXPORT virtual bool isConnected(void)
{ if (myState == STATE_CONNECTED) return true; else return false; }
AREXPORT virtual bool isTryingToConnect(void)
{
if (myState != STATE_CONNECTED && myState != STATE_NONE)
return true;
else if (myStartConnect)
return true;
else
return false;
}
/// Sets the device connection
AREXPORT virtual void setDeviceConnection(ArDeviceConnection *conn);
/** The internal function used by the ArRangeDeviceThreaded
* @internal
*/
AREXPORT virtual void * runThread(void *arg);
AREXPORT virtual void setRobot(ArRobot *robot);
protected:
// The packet handler for when connected to the simulator
AREXPORT bool simPacketHandler(ArRobotPacket * packet);
// The function called if the laser isn't running in its own thread and isn't simulated
AREXPORT void sensorInterpCallback(void);
// An internal function for connecting to the sim
AREXPORT bool internalConnectSim(void);
/// An internal function, single loop event to connect to laser
AREXPORT int internalConnectHandler(void);
// The internal function which processes the sickPackets
AREXPORT void processPacket(ArLMS2xxPacket *packet, ArPose pose,
ArPose encoderPose, unsigned int counter,
bool deinterlace, ArPose deinterlaceDelta);
// The internal function that gets does the work
AREXPORT void runOnce(bool lockRobot);
// Internal function, shouldn't be used, drops the conn because of error
AREXPORT void dropConnection(void);
// Internal function, shouldn't be used, denotes the conn failed
AREXPORT void failedConnect(void);
// Internal function, shouldn't be used, does the after conn stuff
AREXPORT void madeConnection(void);
/// Internal function that gets whether the laser is simulated or not (just for the old ArSick)
AREXPORT bool sickGetIsUsingSim(void);
/// Internal function that sets whether the laser is simulated or not (just for the old ArSick)
AREXPORT void sickSetIsUsingSim(bool usingSim);
/// internal function to runOnRobot so that ArSick can do that while this class won't
AREXPORT bool internalRunOnRobot(void);
/// Finishes getting the unset parameters from the robot then
/// setting some internal variables that need it
bool finishParams(void);
AREXPORT virtual bool laserCheckParams(void);
AREXPORT virtual void laserSetName(const char *name);
enum State {
STATE_NONE, ///< Nothing, haven't tried to connect or anything
STATE_INIT, ///< Initializing the laser
STATE_WAIT_FOR_POWER_ON, ///< Waiting for power on
STATE_CHANGE_BAUD, ///< Change the baud, no confirm here
STATE_CONFIGURE, ///< Send the width and increment to the laser
STATE_WAIT_FOR_CONFIGURE_ACK, ///< Wait for the configuration Ack
STATE_INSTALL_MODE, ///< Switch to install mode
STATE_WAIT_FOR_INSTALL_MODE_ACK, ///< Wait until its switched to install mode
STATE_SET_MODE, ///< Set the mode (mm/cm) and extra field bits
STATE_WAIT_FOR_SET_MODE_ACK, ///< Waiting for set-mode ack
STATE_START_READINGS, ///< Switch to monitoring mode
STATE_WAIT_FOR_START_ACK, ///< Waiting for the switch-mode ack
STATE_CONNECTED ///< We're connected and getting readings
};
/// Internal function for switching states
AREXPORT void switchState(State state);
State myState;
ArTime myStateStart;
ArFunctorC<ArLMS2xx> myRobotConnectCB;
ArRetFunctor1C<bool, ArLMS2xx, ArRobotPacket *> mySimPacketHandler;
ArFunctorC<ArLMS2xx> mySensorInterpCB;
std::list<ArSensorReading *>::iterator myIter;
bool myStartConnect;
bool myRunningOnRobot;
// range buffers to hold current range set and assembling range set
std::list<ArSensorReading *> *myAssembleReadings;
std::list<ArSensorReading *> *myCurrentReadings;
bool myProcessImmediately;
bool myInterpolation;
// list of packets, so we can process them from the sensor callback
std::list<ArLMS2xxPacket *> myPackets;
// these two are just for the sim packets
unsigned int myWhichReading;
unsigned int myTotalNumReadings;
// some variables so we don't have to do a tedios if every time
double myOffsetAmount;
double myIncrementAmount;
// packet stuff
ArLMS2xxPacket myPacket;
bool myUseSim;
int myNumReflectorBits;
bool myInterlaced;
// stuff for the sim packet
ArPose mySimPacketStart;
ArTransform mySimPacketTrans;
ArTransform mySimPacketEncoderTrans;
unsigned int mySimPacketCounter;
// connection
ArLMS2xxPacketReceiver myLMS2xxPacketReceiver;
ArMutex myStateMutex;
ArRetFunctorC<bool, ArLMS2xx> myAriaExitCB;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArSyncTask.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSYNCTASK_H
#define ARSYNCTASK_H
#include <string>
#include <map>
#include "ariaTypedefs.h"
#include "ArFunctor.h"
#include "ArTaskState.h"
/// Class used internally to manage the tasks that are called every cycle
/**
This is used internally, no user should normally have to create one, but
serious developers may want to use the members. Most users will be able to
add user tasks via the ArRobot class.
The way it works is that each instance is a node in a tree. The only node
that should ever be created with a new is the top one. The run and print
functions both call the run/print on themselves, then on all of their
children, going from lowest numbered position to highest numbered, lower
going first. There are no hard limits to the position, it can be any
integer. ARIA uses the convention of 0 to 100, when you add things of
your own you should leave room to add in between. Also you can add things
with the same position, the only effect this has is that the first addition
will show up first in the run or print.
After the top one is created, every other task should be created with
either addNewBranch() or addNewLeaf(). Each node can either be a branch node
or a list node. The list (a multimap) of branches/nodes is ordered
by the position passed in to the add function. addNewBranch() adds a new
branch node to the instance it is called on, with the given name and
position. addNewLeaf() adds a new leaf node to the instance it is called on,
with the given name and position, and also with the ArFunctor given, this
functor will be called when the leaf is run. Either add creates the new
instance and puts it in the list of branches/nodes in the approriate spot.
The tree takes care of all of its own memory management and list management,
the "add" functions put into the list and creates the memory, conversely
if you delete an ArSyncTask (which is the correct way to get rid of one)
it will remove itself from its parents list.
If you want to add something to the tree the proper way to do it is to get
the pointer to the root of the tree (ie with ArRobot::getSyncProcRoot) and
then to use find on the root to find the branch you want to travel down,
then continue this until you find the node you want to add to. Once there
just call addNewBranch or addNewLeaf and you're done.
The state of a task can be stored in the target of a given ArTaskState::State pointer,
or if NULL than ArSyncTask will use its own member variable.
@internal
*/
class ArSyncTask
{
public:
/// Constructor, shouldn't ever do a new on anything besides the root node
AREXPORT ArSyncTask(const char *name, ArFunctor * functor = NULL,
ArTaskState::State *state = NULL,
ArSyncTask * parent = NULL);
/// Destructor
AREXPORT virtual ~ArSyncTask();
/// Runs the node, which runs all children of this node as well
AREXPORT void run(void);
/// Prints the node, which prints all the children of this node as well
AREXPORT void log(int depth = 0);
/// Gets the state of the task
AREXPORT ArTaskState::State getState(void);
/// Sets the state of the task
AREXPORT void setState(ArTaskState::State state);
/// Finds the task in the instances list of children, by name
AREXPORT ArSyncTask *findNonRecursive(const char *name);
/// Finds the task in the instances list of children, by functor
AREXPORT ArSyncTask *findNonRecursive(ArFunctor *functor);
/// Finds the task recursively down the tree by name
AREXPORT ArSyncTask *find(const char *name);
/// Finds the task recursively down the tree by functor
AREXPORT ArSyncTask *find(ArFunctor *functor);
/// Returns what this is running, if anything (recurses)
AREXPORT ArSyncTask *getRunning(void);
/// Adds a new branch to this instance
AREXPORT void addNewBranch(const char *nameOfNew, int position,
ArTaskState::State *state = NULL);
/// Adds a new leaf to this instance
AREXPORT void addNewLeaf(const char *nameOfNew, int position,
ArFunctor *functor,
ArTaskState::State *state = NULL);
/// Gets the name of this task
AREXPORT std::string getName(void);
/// Gets the functor this instance runs, if there is one
AREXPORT ArFunctor *getFunctor(void);
/// Sets the functor called to get the cycle warning time (should only be used from the robot)
AREXPORT void setWarningTimeCB(
ArRetFunctor<unsigned int> *functor);
/// Gets the functor called to get the cycle warning time (should only be used from the robot)
AREXPORT ArRetFunctor<unsigned int> *getWarningTimeCB(void);
/// Sets the functor called to check if there should be a time warning this cycle (should only be used from the robot)
AREXPORT void setNoTimeWarningCB(
ArRetFunctor<bool> *functor);
/// Gets the functor called to check if there should be a time warning this cycle (should only be used from the robot)
AREXPORT ArRetFunctor<bool> *getNoTimeWarningCB(void);
// removes this task from the map
AREXPORT void remove(ArSyncTask * proc);
// returns whether this node is deleting or not
AREXPORT bool isDeleting(void);
protected:
std::multimap<int, ArSyncTask *> myMultiMap;
ArTaskState::State *myStatePointer;
ArTaskState::State myState;
ArFunctor *myFunctor;
std::string myName;
ArSyncTask *myParent;
bool myIsDeleting;
ArRetFunctor<unsigned int> *myWarningTimeCB;
ArRetFunctor<bool> *myNoTimeWarningCB;
// variables for introspection
bool myRunning;
// this is just a pointer to what we're invoking so we can know later
ArSyncTask *myInvokingOtherFunctor;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArIrrfDevice.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARIRRFDEVICE_H
#define ARIRRFDEVICE_H
#include "ariaTypedefs.h"
#include "ArRangeDevice.h"
#include "ArFunctor.h"
#include "ArRobot.h"
/// A class for connecting to a PB-9 and managing the resulting data
/**
This class is for use with a PB9 IR rangefinder. It has the packethandler
necessary to process the packets, and will put the data into ArRangeBuffers
for use with obstacle avoidance, etc.
The PB9 is still under development, and only works on an H8 controller
running AROS.
*/
class ArIrrfDevice : public ArRangeDevice
{
public:
/// Constructor
AREXPORT ArIrrfDevice(size_t currentBufferSize = 91,
size_t cumulativeBufferSize = 273,
const char * name = "irrf");
/// Destructor
AREXPORT virtual ~ArIrrfDevice();
/// The packet handler for use when connecting to an H8 micro-controller
AREXPORT bool packetHandler(ArRobotPacket *packet);
/// Maximum range for a reading to be added to the cumulative buffer (mm)
AREXPORT void setCumulativeMaxRange(double r) { myCumulativeMaxRange = r; }
AREXPORT virtual void setRobot(ArRobot *);
protected:
ArRetFunctor1C<bool, ArIrrfDevice, ArRobotPacket *> myPacketHandler;
ArTime myLastReading;
AREXPORT void processReadings(void);
double myCumulativeMaxRange;
double myFilterNearDist;
double myFilterFarDist;
std::map<int, ArSensorReading *> myIrrfReadings;
};
#endif // ARIRRFDEVICE_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArNetServer.h | <filename>Aria/ArNetServer.h
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARNETSERVER_H
#define ARNETSERVER_H
#include "ariaTypedefs.h"
#include "ArSocket.h"
#include "ArFunctor.h"
#include "ariaUtil.h"
#include <list>
class ArRobot;
class ArArgumentBuilder;
/// Class for running a simple net server to send/recv commands via text
/**
This class is for running a simple server which will have a
list of commands to use and a fairly simple set of interactions...
Start the server with the open() function, add commands with the
addCommand() function and remove commands with remCommand(), and close
the server with the close() function.
A client can connect via TCP on the port provided to open() and send
a line of text where the first word is the command and the following
words are extra arguments or data (space separated). The line should
end with a newline ("\n") or carriage return character. The first
line sent should be a password and must match the password given to
open() in order to continue.
You can use the "telnet" program as a general client to any ArNetServer server.
It has a built in mutex, if you only use sendToAllClients() through
the normal commands or during the robot loop you don't need to
worry about locking anything and the server is locked before any of
the callbacks for the commands are called so you really only need
to lock the server if you're dealing with from another thread....
From another thread you can use sendToAllClientsNextCycle which
takes care of all the locking itself in a threadsafe way (it puts
the message in a list, then sends it in the next cycle of the
loop). The only real reason to use the
lock/sendToAllClients/unlock method is if you're highly concerned
about synchronizing the different types of output.
@ingroup OptionalClasses
**/
class ArNetServer
{
public:
/// Constructor
AREXPORT ArNetServer(bool addAriaExitCB = true,
bool doNotAddShutdownServer = false,
const char *name = "ArNetServer",
ArNetServer *childServer = NULL);
/// Destructor
AREXPORT ~ArNetServer();
/// Initializes the server
AREXPORT bool open(ArRobot *robot, unsigned int port,
const char *password, bool multipleClients = true,
const char *openOnIP = NULL);
/// Closes the server
AREXPORT void close(void);
/// Adds a new command
AREXPORT bool addCommand(const char *command,
ArFunctor3<char **, int, ArSocket *> *functor,
const char *help);
/// Removes a command
AREXPORT bool remCommand(const char *command);
/// Gets the name of this instance
const char *getName(void) { return myName.c_str(); }
#ifndef SWIG
/** @brief Sends the given string to all the clients. See also the
* notes on locking in the class description.
* @swigomit @sa
* sendToAllClientsPlain()
*/
AREXPORT void sendToAllClients(const char *str, ...);
#endif
/// Sends the given string to all the clients, no varargs, wrapper for java
AREXPORT void sendToAllClientsPlain(const char *str);
#ifndef SWIG
/** @brief Sends the given string to all the clients next cycle
* @swigomit
* @sa sendToAllClientsNextCyclePlain()
*/
AREXPORT void sendToAllClientsNextCycle(const char *str, ...);
#endif
/// Sends the given string to all the clients next cycle, no varargs
AREXPORT void sendToAllClientsNextCyclePlain(const char *str);
/// Sends the given string to all the clients next cycle, no varargs... helper for config changes
AREXPORT bool sendToAllClientsNextCyclePlainBool(const char *str);
#ifndef SWIG
/** @brief Sends the given string to the (hopefully) the client given (this method may go away)
* @swigomit
* @sa sendToClientPlain()
*/
AREXPORT void sendToClient(ArSocket *socket, const char *ipString,
const char *str, ...);
#endif
/// Sends the given plain string to the (hopefully) the client given (this method may go away)
AREXPORT void sendToClientPlain(ArSocket *socket, const char *ipString,
const char *str);
/// Sees if the server is running and open
AREXPORT bool isOpen(void);
/// Sets whether we are logging all data sent or not
AREXPORT void setLoggingDataSent(bool loggingData);
/// Gets whether we are logging all data sent or not
AREXPORT bool getLoggingDataSent(void);
/// Sets whether we are logging all data received or not
AREXPORT void setLoggingDataReceived(bool loggingData);
/// Gets whether we are logging all data received or not
AREXPORT bool getLoggingDataReceived(void);
/// Sets whether we're using the wrong (legacy) end chars or not
AREXPORT void setUseWrongEndChars(bool useWrongEndChars);
/// Gets whether we're using the wrong (legacy) end chars or not
AREXPORT bool getUseWrongEndChars(void);
/// the internal sync task we use for our loop
AREXPORT void runOnce(void);
/// the internal function that gives the greeting message
AREXPORT void internalGreeting(ArSocket *socket);
/// The internal function that does the help
AREXPORT void internalHelp(ArSocket *socket);
/// The internal function for the help cb
AREXPORT void internalHelp(char **argv, int argc, ArSocket *socket);
/// The internal function for echo
AREXPORT void internalEcho(char **argv, int argc, ArSocket *socket);
/// The internal function for closing this connection
AREXPORT void internalQuit(char **argv, int argc, ArSocket *socket);
/// The internal function for shutting down
AREXPORT void internalShutdownServer(char **argv, int argc,
ArSocket *socket);
/// The internal function for parsing a command on a socket
AREXPORT void parseCommandOnSocket(ArArgumentBuilder *args,
ArSocket *socket, bool allowLog = true);
/// The internal function that adds a client to our list
AREXPORT void internalAddSocketToList(ArSocket *socket);
/// The internal function that adds a client to our delete list
AREXPORT void internalAddSocketToDeleteList(ArSocket *socket);
/// This squelchs all the normal commands and help
AREXPORT void squelchNormal(void);
/// Sets an extra string that the server holds for passing around
AREXPORT void setExtraString(const char *str) { myExtraString = str; }
/// Gets an extra string that the server holds for passing around
AREXPORT const char *getExtraString(void) { return myExtraString.c_str(); }
/// Lock the server
AREXPORT int lock() {return(myMutex.lock());}
/// Try to lock the server without blocking
AREXPORT int tryLock() {return(myMutex.tryLock());}
/// Unlock the server
AREXPORT int unlock() {return(myMutex.unlock());}
protected:
std::string myName;
ArNetServer *myChildServer;
ArMutex myMutex;
ArSocket myAcceptingSocket;
std::map<std::string, ArFunctor3<char **, int, ArSocket *> *, ArStrCaseCmpOp> myFunctorMap;
std::map<std::string, std::string, ArStrCaseCmpOp> myHelpMap;
bool myLoggingDataSent;
bool myLoggingDataReceived;
bool myUseWrongEndChars;
bool myOpened;
bool myWantToClose;
bool mySquelchNormal;
ArSocket myServerSocket;
ArRobot *myRobot;
std::string myPassword;
bool myMultipleClients;
unsigned int myPort;
std::string myExtraString;
std::list<ArSocket *> myConns;
std::list<ArSocket *> myConnectingConns;
std::list<ArSocket *> myDeleteList;
ArMutex myNextCycleSendsMutex;
std::list<std::string> myNextCycleSends;
ArFunctorC<ArNetServer> myTaskCB;
ArFunctor3C<ArNetServer, char **, int, ArSocket *> myHelpCB;
ArFunctor3C<ArNetServer, char **, int, ArSocket *> myEchoCB;
ArFunctor3C<ArNetServer, char **, int, ArSocket *> myQuitCB;
ArFunctor3C<ArNetServer, char **, int, ArSocket *> myShutdownServerCB;
ArFunctorC<ArNetServer> myAriaExitCB;
};
#endif // ARNETSERVER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionDeceleratingLimiter.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONDECELERATINGLIMITER_H
#define ARACTIONDECELERATINGLIMITER_H
#include "ariaTypedefs.h"
#include "ArAction.h"
/// Action to limit the forwards motion of the robot based on range sensor readings
/**
This action uses the robot's range sensors (e.g. sonar, laser) to find a
maximum speed at which to travel
and will increase the deceleration so that the robot doesn't hit
anything. If it has to, it will trigger an estop to avoid a
collision.
Note that this cranks up the deceleration with a strong strength,
but it checks to see if there is already something decelerating
more strongly... so you can put these actions lower in the priority list so
things will play together nicely.
@ingroup ActionClasses
**/
class ArActionDeceleratingLimiter : public ArAction
{
public:
enum LimiterType {
FORWARDS, ///< Limit forwards
BACKWARDS, ///< Limit backwards
LATERAL_LEFT, ///< Limit lateral left
LATERAL_RIGHT ///< Limit lateral right
};
/// Constructor
AREXPORT ArActionDeceleratingLimiter(const char *name = "limitAndDecel",
LimiterType type = FORWARDS);
/// Destructor
AREXPORT virtual ~ArActionDeceleratingLimiter();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
/// Sets the parameters (don't use this if you're using the addToConfig)
AREXPORT void setParameters(double clearance = 100,
double sideClearanceAtSlowSpeed = 50,
double paddingAtSlowSpeed = 50,
double slowSpeed = 200,
double sideClearanceAtFastSpeed = 400,
double paddingAtFastSpeed = 300,
double fastSpeed = 1000,
double preferredDecel = 600,
bool useEStop = false,
double maxEmergencyDecel = 0);
/// Gets if this will control us when going forwards
LimiterType getType(void) { return myType; }
/// Sets if this will control us when going forwards
void setType(LimiterType type) { myType = type; }
/// Adds to the ArConfig given, in section, with prefix
AREXPORT void addToConfig(ArConfig *config, const char *section,
const char *prefix = NULL);
/// Sets if we're using locationDependent range devices or not
bool getUseLocationDependentDevices(void)
{ return myUseLocationDependentDevices; }
/// Sets if we're using locationDependent range devices or not
void setUseLocationDependentDevices(bool useLocationDependentDevices)
{ myUseLocationDependentDevices = useLocationDependentDevices; }
// sets if we should stop rotation too if this action has stopped the robot
void setStopRotationToo(bool stopRotationToo)
{ myStopRotationToo = stopRotationToo; }
protected:
bool myLastStopped;
LimiterType myType;
double myClearance;
double mySideClearanceAtSlowSpeed;
double myPaddingAtSlowSpeed;
double mySlowSpeed;
double mySideClearanceAtFastSpeed;
double myPaddingAtFastSpeed;
double myFastSpeed;
double myPreferredDecel;
double myMaxEmergencyDecel;
bool myUseEStop;
bool myUseLocationDependentDevices;
bool myStopRotationToo;
//unused? double myDecelerateDistance;
ArActionDesired myDesired;
};
#endif // ARACTIONSPEEDLIMITER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionKeydrive.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONKEYDRIVE_H
#define ARACTIONKEYDRIVE_H
#include "ariaTypedefs.h"
#include "ArAction.h"
#include "ArFunctor.h"
class ArRobot;
/// This action will use the keyboard arrow keys for input to drive the robot
/// @ingroup ActionClasses
class ArActionKeydrive : public ArAction
{
public:
/// Constructor
AREXPORT ArActionKeydrive(const char *name = "keydrive",
double transVelMax = 400,
double turnAmountMax = 24,
double velIncrement = 25,
double turnIncrement = 8);
/// Destructor
AREXPORT virtual ~ArActionKeydrive();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
/// For setting the maximum speeds
AREXPORT void setSpeeds(double transVelMax, double turnAmountMax);
/// For setting the increment amounts
AREXPORT void setIncrements(double velIncrement, double turnIncrement);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
AREXPORT virtual void setRobot(ArRobot *robot);
AREXPORT virtual void activate(void);
AREXPORT virtual void deactivate(void);
/// Takes the keys this action wants to use to drive
AREXPORT void takeKeys(void);
/// Gives up the keys this action wants to use to drive
AREXPORT void giveUpKeys(void);
/// Internal, callback for up arrow
AREXPORT void up(void);
/// Internal, callback for down arrow
AREXPORT void down(void);
/// Internal, callback for left arrow
AREXPORT void left(void);
/// Internal, callback for right arrow
AREXPORT void right(void);
/// Internal, callback for space key
AREXPORT void space(void);
protected:
ArFunctorC<ArActionKeydrive> myUpCB;
ArFunctorC<ArActionKeydrive> myDownCB;
ArFunctorC<ArActionKeydrive> myLeftCB;
ArFunctorC<ArActionKeydrive> myRightCB;
ArFunctorC<ArActionKeydrive> mySpaceCB;
// action desired
ArActionDesired myDesired;
// full speed
double myTransVelMax;
// full amount to turn
double myTurnAmountMax;
// amount to increment vel by on an up arrow or decrement on a down arrow
double myVelIncrement;
// amount to increment turn by on a left arrow or right arrow
double myTurnIncrement;
// amount we want to speed up
double myDeltaVel;
// amount we want to turn
double myTurnAmount;
// what speed we want to go
double myDesiredSpeed;
// if our speeds been reset
bool mySpeedReset;
};
#endif // ARACTIONKEYDRIVE_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArBatteryMTX.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARBATTERYMTX_H
#define ARBATTERYMTX_H
#include "ariaTypedefs.h"
#include "ArRangeDevice.h"
#include "ArFunctor.h"
#include "ArRobot.h"
#include "ArRobotPacket.h"
#include "ArRobotConnector.h"
// Packets are in the format of
// 2 bytes header (0xfa 0xba)
// 1 byte length
// 1 byte command
// xx bytes command specific / args
// 2 bytes checksum
//
/**
@since 2.8.0
*/
class ArBatteryMTX : public ArASyncTask
{
public:
/// Constructor
AREXPORT ArBatteryMTX(
int batteryBoardNum = 0,
const char * name = "MTXBattery",
ArDeviceConnection *conn = NULL,
ArRobot *robot = NULL);
/// Destructor
AREXPORT virtual ~ArBatteryMTX();
// Grabs the new readings from the robot and adds them to the buffers
// (Primarily for internal use.)
//AREXPORT void processReadings(void);
int getBoardNum(void)
{ return myBoardNum; }
/// Sets the robot pointer, also attaches its process function to the
/// robot as a Sensor Interpretation task.
AREXPORT virtual void setRobot(ArRobot *robot);
/// Very Internal call that gets the packet sender, shouldn't be used
ArRobotPacketSender *getPacketSender(void)
{ return mySender; }
/// Very Internal call that gets the packet sender, shouldn't be used
ArRobotPacketReceiver *getPacketReceiver(void)
{ return myReceiver; }
/// Sets the device this instance receives packets from
AREXPORT void setDeviceConnection(ArDeviceConnection *conn);
/// Gets the device this instance receives packets from
AREXPORT ArDeviceConnection *getDeviceConnection(void);
AREXPORT int getAsyncConnectState(void);
ArRobotPacket getCellPacket()
{ return myCellPacket; }
AREXPORT virtual bool blockingConnect(bool sendTracking, bool recvTracking);
AREXPORT virtual bool disconnect(void);
virtual bool isConnected(void) { return myIsConnected; }
virtual bool isTryingToConnect(void)
{
if (myStartConnect)
return true;
else if (myTryingToConnect)
return true;
else
return false;
}
/// Lock this device
virtual int lockDevice() { return(myDeviceMutex.lock());}
/// Try to lock this device
virtual int tryLockDevice() {return(myDeviceMutex.tryLock());}
/// Unlock this device
virtual int unlockDevice() {return(myDeviceMutex.unlock());}
AREXPORT void logBatteryInfo(ArLog::LogLevel level = ArLog::Normal);
AREXPORT void logCellInfo(ArLog::LogLevel level = ArLog::Normal);
void log(ArLog::LogLevel level = ArLog::Normal)
{
logBatteryInfo(level);
logCellInfo(level);
}
AREXPORT bool sendPowerOff();
AREXPORT bool sendPowerOffCancel();
AREXPORT bool sendStopCharging();
AREXPORT bool sendStartCharging();
AREXPORT bool sendSetPowerOffDelay(unsigned int msDelay);
AREXPORT bool sendSetRealTimeClock(unsigned int secSinceEpoch);
AREXPORT bool sendResetCellData();
AREXPORT bool sendSetReserveValue(unsigned short hundredthOfPercent);
AREXPORT bool sendSetBalanceValue(unsigned short hundredthOfPercent);
AREXPORT bool sendEmergencyPowerOff();
AREXPORT bool sendSystemInfo(unsigned char dataValue);
AREXPORT bool sendCellInfo(unsigned char dataValue);
AREXPORT bool sendBasicInfo(unsigned char dataValue);
AREXPORT void updateSystemInfo(unsigned char *buf);
AREXPORT void updateCellInfo(unsigned char *buf);
AREXPORT void updateBasicInfo(unsigned char *buf);
// need to figure out how to pass back the system and cell info
//AREXPORT bool fetchSystemInfo();
//AREXPORT bool fetchCellInfo();
// basic info
/// Charge estimate (in percentage, 0-100)
double getChargeEstimate(void) const
{ return myChargeEstimate; }
/// Current draw (amps, negative is charging)
double getCurrentDraw(void) const
{ return myCurrentDraw; }
/// volts
double getPackVoltage(void) const
{ return myPackVoltage; }
int getStatusFlags(void) const
{ return myStatusFlags; }
int getErrorFlags(void) const
{ return myErrorFlags; }
bool onCharger(void) const
{ return (myStatusFlags & STATUS_ON_CHARGER); }
ArRobot::ChargeState getChargeState(void) const
{ return myChargeState; }
int getChargeStateAsInt(void) const
{ return myChargeState; }
// system info
int getId(void) const
{ return myId; }
int getFirmwareVersion(void) const
{ return myFirmwareVersion; }
int getSerialNumber(void) const
{ return mySerialNumber; }
//int getCurrentTime(void) const
// { return myCurrentTime; }
long long getCurrentTime(void) const
{ return myCurrentTime; }
long long getLastChargeTime(void) const
{ return myLastChargeTime; }
int getChargeRemainingEstimate(void) const
{ return myChargeRemainingEstimate; }
int getCapacityEstimate(void) const
{ return myCapacityEstimate; }
double getDelay(void) const
{ return myDelay; }
int getCycleCount(void) const
{ return myCycleCount; }
double getTemperature(void) const
{ return myTemperature; }
double getPaddleVolts(void) const
{ return myPaddleVolts; }
double getVoltage(void) const
{ return myVoltage; }
double getFuseVoltage(void) const
{ return myFuseVoltage; }
double getChargeCurrent(void) const
{ return myChargeCurrent; }
double getDisChargeCurrent(void) const
{ return myDisChargeCurrent; }
double getCellImbalance(void) const
{ return myCellImbalance; }
double getImbalanceQuality(void) const
{ return myImbalanceQuality; }
double getReserveChargeValue(void) const
{ return myReserveChargeValue; }
// cell info
int getNumCells(void) const
{ return myNumCells; }
int getCellFlag(int cellNum) const
{
std::map<int, CellInfo *>::const_iterator iter =
myCellNumToInfoMap.find(cellNum);
if (iter == myCellNumToInfoMap.end())
return -1;
else {
CellInfo *info = iter->second;
return(info->myCellFlags);
} }
int getCellCapacity(int cellNum) const
{
std::map<int, CellInfo *>::const_iterator iter =
myCellNumToInfoMap.find(cellNum);
if (iter == myCellNumToInfoMap.end())
return -1;
else {
CellInfo *info = iter->second;
return(info->myCellCapacity);
} }
int getCellCharge(int cellNum) const
{
std::map<int, CellInfo *>::const_iterator iter =
myCellNumToInfoMap.find(cellNum);
if (iter == myCellNumToInfoMap.end())
return -1;
else {
CellInfo *info = iter->second;
return(info->myCellCharge);
} }
double getCellVoltage(int cellNum) const
{
std::map<int, CellInfo *>::const_iterator iter =
myCellNumToInfoMap.find(cellNum);
if (iter == myCellNumToInfoMap.end())
return -1;
else {
CellInfo *info = iter->second;
return(info->myCellVoltage);
} }
/// Request a continous stream of packets
AREXPORT void requestContinuousSysInfoPackets(void);
/// Stop the stream of packets
AREXPORT void stopSysInfoPackets(void);
/// See if we've requested packets
AREXPORT bool haveRequestedSysInfoPackets(void);
/// Request a continous stream of packets
AREXPORT void requestContinuousCellInfoPackets(void);
/// Stop the stream of packets
AREXPORT void stopCellInfoPackets(void);
/// See if we've requested packets
AREXPORT bool haveRequestedCellInfoPackets(void);
AREXPORT virtual const char *getName(void) const;
void setInfoLogLevel(ArLog::LogLevel infoLogLevel)
{ myInfoLogLevel = infoLogLevel; }
/// Gets the default port type for the battery
const char *getDefaultPortType(void) { return myDefaultPortType.c_str(); }
/// Gets the default port type for the battery
const char *getDefaultTcpPort(void) { return myDefaultTcpPort.c_str(); }
/// Sets the numter of seconds without a response until connection assumed lost
virtual void setConnectionTimeoutSeconds(double seconds)
{ ArLog::log(ArLog::Normal,
"%s::setConnectionTimeoutSeconds: Setting timeout to %g secs",
getName(), seconds);
myTimeoutSeconds = seconds; }
/// Gets the number of seconds without a response until connection assumed lost
virtual double getConnectionTimeoutSeconds(void)
{return myTimeoutSeconds; }
/// check for lost connections
AREXPORT bool checkLostConnection(void);
/// disconnect
AREXPORT void disconnectOnError(void);
/// Gets the time data was last receieved
ArTime getLastReadingTime(void) { return myLastReading; }
/// Gets the number of battery readings received in the last second
AREXPORT int getReadingCount(void);
// Function called in sensorInterp to indicate that a
// reading was received
AREXPORT virtual void internalGotReading(void);
/// Adds a callback for when disconnection happens because of an error
void addDisconnectOnErrorCB(ArFunctor *functor,
int position = 51)
{ myDisconnectOnErrorCBList.addCallback(functor, position); }
/// Removes a callback for when disconnection happens because of an error
void remDisconnectOnErrorCB(ArFunctor *functor)
{ myDisconnectOnErrorCBList.remCallback(functor); }
/// Adds a callback for when the battery is powering off
void addBatteryPoweringOffCB(ArFunctor *functor,
int position = 51)
{ myBatteryPoweringOffCBList.addCallback(functor, position); }
/// Removes a callback for when the battery is powering off
void remBatteryPoweringOffCB(ArFunctor *functor)
{ myBatteryPoweringOffCBList.remCallback(functor); }
/// Adds a callback for when the battery is powering off
void addBatteryPoweringOffCancelledCB(ArFunctor *functor,
int position = 51)
{ myBatteryPoweringOffCancelledCBList.addCallback(functor, position); }
/// Removes a callback for when the battery is powering off
void remBatteryPoweringOffCancelledCB(ArFunctor *functor)
{ myBatteryPoweringOffCancelledCBList.remCallback(functor); }
// myStatusFlags
enum StatusFlags {
STATUS_ON_CHARGER=0x0001,
STATUS_CHARGING=0x0002,
STATUS_BALANCING_ENGAGED=0x0004,
STATUS_CHARGER_ON=0x0008,
STATUS_BATTERY_POWERING_OFF=0x0010,
/// MPL adding the rest of these since I need one of 'em
STATUS_MASTER_SWITCH_ON=0x0020,
STATUS_CHARGE_SWITCH_ON=0x0040,
STATUS_COMMANDED_SHUTDOWN=0x0080,
STATUS_OFF_BUTTON_PRESSED=0x0100,
STATUS_ON_BUTTON_PRESSED=0x0200,
STATUS_USER_BUTTON_PRESSED=0x0400
};
// myErrorFlags (if this is updated also change the code in interpBasicInfo
enum ErrorFlags {
ERROR_BATTERY_OVERVOLTAGE=0x0001,
ERROR_BATTERY_UNDERVOLTAGE=0x0002,
ERROR_OVERCURRENT=0x0004,
ERROR_BLOWNFUSE=0x0008,
ERROR_RTC_ERROR=0x0010,
ERROR_OVER_TEMPERATURE=0x0020,
ERROR_MASTER_SWITCH_FAULT=0x0040,
ERROR_SRAM_ERROR=0x0080,
ERROR_CHARGER_OUT_OF_VOLTAGE_RANGE=0x0100,
ERROR_CHARGER_CIRCUIT_FAULT=0x0200
};
enum Headers {
HEADER1=0xfa,
HEADER2=0xba
};
protected:
ArDeviceConnection *myConn;
int myAsyncConnectState;
std::string myName;
std::string myDefaultPortType;
std::string myDefaultTcpPort;
double myTimeoutSeconds;
bool myRobotRunningAndConnected;
ArTime myLastReading;
// packet count
time_t myTimeLastReading;
int myReadingCurrentCount;
int myReadingCount;
ArCallbackList myDisconnectOnErrorCBList;
ArCallbackList myBatteryPoweringOffCBList;
ArCallbackList myBatteryPoweringOffCancelledCBList;
ArRobot *myRobot;
ArFunctorC<ArBatteryMTX> myProcessCB;
AREXPORT virtual void batterySetName(const char *name);
AREXPORT virtual void * runThread(void *arg);
AREXPORT bool getSystemInfo();
AREXPORT bool getCellInfo();
AREXPORT bool getBasicInfo();
void interpBasicInfo(void);
void interpErrors(void);
void checkAndSetCurrentErrors(ErrorFlags errorFlag, const char *errorString);
// PS - need this because of debug log - battery won't send continuous cell
ArRobotPacket myCellPacket;
void sensorInterp(void);
void failedToConnect(void);
void clear(void);
bool myIsConnected;
bool myTryingToConnect;
bool myStartConnect;
ArRobot::ChargeState myChargeState;
int myBoardNum;
unsigned char myVersion;
ArLog::LogLevel myLogLevel;
//ArBatteryMTXPacketReceiver myReceiver;
ArRobotPacketReceiver *myReceiver;
ArRobotPacketSender *mySender;
ArMutex myPacketsMutex;
ArMutex myDataMutex;
ArMutex myDeviceMutex;
ArLog::LogLevel myInfoLogLevel;
//std::list<ArBatteryMTXPacket *> myPackets;
std::list<ArRobotPacket *> myPackets;
ArTime myPrevBatteryIntTime;
bool myRequestedSysInfoBatteryPackets;
bool myRequestedCellInfoBatteryPackets;
bool mySendTracking;
bool myRecvTracking;
// Protocol Commands
enum Commands {
BASIC_INFO=0x00,
SYSTEM_INFO=0x01,
CELL_INFO=0x02,
POWER_OFF_REQUEST=0x10,
POWER_OFF_CANCEL=0x11,
STOP_CHARGING=0x12,
START_CHARGING=0x13,
SET_POWER_OFF_DELAY=0x20,
SET_REAL_TIME_CLOCK=0x21,
RESET_CELL_DATA=0x22,
SET_RESERVE_VALUE=0x23,
SET_BALANCE_VALUE=0x24,
EMERGENCY_OFF=0xff
};
// SYSTEM_INFO and CELL_INFO Data
enum Data {
STOP_SENDING=0x00,
SEND_ONCE=0x01,
SEND_CONTINUOUS=0x02
};
// Length fields -
enum Sizes {
BASIC_INFO_SIZE=16,
SYSTEM_INFO_SIZE=60,
CELL_INFO_SIZE=95 // this is for 8 cells
};
// System Info
unsigned char myId;
unsigned char myFirmwareVersion;
unsigned int mySerialNumber;
long long myCurrentTime;
//unsigned int myCurrentTime;
//unsigned int myLastChargeTime;
long long myLastChargeTime;
unsigned int myChargeRemainingEstimate;
unsigned int myCapacityEstimate;
unsigned int myRawDelay;
double myDelay;
unsigned int myCycleCount;
unsigned short myRawTemperature;
double myTemperature;
unsigned short myRawPaddleVolts;
double myPaddleVolts;
unsigned short myRawVoltage;
double myVoltage;
unsigned short myRawFuseVoltage;
double myFuseVoltage;
unsigned short myRawChargeCurrent;
double myChargeCurrent;
unsigned short myRawDisChargeCurrent;
double myDisChargeCurrent;
unsigned short myRawCellImbalance;
double myCellImbalance;
unsigned short myRawImbalanceQuality;
double myImbalanceQuality;
unsigned short myRawReserveChargeValue;
double myReserveChargeValue;
// end system info
// Cell Info
// myCellFlags defines
enum CellFlags {
BALANCER_IS_ON=0x01,
OVER_VOLTAGE=0x02,
UNDER_VOLTAGE=0x04
};
struct CellInfo {
unsigned char myCellFlags;
unsigned short myRawCellVoltage;
double myCellVoltage;
unsigned short myCellCharge;
unsigned short myCellCapacity;
};
unsigned char myNumCells;
std::map <int, CellInfo *> myCellNumToInfoMap;
// end cell info
// Basic Info
unsigned short myRawChargeEstimate;
double myChargeEstimate;
short myRawCurrentDraw;
double myCurrentDraw;
unsigned short myRawPackVoltage;
double myPackVoltage;
unsigned short myStatusFlags;
unsigned short myErrorFlags;
bool myHaveSetRTC;
int myLastStatusFlags;
bool myFirstErrorFlagsCheck;
unsigned short myLastErrorFlags;
std::string myErrorString;
int myErrorCount;
std::string myLastErrorString;
int myLastErrorCount;
// end basic info
ArFunctorC<ArBatteryMTX> mySensorInterpTask;
ArRetFunctorC<bool, ArBatteryMTX> myAriaExitCB;
};
#endif // ARBATTERYMTX_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArActionBumpers.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System<gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARACTIONBUMPERS_H
#define ARACTIONBUMPERS_H
#include "ariaTypedefs.h"
#include "ArAction.h"
/// Action to deal with if the bumpers trigger
/**
This class basically responds to the bumpers the robot has, what
the activity things the robot has is decided by the param file. If
the robot is going forwards and bumps into something with the front
bumpers, it will back up and turn. If the robot is going backwards
and bumps into something with the rear bumpers then the robot will
move forward and turn.
@ingroup ActionClasses
*/
class ArActionBumpers : public ArAction
{
public:
/// Constructor
AREXPORT ArActionBumpers(const char *name = "bumpers",
double backOffSpeed = 100, int backOffTime = 3000,
int turnTime = 3000, bool setMaximums = false);
/// Destructor
AREXPORT virtual ~ArActionBumpers();
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
AREXPORT virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
AREXPORT virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
AREXPORT double findDegreesToTurn(int bumpValue, int whichBumper);
AREXPORT virtual void activate(void);
protected:
ArActionDesired myDesired;
bool mySetMaximums;
double myBackOffSpeed;
int myBackOffTime;
int myTurnTime;
//int myStopTime;
bool myFiring;
double mySpeed;
double myHeading;
int myBumpMask;
ArTime myStartBack;
//ArTime myStoppedSince;
};
#endif // ARACTIONBUMPERS
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArFileDeviceConnection.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARFILECONNECTION_H
#define ARFILECONNECTION_H
#include "ArDeviceConnection.h"
#include <string>
#include "ariaTypedefs.h"
#include "ArSocket.h"
/// Reads/writes data to a plain file or character device. Used occasionally
/// by certain tests/debugging. For real connections, use ArSerialConnection or
/// ArFileDeviceConnection instead.
class ArFileDeviceConnection: public ArDeviceConnection
{
public:
/// Constructor
AREXPORT ArFileDeviceConnection();
/// Destructor also closes connection
AREXPORT virtual ~ArFileDeviceConnection();
/// Opens a connection to the given host and port
AREXPORT int open(const char *infilename = NULL, const char *outfilename = NULL, int outflags = 0);
bool openSimple() { return this->open() == 0; }
AREXPORT virtual bool close(void);
AREXPORT virtual int read(const char *data, unsigned int size,
unsigned int msWait = 0);
AREXPORT virtual int write(const char *data, unsigned int size);
virtual int getStatus() { return myStatus; }
AREXPORT virtual const char *getOpenMessage(int err);
AREXPORT virtual ArTime getTimeRead(int index);
AREXPORT virtual bool isTimeStamping(void);
/// If >0 then only read at most this many bytes during read(), regardless of supplied size argument
void setForceReadBufferSize(unsigned int s) { myForceReadBufferSize = s; }
/// If >0 then add additional, artificial delay in read() by sleeping this many miliseconds per byte read in read().
void setReadByteDelay(float d) { myReadByteDelay = d; }
protected:
std::string myInFileName;
std::string myOutFileName;
int myInFD;
int myOutFD;
int myStatus;
unsigned int myForceReadBufferSize;
float myReadByteDelay;
};
#endif
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArRobotPacket.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARROBOTPACKET_H
#define ARROBOTPACKET_H
#include "ariaTypedefs.h"
#include "ArBasePacket.h"
#include "ariaUtil.h"
/// Represents the packets sent to the robot as well as those received from it
/**
This class reimplements some of the buf operations since the robot is
opposeite endian from intel. Also has the getID for convenience.
You can just look at the documentation for the ArBasePacket except for
the 4 new functions here, verifyCheckSum, getID, print, and calcCheckSum.
*/
class ArRobotPacket: public ArBasePacket
{
public:
/// Constructor
AREXPORT ArRobotPacket(unsigned char sync1 = 0xfa,
unsigned char sync2 = 0xfb);
/// Destructor
AREXPORT virtual ~ArRobotPacket();
/// Assignment operator
AREXPORT ArRobotPacket &operator=(const ArRobotPacket &other);
/// returns true if the checksum matches what it should be
AREXPORT bool verifyCheckSum(void);
/// returns the ID of the packet
AREXPORT ArTypes::UByte getID(void);
/// Sets the ID of the packet
AREXPORT void setID(ArTypes::UByte id);
/// returns the checksum, probably used only internally
AREXPORT ArTypes::Byte2 calcCheckSum(void);
// only call finalizePacket before a send
AREXPORT virtual void finalizePacket(void);
/// Gets the time the packet was received at
AREXPORT ArTime getTimeReceived(void);
/// Sets the time the packet was received at
AREXPORT void setTimeReceived(ArTime timeReceived);
AREXPORT virtual void log();
protected:
unsigned char mySync1;
unsigned char mySync2;
ArTime myTimeReceived;
};
#endif // ARROBOTPACKET_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | API/PioneerRobotInterface.h | /**
* @file PioneerRobotInterface.h
* @Author <NAME> (<EMAIL>)
* @date last January, 24th, 2021
* @brief PioneerRobotInterface class declaration
*
*
* This file defines the MainMenu's necessary functions
*/
#ifndef _PIONEERROBOTINTERFACE_
#define _PIONEERROBOTINTERFACE_
#include "PioneerRobotAPI.h"
#include "RobotInterface.h"
#include"../Sensors/RangeSensor.h"
#include"../Sensors/SonarSensor.h"
#include"../Sensors/LaserSensor.h"
#include "../Position/Pose.h"
class PioneerRobotInterface:public RobotInterface
{
private:
PioneerRobotAPI* robotAPI=new PioneerRobotAPI;
public:
PioneerRobotInterface(Pose*,PioneerRobotAPI*);
~PioneerRobotInterface();
void turnLeft();
void turnRight();
void forward(float);
void print();
void backward(float);
Pose getPose();
void setPose(Pose);
void stopTurn();
void stopMove();
void updateSensors();
};
#endif //! _PIONEERROBOTINTERFACE_
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArDPPTU.h | <reponame>Muhammedsuwaneh/Mobile_Robot_Control_System
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARDPPTU_H
#define ARDPPTU_H
#include "ariaTypedefs.h"
#include "ArRobot.h"
#include "ArPTZ.h"
#include <vector>
class ArBasePacket;
/** Interface to Directed Perception pan/tilt unit, implementing and extending the ArPTZ
* interface.
Functions such as pan(), tilt(), etc.
send requests to the PTU. By default, a new motion command will interrupt the
previous command, but the awaitExec() function sends a command instructing the
PTU to wait for the previous motion to finish.
Incoming data sent from the PTU is read every ArRobot task cycle (10hz). If this
data contains a message giving the current measured position of the pan and
tilt axes, then this is stored as the current pan and tilt positions, and a request for
the next positions is sent. (This means that the pan and tilt positions are
received as fast as the PTU can send them, but no faster than the robot task
cycle.) If no pan and tilt positions have been received, then ArDPPTU defaults
to providing as pan and tilt position whatever the last *requested* positions
are (from the last use of pan(), tilt() or panTilt()). (This is the standard
behavior specified by the ArPTZ interface, and lets you deal with different
kinds of PTUs, some of which cannot measure their own position.) You can also
always check the last pan or tilt request with getLastPanRequest() and
getLastTiltRequest().
To use ArDPPTU you must set the appropriate device connection (usually an
ArSerialConnection), open this connection, then call the init() method on the
ArDPPTU object. Then, you can use resetCalib() to have the unit perform a self
calibration routine, configure power modes, set speeds, etc.
The ArDPPTU constructor will switch on power to the PTU when on a Seekur or
Seekur Jr. robot. The shutdown() method (and destructor) will switch off power.
If a specific DPPTU type was given in the constructor, then some internal
conversion factors are set according to that type. If left as the
PANTILT_DEFAULT type, then the conversion factors are automatically determined
by querying the DPPTU device. PANTILT_DEFAULT is recommended.
The DPPTU performs a startup self-calibration routine when first powered on. You
can recalibrate by calling resetCalib().
By default the DPPTU is configured to use low power when in motion, and no power
on the motors when holding a position. This is OK for most cameras. However,
the DPPTU has a very high payload (especially PTU47 for outdoor use) and you
may want to enable higher power modes if the PTU slips when carrying heavy
payloads using setMovePower() and setHoldPower().
The DPPTU can be connected to a computer serial port (typically COM4) or through
a Pioneer microcontroller auxilliary serial port.
If the DPPTU is connected to the microcontroller, make sure that the baud rate of the microcontroller-DPPTU connection is at least as fast, if not faster than the connection of the computer to the microcontroller. If it's slower then the commands sent to the DPPTU may get backed up in the AUX port buffer and cause the DPPTU to behave erratically. So, if the computer-microcontroller connection is autobauding up to 38400bps, then make sure that the microcontroller aux port is set to 38400bps, as well, and consult the DPPTU manual for directions on changing its baud rate.
@sa the DPPTU manuals and documentation available at <a
href="http://robots.mobilerobots.com">http://robots.mobilerobots.com</a>
@ingroup OptionalClasses
*/
/// A class with the commands for the DPPTU
class ArDPPTUCommands
{
public:
enum {
DELIM = 0x20, ///<Space - Carriage return delimeter
INIT = 0x40, ///<Init character
ACCEL = 0x61, ///<Acceleration, Await position-command completion
BASE = 0x62, ///<Base speed
CONTROL = 0x63, ///<Speed control
DISABLE = 0x64, ///<Disable character, Delta, Default
ENABLE = 0x65, ///<Enable character, Echoing
FACTORY = 0x66, ///<Restore factory defaults
HALT = 0x68, ///<Halt, Hold, High
IMMED = 0x69, ///<Immediate position-command execution mode, Independent control mode
LIMIT = 0x6C, ///<Position limit character, Low
MONITOR = 0x6D, ///<Monitor, In-motion power mode
OFFSET = 0x6F, ///<Offset position, Off
PAN = 0x70, ///<Pan
RESET = 0x72, ///<Reset calibration, Restore stored defaults, Regular
SPEED = 0x73, ///<Speed, Slave
TILT = 0x74, ///<Tilt
UPPER = 0x75, ///<Upper speed limit
VELOCITY = 0x76 ///<Velocity control mode
};
};
/// A class for for making commands to send to the DPPTU
/**
Note, You must use byteToBuf() and byte2ToBuf(), no other ArBasePacket methods are
implemented for ArDPPTU.
Each ArDPPTUPacket represents a single command.
The packet is finalized by adding the delimiter (CR"") before being sent.
*/
class ArDPPTUPacket: public ArBasePacket
{
public:
/// Constructor
AREXPORT ArDPPTUPacket(ArTypes::UByte2 bufferSize = 30);
/// Destructor
AREXPORT virtual ~ArDPPTUPacket();
AREXPORT virtual void byte2ToBuf(int val);
AREXPORT virtual void finalizePacket(void);
protected:
};
/// Driver for the DPPTU
class ArDPPTU : public ArPTZ
{
public:
enum DeviceType {
PANTILT_DEFAULT, ///< Automatically detect correct settings
PANTILT_PTUD47, ///< Force settings for PTU-D47 @since 2.7.0
PANTILT_PTUD46 ///< Force settings for PTU-D46 @since 2.7.5
};
enum Axis {
PAN = 'P',
TILT = 'T'
};
/// Constructor
AREXPORT ArDPPTU(ArRobot *robot, DeviceType deviceType = PANTILT_DEFAULT, int deviceIndex = -1);
/// Destructor
AREXPORT virtual ~ArDPPTU();
AREXPORT bool init(void);
AREXPORT virtual const char *getTypeName() { return "dpptu"; }
virtual bool canZoom(void) const { return false; }
virtual bool canGetRealPanTilt() const { return myCanGetRealPanTilt; }
/// Sends a delimiter only
AREXPORT bool blank(void);
/// Perform reset calibration (PTU will move to the limits of pan and tilt axes in turn and return to 0,0)
AREXPORT bool resetCalib(void);
/// Change stored configuration options
/// @{
/// Configure DPPTU to disable future power-on resets
AREXPORT bool disableReset(void);
/// Configure DPPTU to only reset tilt on future power-up
AREXPORT bool resetTilt(void);
/// Configure DPPTU to only reset pan on future power up
AREXPORT bool resetPan(void);
/// Configure DPPTU to reset both pan and tilt on future power on
AREXPORT bool resetAll(void);
/// Enables monitor mode at power up
AREXPORT bool enMon(void);
/// Disables monitor mode at power up
AREXPORT bool disMon(void);
/// Save current settings as defaults
AREXPORT bool saveSet(void);
/// Restore stored defaults
AREXPORT bool restoreSet(void);
/// Restore factory defaults
AREXPORT bool factorySet(void);
///@}
protected:
///Move the pan and tilt axes
//@{
virtual bool panTilt_i(double pdeg, double tdeg)
{
return pan(pdeg) && tilt(tdeg);
}
AREXPORT virtual bool pan_i(double deg);
virtual bool panRel_i(double deg)
{
return panTilt(myPan+deg, myTilt);
}
AREXPORT virtual bool tilt_i(double deg);
virtual bool tiltRel_i(double deg)
{
return panTilt(myPan, myTilt+deg);
}
virtual bool panTiltRel_i(double pdeg, double tdeg)
{
return panRel(pdeg) && tiltRel(tdeg);
}
//@}
public:
/// Instructs unit to await completion of the last issued command
AREXPORT bool awaitExec(void);
/// Halts all pan-tilt movement
AREXPORT bool haltAll(void);
/// Halts pan axis movement
AREXPORT bool haltPan(void);
/// Halts tilt axis movement
AREXPORT bool haltTilt(void);
/// Sets monitor mode - pan pos1/pos2, tilt pos1/pos2
AREXPORT bool initMon(double deg1, double deg2, double deg3, double deg4);
///@}
/// Enables or disables the position limit enforcement
AREXPORT bool limitEnforce(bool val);
///Set execution modes
///@{
/// Sets unit to immediate-execution mode for positional commands. Commands will be executed by PTU as soon as they are received.
AREXPORT bool immedExec(void);
/// Sets unit to slaved-execution mode for positional commands. Commands will not be executed by PTU until awaitExec() is used.
AREXPORT bool slaveExec(void);
///@}
double getMaxPanSlew(void) { return myMaxPanSlew; }
virtual double getMaxPanSpeed() { return getMaxPanSlew(); }
double getMinPanSlew(void) { return myMinPanSlew; }
double getMaxTiltSlew(void) { return myMaxTiltSlew; }
virtual double getMaxTiltSpeed() { return getMaxTiltSlew(); }
double getMinTiltSlew(void) { return myMinTiltSlew; }
double getMaxPanAccel(void) { return myMaxPanSlew; }
double getMinPanAccel(void) { return myMinPanSlew; }
double getMaxTiltAccel(void) { return myMaxTiltSlew; }
double getMinTiltAccel(void) { return myMinTiltSlew; }
///Enable/disable moving and holding power modes for pan and tilt
///@{
enum PowerMode {
OFF = 'O',
LOW = 'L',
NORMAL = 'R',
HIGH = 'H'
};
/// Configure power mode for an axis when in motion.
/// init() sets initial moving power mode to Low, call this method to choose a different mode.
/// The recomended modes are either Low or Normal.
AREXPORT bool setMovePower(Axis axis, PowerMode mode);
/// Configure power mode for an axis when stationary.
/// init() sets the initial halted power to Off. Call this method to choose a different mode.
/// The recommended modes are Off or Low.
AREXPORT bool setHoldPower(Axis axis, PowerMode mode);
/// @deprecated
bool offStatPower(void) {
return setHoldPower(PAN, OFF) && setHoldPower(TILT, OFF);
}
/// @deprecated
bool regStatPower(void) {
return setHoldPower(PAN, NORMAL) && setHoldPower(TILT, NORMAL);
}
/// @deprecated
bool lowStatPower(void) {
return setHoldPower(PAN, LOW) && setHoldPower(TILT, LOW);
}
/// @deprecated
bool highMotPower(void) {
return setMovePower(PAN, HIGH) && setMovePower(TILT, HIGH);
}
/// @deprecated
bool regMotPower(void) {
return setMovePower(PAN, NORMAL) && setMovePower(TILT, NORMAL);
}
/// @deprecated
bool lowMotPower(void) {
return setMovePower(PAN, LOW) && setMovePower(TILT, LOW);
}
///@}
/// Sets acceleration for pan axis
AREXPORT bool panAccel(double deg);
/// Sets acceleration for tilt axis
AREXPORT bool tiltAccel(double deg);
/// Sets the start-up pan slew
AREXPORT bool basePanSlew(double deg);
/// Sets the start-up tilt slew
AREXPORT bool baseTiltSlew(double deg);
/// Sets the upper pan slew
AREXPORT bool upperPanSlew(double deg);
/// Sets the lower pan slew
AREXPORT bool lowerPanSlew(double deg);
/// Sets the upper tilt slew
AREXPORT bool upperTiltSlew(double deg);
/// Sets the lower pan slew
AREXPORT bool lowerTiltSlew(double deg);
/// Sets motion to indenpendent control mode
AREXPORT bool indepMove(void);
/// Sets motion to pure velocity control mode
AREXPORT bool velMove(void);
/// Sets the rate that the unit pans at
AREXPORT bool panSlew(double deg);
/// Sets the rate the unit tilts at
AREXPORT bool tiltSlew(double deg);
bool canPanTiltSlew() { return true; }
/// Sets the rate that the unit pans at, relative to current slew
AREXPORT bool panSlewRel(double deg) { return panSlew(myPanSlew+deg); }
/// Sets the rate the unit tilts at, relative to current slew
AREXPORT bool tiltSlewRel(double deg) { return tiltSlew(myTiltSlew+deg); }
/// called automatically by Aria::init()
///@since 2.7.6
///@internal
#ifndef SWIG
static void registerPTZType();
#endif
protected:
/// Get current pan/tilt position, if receiving from device, otherwise return
/// last position request sent to the device. @see canGetRealPanTilt()
//@{
virtual double getPan_i(void) const
{
return myPan;
}
virtual double getTilt_i(void) const
{
return myTilt;
}
//@}
public:
/// Get last pan/tilt requested. The device may still be moving towards these positions. (@sa getPan(), getTilt(), canGetRealPanTilt())
//@{
double getLastPanRequest() const { return myPanSent; }
double getLastTiltRequest() const { return myTiltSent; }
/// Gets the current pan slew
double getPanSlew(void) { return myPanSlew; }
/// Gets the current tilt slew
double getTiltSlew(void) { return myTiltSlew; }
/// Gets the base pan slew
double getBasePanSlew(void) { return myBasePanSlew; }
/// Gets the base tilt slew
double getBaseTiltSlew(void) { return myBaseTiltSlew; }
/// Gets the current pan acceleration rate
double getPanAccel(void) { return myPanAccel; }
/// Gets the current tilt acceleration rate
double getTiltAccel(void) { return myTiltAccel; }
AREXPORT void query(); // called from robot sensor interpretation task, or can be done seperately
protected:
ArRobot *myRobot;
ArDPPTUPacket myPacket;
void preparePacket(void); ///< adds on extra delim in front to work on H8
double myPanSent; ///< Last pan command sent
double myTiltSent; ///< Last tilt command sent
double myPanSlew;
double myTiltSlew;
double myBasePanSlew;
double myBaseTiltSlew;
double myPanAccel;
double myTiltAccel;
DeviceType myDeviceType;
/*
int myMaxPan;
int myMinPan;
int myMaxTilt;
int myMinTilt;
*/
int myMaxPanSlew;
int myMinPanSlew;
int myMaxTiltSlew;
int myMinTiltSlew;
int myMaxPanAccel;
int myMinPanAccel;
int myMaxTiltAccel;
int myMinTiltAccel;
float myPanConvert;
float myTiltConvert;
float myPan;
float myPanRecd; ///< Last pan value received from DPPTU from PP command
float myTilt;
float myTiltRecd; ///< Last tilt value received from DPPTU from TP command
bool myCanGetRealPanTilt;
bool myInit;
//AREXPORT virtual bool packetHandler(ArBasePacket *pkt);
AREXPORT virtual ArBasePacket *readPacket();
ArFunctorC<ArDPPTU> myQueryCB;
char *myDataBuf;
ArFunctorC<ArDPPTU> myShutdownCB;
int myDeviceIndex;
void shutdown();
ArTime myLastPositionMessageHandled;
bool myWarnedOldPositionData;
ArTime myLastQuerySent;
std::vector<char> myPowerPorts;
bool myGotPanRes;
bool myGotTiltRes;
///@since 2.7.6
static ArPTZ* create(size_t index, ArPTZParams params, ArArgumentParser *parser, ArRobot *robot);
///@since 2.7.6
static ArPTZConnector::GlobalPTZCreateFunc ourCreateFunc;
};
#endif // ARDPPTU_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArASyncTask.h | <filename>Aria/ArASyncTask.h
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARASYNCTASK_H
#define ARASYNCTASK_H
#include "ariaTypedefs.h"
#include "ArFunctor.h"
#include "ArThread.h"
/// Asynchronous task (runs in its own thread)
/**
The ArAsynTask is a task that runs in its own thread. This is a
rather simple class. The user simply needs to derive their own
class from ArAsyncTask and define the runThread() function. They
then need to create an instance of their task and call run or
runAsync. The standard way to stop a task is to call stopRunning()
which sets ArThread::myRunning to false. In their run loop, they
should pay attention to the getRunning() or the ArThread::myRunning
variable. If this value goes to false, the task should clean up
after itself and exit its runThread() function.
@ingroup UtilityClasses
**/
class ArASyncTask : public ArThread
{
public:
/// Constructor
AREXPORT ArASyncTask();
/// Destructor
AREXPORT virtual ~ArASyncTask();
/// The main run loop
/**
Override this function and put your taskes run loop here. Check the
value of getRunning() periodicly in your loop. If the value
is false, the loop should exit and runThread() should return.
The argument and return value are specific to the platform thread implementation, and
can be ignored.
@swignote In the wrapper libraries, this method takes no arguments and has no return value.
*/
AREXPORT virtual void * runThread(void *arg) = 0;
/// Run without creating a new thread
/**
This will run the the ArASyncTask without creating a new
thread to run it in. It performs the needed setup then calls runThread()
directly instead of letting the system threading system do it in a new thread.
*/
virtual void run(void) { runInThisThread(); }
/// Run in its own thread
virtual void runAsync(void) { create(); }
// reimplemented here just so its easier to see in the docs
/// Stop the thread
virtual void stopRunning(void) {myRunning=false;}
/// Create the task and start it going
AREXPORT virtual int create(bool joinable=true, bool lowerPriority=true);
/** Internal function used with system threading system to run the new thread.
In general, use run() or runAsync() instead.
@internal
*/
AREXPORT virtual void * runInThisThread(void *arg=0);
/// Gets a string that describes what the thread is doing, or NULL if it
/// doesn't know. Override this in your subclass to return a status
/// string. This can be used for debugging or UI display.
virtual const char *getThreadActivity(void) { return NULL; }
private:
// Hide regular Thread::Create
virtual int create(ArFunctor * /*func*/, bool /*joinable=true*/,
bool /*lowerPriority=true*/) {return(false);}
ArRetFunctor1C<void*, ArASyncTask, void*> myFunc;
};
#endif // ARASYNCTASK_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Position/Pose.h | <gh_stars>0
/**
* @file Pose.h
* @Author <NAME>
* @date December, 2020
* @brief This class is responsible for holding location info and management of the robot.
*/
#ifndef POSE_H
#define POSE_H
class Pose
{
public:
Pose() { x = 0; y = 0; th = 0; }
Pose(float, float, float);
float getX();
void setX(float);
float getY();
void setY(float);
void setTh(float);
float getTh();
bool operator ==(const Pose&);
Pose operator +(const Pose&);
Pose operator -(const Pose&);
Pose& operator +=(const Pose&);
Pose& operator -=(const Pose&);
bool operator <(const Pose&);
void getPose(float&, float&, float&);
void setPose(float, float, float);
float findDistanceTo(Pose);
float findAngleTo(Pose);
private:
float x;
float y;
float th;
};
#endif // !POSE_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Console Menu/mainMenu.h | /**
* @file mainMenu.h
* @Author <NAME> (<EMAIL>)
* @date last updated January 24th, 2021
* @brief Path class declaration
*
*
* This file declares the MainMenu class and all it's necessary functions
*/
#ifndef _MAINMENU_
#define _MAINMENU_
#include <iostream>
#include "../API/PioneerRobotAPI.h"
#include "../Controls/RobotControl.h"
#include"../Position/Pose.h"
#include"../Sensors/RangeSensor.h"
#include"../Sensors/LaserSensor.h"
#include"../Sensors/SonarSensor.h"
#include"../Records/Record.h"
#include"../Path/Path.h"
class MainMenu {
private:
PioneerRobotAPI robotAPI;
Pose pose;
RobotControl* robotcontrol = new RobotControl(&robotAPI,&pose);
float laserRange[724];
float sonarRange[16];
RangeSensor* lasers = new LaserSensor(&robotAPI,laserRange);
RangeSensor* sonars = new SonarSensor(&robotAPI,sonarRange);
Record record;
RobotInterface* robotInterface = new PioneerRobotInterface(&pose,&robotAPI);
bool connectionStatus = false;
public:
void displayMainMenu();
void connectionMenu();
void motionMenu();
void positionMenu();
void sensorMenu();
void print();
};
#endif //! _MAINMENU_
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArJoyHandler.h | <gh_stars>0
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARJOYHANDLER_H
#define ARJOYHANDLER_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#ifdef WIN32
#include <mmsystem.h> // for JOYINFO
#else // if not win32
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#endif
#ifdef linux
#include <linux/joystick.h> // for JS_DATA_TYPE
#endif
/// Interfaces to a computer joystick
/**
This class is used to read data from a joystick device attached to the computer
(usually via USB).
The joystick handler keeps track of the minimum and maximums for both
axes, updating them to constantly be better calibrated. The speeds set
with setSpeed() influence what is returned by getAdjusted() or getDoubles().
The joystick device is not opened until init() is called. If there was
an error connecting to the joystick device, it will return false, and
haveJoystick() will return false. After calling
init(), use getAdjusted() or getDoubles()
to get values, and getButton() to check whether a button is pressed. setSpeed() may be
called at any time to configure or reconfigure the range of the values returned by
getAdjusted() and getDoubles().
To get the raw data instead, use getUnfiltered() or getAxis().
For example, if you want the X axis output to range from -1000 to 1000, and the Y axis
output to range from -100 to 100, call <code>setSpeed(1000, 100);</code>.
The X joystick axis is usually the left-right axis, and Y is forward-back.
If a joystick has a Z axis, it is usually a "throttle" slider or dial on the
joystick. The usual way to
drive a robot with a joystick is to use the X joystick axis for rotational velocity,
and Y for translational velocity (note the robot coordinate system, this is its local
X axis), and use the Z axis to adjust the robot's maximum driving speed.
@ingroup OptionalClasses
*/
class ArJoyHandler
{
public:
/// Constructor
AREXPORT ArJoyHandler(bool useOSCal = true, bool useOldJoystick = false);
/// Destructor
AREXPORT ~ArJoyHandler();
/// Intializes the joystick, returns true if successful
AREXPORT bool init(void);
/// Returns if the joystick was successfully initialized or not
bool haveJoystick(void) { return myInitialized; }
/// Gets the adjusted reading, as floats, between -1.0 and 1.0
AREXPORT void getDoubles(double *x, double *y, double *z = NULL);
/// Gets the button
AREXPORT bool getButton(unsigned int button);
/// Returns true if we definitely have a Z axis (we don't know in windows unless it moves)
bool haveZAxis(void) { return myHaveZ; }
/// Sets the maximums for the x, y and optionally, z axes.
void setSpeeds(int x, int y, int z = 0)
{ myTopX = x; myTopY = y; myTopZ = z; }
/// Gets the adjusted reading, as integers, based on the setSpeed
AREXPORT void getAdjusted(int *x, int *y, int *z = NULL);
/// Gets the number of axes the joystick has
AREXPORT unsigned int getNumAxes(void);
/// Gets the floating (-1 to 1) location of the given joystick axis
AREXPORT double getAxis(unsigned int axis);
/// Gets the number of buttons the joystick has
AREXPORT unsigned int getNumButtons(void);
/// Sets whether to just use OS calibration or not
AREXPORT void setUseOSCal(bool useOSCal);
/// Gets whether to just use OS calibration or not
AREXPORT bool getUseOSCal(void);
/// Starts the calibration process
AREXPORT void startCal(void);
/// Ends the calibration process
AREXPORT void endCal(void);
/// Gets the unfilitered reading, mostly for internal use, maybe
/// useful for Calibration
AREXPORT void getUnfiltered(int *x, int *y, int *z = NULL);
/// Gets the stats for the joystick, useful after calibrating to save values
AREXPORT void getStats(int *maxX, int *minX, int *maxY, int *minY,
int *cenX, int *cenY);
/// Sets the stats for the joystick, useful for restoring calibrated settings
AREXPORT void setStats(int maxX, int minX, int maxY, int minY,
int cenX, int cenY);
/// Gets the maximums for each axis.
AREXPORT void getSpeeds(int *x, int *y, int *z);
protected:
// function to get the data for OS dependent part
void getData(void);
int myMaxX, myMinX, myMaxY, myMinY, myCenX, myCenY, myTopX, myTopY, myTopZ;
bool myHaveZ;
std::map<unsigned int, int> myAxes;
std::map<unsigned int, bool> myButtons;
int myPhysMax;
bool myInitialized;
bool myUseOSCal;
bool myUseOld;
bool myFirstData;
ArTime myLastDataGathered;
#ifdef WIN32
unsigned int myJoyID;
int myLastZ;
JOYINFO myJoyInfo;
JOYCAPS myJoyCaps;
#else // if not win32
int myJoyNumber;
char myJoyNameTemp[512];
ArTime myLastOpenTry;
void getOldData(void);
void getNewData(void);
#ifdef linux
struct JS_DATA_TYPE myJoyData; // structure for the buttons and x,y coords
#else
int myJoyData;
#endif
FILE * myOldJoyDesc;
int myJoyDesc;
#endif // linux
};
#endif // ARJOYHANDLER_H
|
Muhammedsuwaneh/Mobile_Robot_Control_System | Aria/ArExitErrorSource.h | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
<EMAIL> or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef AREXITERRORSOURCE_H
#define AREXITERRORSOURCE_H
/// Small interface for obtaining exit-on-error information
/**
* ArExitErrorSource may be implemented by classes that wish to
* provide information if and when they cause an erroneous
* application exit. The use of this interface is entirely at
* the discretion of the application. Aria does not invoke its
* methods.
**/
class ArExitErrorSource
{
public:
/// Constructor
ArExitErrorSource() {}
/// Destructor
virtual ~ArExitErrorSource() {}
/// Returns a textual description of the error source.
/**
* @param buf a char array in which the method puts the output
* error description
* @param bufLen the int number of char's in the array
* @return bool true if the description was successfully written;
* false if an error occurred
**/
virtual bool getExitErrorDesc(char *buf, int bufLen) = 0;
/// Returns a textual description of the error source intended for a user (it will be prefixed by something stating the action taking place)
/**
* @param buf a char array in which the method puts the output user
* error description
* @param bufLen the int number of char's in the array
* @return bool true if the description was successfully written;
* false if an error occurred
**/
virtual bool getExitErrorUserDesc(char *buf, int bufLen) = 0;
/// Returns the error code used for the exit call
/**
* Ideally, the returned error code should be unique across all
* error sources. (Past implementations have the method spec and
* body on a single line so that it's easily searchable... Current
* implementations have that OR this string on a line so that it'll
* show up searchable easily still).
**/
virtual int getExitErrorCode() const = 0;
}; // end class ArExitErrorSource
#endif // AREXITERRORSOURCE_H
|
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/Defines.h | #ifndef TRIXBRIX_DEFINES_H
#define TRIXBRIX_DEFINES_H
//////////////////////////////////////// PINS ////////////////////////////////////////
#define LED_PCB1 10 //PB2 PCINT2 SS OC1B
#define LED_PCB2 7 //PD7 PCINT23 AIN1
#define LED_SIGNAL1 14 //PC0 PCINT8 ADC0
#define LED_SIGNAL2 15 //PC1 PCINT9 ADC1
#define BUTTON_RIGHT 3 //PD3 PCINT19 OC2B INT1
#define BUTTON_LEFT 2 //PD2 PCINT18 INT0
#define DIST_SENS1 17 //PC3 PCINT11 ADC3
#define DIST_SENS2 16 //PC2 PCINT10 ADC2
#define SERVO1 18 //PC4 PCINT12 ADC4 SDA
#define SERVO1_POW 4 //PD4 PCINT20
#define SERVO1_NEG 8 //PB0 PCINT0
#define SERVO1_NEG_POW 9 //PB1 PCINT1 OC1A
#define SERVO2 19 //PC5 PCINT13 ADC5 SCL
//////////////////////////////////////// DEFINES ////////////////////////////////////////
//////// DEBUG MODES //////// to enable debug uncoment at least debug basic mode or more options
//#define DEBUG_MODE_BASIC
//#define DEBUG_MODE_PCINT
//#define DEBUG_MODE_TIMERSs
//#define DEBUG_MODE_INTERRUPTS
//#define DEBUG_MODE_COOLDOWN_MEASURE
#define EEPROM_ADDRESS 4
#define SERVO1_RIGHT_CLICK 56 //angle for switch servo in position 1
#define SERVO1_LEFT_CLICK 98 //angle for switch servo in position 2
#define SERVO2_RIGHT_CLICK 0 //angle for boom barrier servo in posiotion down
#define SERVO2_LEFT_CLICK 88 //angle for boom barrier servo in posiotion up
#define DIFF 0 //angle which switch servo goes back after reaching position defined by values above, leave 0 for function disable
#define COOLDOWN_MS 1100 //time [ms] during which controller is insensitive for signals from distance sensors, used to avoid false reactions caused by gaps between consecutive railroad cars
#define SWITCH_ON_SERVO_DELAY_MS 50 //time [ms] after turning power on the switch servo when command for the servo is going to be sent, after whole switching sequence power is going to be turn off
#define SWITCH_ON_SERVO_DURATION_MS 180 //time [ms] for which switch servo is powered in single sequence and can move
#define SWITCH_ON_SERVO_LATENCY_MS 100 //latency [ms] which indicates how fast consecutive switch sequences can be performed
#define SLOW_MOVE_SERVO_MOVE_DIVIDER 44 //number of steps in which single boom barrier servo move is divided, the more steps the slower move is going to be performed
#define MOVE_SERVO_PERIOD_US 20000 //period [us] of a single steering signal, it's duty depends on angle where servo should stops
#endif |
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/Globals.h | #ifndef TRIXBRIX_GLOBALS_H
#define TRIXBRIX_GLOBALS_H
#include "Trixbrix/Types.h"
extern volatile enum boom_barrier_position actualBoomBarrierPosition;
extern char activePcbLed;
extern char activeSignalLed;
extern enum mode distanceSensorMode;
extern char ledChangeMode;
extern volatile char buttonPressedOrDistSensWorkedInSwitchMode;
extern volatile char distSensWorkedInSwitchModeInQueue;
extern volatile bool risingOrFallingDistSens1;
extern volatile bool risingOrFallingDistSens2;
extern volatile char distSensWorkedInBoomBarrierMode;
extern volatile char distSensWorkedInBoomBarrierMode_StateToSwitchEnd;
extern volatile char distSens1_SwitchModeCooldownLock;
extern volatile char distSens2_SwitchModeCooldownLock;
extern volatile char whichDistSensWorkedPrev;
extern volatile bool distSens1_PrevState;
extern volatile bool distSens2_PrevState;
extern volatile int iteratorTimer0Loop;
extern volatile int iteratorTimer1Loop;
extern volatile int iteratorTimer2Loop;
extern volatile char switchLedState;
extern volatile enum train_detected newTrainDetectedInBoomBarrierMode;
extern volatile unsigned long currTime;
#endif
|
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/ServoLedControl.h | #ifndef TRIXBRIX_SERVOLEDCONTROL_H
#define TRIXBRIX_SERVOLEDCONTROL_H
#include "Trixbrix/Trixbrix.h"
void bothLedBlink(char blinks);
void signalLedChange(int changeMode);
void moveServo(enum servos servo, unsigned int angle, unsigned int timesOfRepeat);
void slowMoveServo(enum servos servo, int startPosition, int endPosition);
void switchPosition1(void);
void switchPosition2(void);
void positionBoomBarrierClose(void);
void positionBoomBarrierOpen(void);
#endif |
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/TimersAndInterruptsHandle.h | #ifndef TRIXBRIX_TIMERS_AND_INTERRUPTS_HANDLE
#define TRIXBRIX_TIMERS_AND_INTERRUPTS_HANDLE
#include "Trixbrix/Trixbrix.h"
void timerLedBlinkInit(void);
void timerLedBlinkDeinit(void);
void timerCooldownInit(int timerInput);
void timerCooldownDeinit(void);
void slopeDetDistSens1Init(enum edge_detection risingOrFalling);
void slopeDetDistSens1Deinit(void);
void slopeDetDistSens2Init(enum edge_detection risingOrFalling);
void slopeDetDistSens2Deinit(void);
void resetStateAfterBoomBarrierSeq(void);
ISR(TIMER0_COMPA_vect);
ISR(TIMER2_COMPA_vect);
ISR(PCINT1_vect);
#endif |
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/Trixbrix.h | <reponame>trixbrix/All-In-One_Controller_2.0
#ifndef TRiXBRIX_TRIXBRIX_H
#define TRiXBRIX_TRIXBRIX_H
#include <Arduino.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "Trixbrix/Defines.h"
#include "Trixbrix/Globals.h"
#include "Trixbrix/Types.h"
#include "Trixbrix/ServoLedControl.h"
#include "Trixbrix/TimersAndInterruptsHandle.h"
#endif |
trixbrix/All-In-One_Controller_2.0 | lib/Trixbrix/Trixbrix/Types.h | <gh_stars>1-10
#ifndef TRIXBRIX_TYPES_H
#define TRIXBRIX_TYPES_H
enum edge_detection {rising, falling}; //rising or falling
enum train_detected {not_detected, detected}; //not detected or detected
enum mode {switch_mode, boom_barrier_mode}; //switch mode or boom barriers mode(1 blik - switch_mode, 2 bliks - boom_barrier_mode while changing mode with both buttons pressed)
enum servos {servo1, servo1_neg, servo2}; //servo1 or servo1 negative or servo2
enum boom_barrier_position {closed, opened}; //closed or opened
#endif |
keystone-enclave/FreeRTOS-Kernel | main/include/msg_test.h | <filename>main/include/msg_test.h
#ifndef MSG_CONF_H
#define MSG_CONF_H
#define DATA_SIZE 512
#endif |
keystone-enclave/FreeRTOS-Kernel | main/include/rl_config.h | #ifndef _RL_CONFIG_H
/* *** Configurations *** */
/* Enables all tasks to be switched via the SM*/
/* All tasks must be registered by the SM */
// #define TASK_REGISTER_ALL
/* Enclave Agent <-> Enclave Driver*/
// #define EA_ED_RL
/* Task Agent <-> Task Driver*/
// #define TA_TD_RL
/* Enclave Agent <-> Task Driver*/
// #define EA_TD_RL
/* Task Agent <-> Enclave Driver*/
// #define TA_ED_RL
// #define RV8
// #define MSG_TEST_TASK
#define MSG_TEST_ENCLAVE
#define SYNC
#ifdef EA_ED_RL
#define AGENT_TID 1
#define DRIVER_TID 2
#endif
#ifdef TA_TD_RL
/* We do nothing since tasks do not need to use the mailbox. */
#endif
#ifdef EA_TD_RL
#ifdef TASK_REGISTER_ALL
#define AGENT_TID 1
#define DRIVER_TID 2
#else
#define AGENT_TID 1
#define DRIVER_TID 0
#endif
#endif
#ifdef TA_ED_RL
#ifdef TASK_REGISTER_ALL
#define AGENT_TID 1
#define DRIVER_TID 2
#else
#define AGENT_TID 0
#define DRIVER_TID 1
#endif
#endif
/* USED FOR DEBUGGING PURPOSES! */
/* Runs purely enclave task tests. */
// #define ENCLAVE
/* Runs purely task tests */
// #define TEST
#endif |
keystone-enclave/FreeRTOS-Kernel | sdk/agent/agent.c | <reponame>keystone-enclave/FreeRTOS-Kernel
#include <stdint.h>
#include <timex.h>
#include "enclave_rl.h"
#include "printf.h"
#include "eapp_utils.h"
#define RAND_MAX 2147483647
static unsigned long my_rand_state = 1;
long rand()
{
my_rand_state = (my_rand_state * 1103515245 + 12345) % 2147483648;
return my_rand_state;
}
double q_table[Q_STATE][N_ACTION] = {0};
int finish = 0;
struct context
{
int reward;
int done;
struct pos next_pos;
};
int max_action(double *actions)
{
double max = 0.0;
int max_idx = 0;
for (int i = 0; i < N_ACTION; i++)
{
if (actions[i] > max)
{
max = actions[i];
max_idx = i;
}
}
return max_idx;
}
double max(double *actions)
{
double ret = 0.0;
for (int i = 0; i < N_ACTION; i++)
{
if (actions[i] > ret)
{
ret = actions[i];
}
}
return ret;
}
void print_q_table()
{
for (int i = 0; i < Q_STATE_N; i++)
{
for (int j = 0; j < Q_STATE_N; j++)
{
printf("| ");
for (int k = 0; k < N_ACTION; k++)
{
printf("%.2f ", q_table[i * Q_STATE_N + j][k]);
}
printf("| ");
}
printf("\n");
}
printf("\n");
}
void send_finish(int DRIVER_TID){
struct send_action_args args;
args.msg_type = FINISH;
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
}
void send_env_reset(int DRIVER_TID){
struct send_action_args args;
int reset_ack;
args.msg_type = RESET;
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
while(sbi_recv(DRIVER_TID, &reset_ack, sizeof(struct send_action_args), YIELD));
}
void send_env_step(int DRIVER_TID, struct probability_matrix_item *next, int action){
struct send_action_args args;
struct ctx ctx_buf;
args.action = action;
args.msg_type = STEP;
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
while(sbi_recv(DRIVER_TID, &ctx_buf, sizeof(struct ctx), YIELD));
next->ctx.done = ctx_buf.done;
next->ctx.new_state = ctx_buf.new_state;
next->ctx.reward = ctx_buf.reward;
}
void EAPP_ENTRY eapp_entry(int DRIVER_TID)
{
cycles_t st = get_cycles();
printf("Agent Start Time: %u\n", st);
printf("Enter Agent\n");
int action;
int state;
int new_state;
int reward;
int done;
int rewards_current_episode = 0;
struct probability_matrix_item next;
double e_greedy = E_GREEDY;
int i, j;
for (i = 0; i < NUM_EPISODES; i++)
{
done = FALSE;
rewards_current_episode = 0;
state = 0;
send_env_reset(DRIVER_TID);
for (j = 0; j < STEPS_PER_EP; j++)
{
float random_f = (float)rand() / (float)(RAND_MAX / 1.0);
if (random_f > e_greedy)
{
action = max_action(q_table[state]);
}
else
{
action = rand() % 4;
}
send_env_step(DRIVER_TID, &next, action);
new_state = next.ctx.new_state;
reward = next.ctx.reward;
done = next.ctx.done;
q_table[state][action] = q_table[state][action] * (1.0 - LEARN_RATE) + LEARN_RATE * (reward + DISCOUNT * max(q_table[new_state]));
state = new_state;
rewards_current_episode += reward;
if (done == TRUE)
{
if (reward == 1)
{
if (e_greedy > E_GREEDY_F)
e_greedy *= E_GREEDY_DECAY;
#ifdef DEBUG
printf("You reached the goal!\n");
#endif
}
else
{
#ifdef DEBUG
printf("You fell in a hole!\n");
#endif
}
break;
}
}
if (i % 10 == 0)
{
printf("Episode: %d, Steps taken: %d, Reward: %d\n", i, j, rewards_current_episode);
}
}
send_finish(DRIVER_TID);
cycles_t et = get_cycles();
printf("Agent End Time: %u\nAgent Duration: %u\n", et, et - st);
syscall_task_return();
}
|
keystone-enclave/FreeRTOS-Kernel | sdk/rv8/norx/norx.c | /*
* cifra - embedded cryptography library
* Written in 2014 by <NAME> <<EMAIL>>
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
// #include <stdio.h>
// #include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include "printf.h"
#include "string.h"
// #include <strings.h>
// #include <assert.h>
#include <eapp_utils.h>
#include "malloc.h"
typedef struct
{
uint32_t s[16];
} norx32_ctx;
/* Domain separation constants */
#define DOMAIN_HEADER 0x01
#define DOMAIN_PAYLOAD 0x02
#define DOMAIN_TRAILER 0x04
#define DOMAIN_TAG 0x08
#define WORD_BYTES 4
#define WORD_BITS 32
#define ROUNDS 4
#define DEGREE 1
#define TAG_BITS 128
#define RATE_BYTES 48
#define RATE_WORDS 12
/* Assorted bitwise and common operations used in ciphers. */
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
static inline void
bzero (void *s, size_t len)
{
memset (s, '\0', len);
}
/** Circularly rotate right x by n bits.
* 0 > n > 32. */
static inline uint32_t rotr32(uint32_t x, unsigned n)
{
return (x >> n) | (x << (32 - n));
}
/** Read 4 bytes from buf, as a 32-bit little endian quantity. */
static inline uint32_t read32_le(const uint8_t buf[4])
{
return (buf[3] << 24) |
(buf[2] << 16) |
(buf[1] << 8) |
(buf[0]);
}
/** Encode v as a 32-bit little endian quantity into buf. */
static inline void write32_le(uint32_t v, uint8_t buf[4])
{
*buf++ = v & 0xff;
*buf++ = (v >> 8) & 0xff;
*buf++ = (v >> 16) & 0xff;
*buf = (v >> 24) & 0xff;
}
typedef void (*cf_blockwise_in_fn)(void *ctx, const uint8_t *data);
void cf_blockwise_accumulate_final(uint8_t *partial, size_t *npartial, size_t nblock,
const void *inp, size_t nbytes,
cf_blockwise_in_fn process,
cf_blockwise_in_fn process_final,
void *ctx)
{
const uint8_t *bufin = inp;
// assert(partial && *npartial < nblock);
// assert(inp || !nbytes);
// assert(process && ctx);
/* If we have partial data, copy in to buffer. */
if (*npartial && nbytes)
{
size_t space = nblock - *npartial;
size_t taken = MIN(space, nbytes);
memcpy(partial + *npartial, bufin, taken);
bufin += taken;
nbytes -= taken;
*npartial += taken;
/* If that gives us a full block, process it. */
if (*npartial == nblock)
{
if (nbytes == 0)
process_final(ctx, partial);
else
process(ctx, partial);
*npartial = 0;
}
}
/* now nbytes < nblock or *npartial == 0. */
/* If we have a full block of data, process it directly. */
while (nbytes >= nblock)
{
/* Partial buffer must be empty, or we're ignoring extant data */
// assert(*npartial == 0);
if (nbytes == nblock)
process_final(ctx, bufin);
else
process(ctx, bufin);
bufin += nblock;
nbytes -= nblock;
}
/* Finally, if we have remaining data, buffer it. */
while (nbytes)
{
size_t space = nblock - *npartial;
size_t taken = MIN(space, nbytes);
memcpy(partial + *npartial, bufin, taken);
bufin += taken;
nbytes -= taken;
*npartial += taken;
/* If we started with *npartial, we must have copied it
* in first. */
// assert(*npartial < nblock);
}
}
void cf_blockwise_accumulate(uint8_t *partial, size_t *npartial, size_t nblock,
const void *inp, size_t nbytes,
cf_blockwise_in_fn process,
void *ctx)
{
cf_blockwise_accumulate_final(partial, npartial, nblock,
inp, nbytes,
process, process, ctx);
}
/* cifra norx */
static void permute(norx32_ctx *restrict ctx)
{
/* This is one quarter of G; the function H plus xor/rotate. */
#define P(u, v, w, rr) \
(u) = ((u) ^ (v)) ^ (((u) & (v)) << 1); \
(w) = rotr32((u) ^ (w), rr);
#define G(s, a, b, c, d) \
P(s[a], s[b], s[d], 8) \
P(s[c], s[d], s[b], 11) \
P(s[a], s[b], s[d], 16) \
P(s[c], s[d], s[b], 31)
for (int i = 0; i < ROUNDS; i++)
{
/* columns */
G(ctx->s, 0, 4, 8, 12);
G(ctx->s, 1, 5, 9, 13);
G(ctx->s, 2, 6, 10, 14);
G(ctx->s, 3, 7, 11, 15);
/* diagonals */
G(ctx->s, 0, 5, 10, 15);
G(ctx->s, 1, 6, 11, 12);
G(ctx->s, 2, 7, 8, 13);
G(ctx->s, 3, 4, 9, 14);
}
#undef G
#undef P
}
static void init(norx32_ctx *ctx,
const uint8_t key[static 16],
const uint8_t nonce[static 8])
{
/* 1. Basic setup */
ctx->s[0] = read32_le(nonce + 0);
ctx->s[1] = read32_le(nonce + 4);
ctx->s[2] = 0xb707322f;
ctx->s[3] = 0xa0c7c90d;
ctx->s[4] = read32_le(key + 0);
ctx->s[5] = read32_le(key + 4);
ctx->s[6] = read32_le(key + 8);
ctx->s[7] = read32_le(key + 12);
ctx->s[8] = 0xa3d8d930;
ctx->s[9] = 0x3fa8b72c;
ctx->s[10] = 0xed84eb49;
ctx->s[11] = 0xedca4787;
ctx->s[12] = 0x335463eb;
ctx->s[13] = 0xf994220b;
ctx->s[14] = 0xbe0bf5c9;
ctx->s[15] = 0xd7c49104;
/* 2. Parameter integration
* w = 32
* l = 4
* p = 1
* t = 128
*/
ctx->s[12] ^= WORD_BITS;
ctx->s[13] ^= ROUNDS;
ctx->s[14] ^= DEGREE;
ctx->s[15] ^= TAG_BITS;
permute(ctx);
}
/* Input domain separation constant for next step, and final permutation of
* preceeding step. */
static void switch_domain(norx32_ctx *ctx, uint32_t constant)
{
ctx->s[15] ^= constant;
permute(ctx);
}
typedef struct
{
norx32_ctx *ctx;
uint32_t type;
} blockctx;
static void input_block_final(void *vctx, const uint8_t *data)
{
blockctx *bctx = vctx;
norx32_ctx *ctx = bctx->ctx;
/* just xor-in data. */
for (int i = 0; i < RATE_WORDS; i++)
{
ctx->s[i] ^= read32_le(data);
data += WORD_BYTES;
}
}
static void input_block(void *vctx, const uint8_t *data)
{
/* Process block, then prepare for the next one. */
blockctx *bctx = vctx;
input_block_final(vctx, data);
switch_domain(bctx->ctx, bctx->type);
}
static void input(norx32_ctx *ctx, uint32_t type,
const uint8_t *buf, size_t nbuf)
{
uint8_t partial[RATE_BYTES];
size_t npartial = 0;
blockctx bctx = { ctx, type };
/* Process input. */
cf_blockwise_accumulate(partial, &npartial, sizeof partial,
buf, nbuf,
input_block,
&bctx);
/* Now pad partial. This contains the trailing portion of buf. */
memset(partial + npartial, 0, sizeof(partial) - npartial);
partial[npartial] = 0x01;
partial[sizeof(partial) - 1] ^= 0x80;
input_block_final(&bctx, partial);
}
static void do_header(norx32_ctx *ctx, const uint8_t *buf, size_t nbuf)
{
if (nbuf)
{
switch_domain(ctx, DOMAIN_HEADER);
input(ctx, DOMAIN_HEADER, buf, nbuf);
}
}
static void do_trailer(norx32_ctx *ctx, const uint8_t *buf, size_t nbuf)
{
if (nbuf)
{
switch_domain(ctx, DOMAIN_TRAILER);
input(ctx, DOMAIN_TRAILER, buf, nbuf);
}
}
static void body_block_encrypt(norx32_ctx *ctx,
const uint8_t plain[static RATE_BYTES],
uint8_t cipher[static RATE_BYTES])
{
for (int i = 0; i < RATE_WORDS; i++)
{
ctx->s[i] ^= read32_le(plain);
write32_le(ctx->s[i], cipher);
plain += WORD_BYTES;
cipher += WORD_BYTES;
}
}
static void encrypt_body(norx32_ctx *ctx,
const uint8_t *plain, uint8_t *cipher, size_t nbytes)
{
if (nbytes == 0)
return;
/* Process full blocks: easy */
while (nbytes >= RATE_BYTES)
{
switch_domain(ctx, DOMAIN_PAYLOAD);
body_block_encrypt(ctx, plain, cipher);
plain += RATE_BYTES;
cipher += RATE_BYTES;
nbytes -= RATE_BYTES;
}
/* Final padded block. */
uint8_t partial[RATE_BYTES];
memset(partial, 0, sizeof partial);
memcpy(partial, plain, nbytes);
partial[nbytes] ^= 0x01;
partial[sizeof(partial) - 1] ^= 0x80;
switch_domain(ctx, DOMAIN_PAYLOAD);
body_block_encrypt(ctx, partial, partial);
memcpy(cipher, partial, nbytes);
}
static void body_block_decrypt(norx32_ctx *ctx,
const uint8_t cipher[static RATE_BYTES],
uint8_t plain[static RATE_BYTES],
size_t start, size_t end)
{
for (size_t i = start; i < end; i++)
{
uint32_t ct = read32_le(cipher);
write32_le(ctx->s[i] ^ ct, plain);
ctx->s[i] = ct;
plain += WORD_BYTES;
cipher += WORD_BYTES;
}
}
static void undo_padding(norx32_ctx *ctx, size_t bytes)
{
// assert(bytes < RATE_BYTES);
ctx->s[bytes / WORD_BYTES] ^= 0x01 << ((bytes % WORD_BYTES) * 8);
ctx->s[RATE_WORDS - 1] ^= 0x80000000;
}
static void decrypt_body(norx32_ctx *ctx,
const uint8_t *cipher, uint8_t *plain, size_t nbytes)
{
if (nbytes == 0)
return;
/* Process full blocks. */
while (nbytes >= RATE_BYTES)
{
switch_domain(ctx, DOMAIN_PAYLOAD);
body_block_decrypt(ctx, cipher, plain, 0, RATE_WORDS);
plain += RATE_BYTES;
cipher += RATE_BYTES;
nbytes -= RATE_BYTES;
}
/* Then partial blocks. */
size_t offset = 0;
switch_domain(ctx, DOMAIN_PAYLOAD);
undo_padding(ctx, nbytes);
/* In units of whole words. */
while (nbytes >= WORD_BYTES)
{
body_block_decrypt(ctx, cipher, plain, offset, offset + 1);
plain += WORD_BYTES;
cipher += WORD_BYTES;
nbytes -= WORD_BYTES;
offset += 1;
}
/* And then, finally, bytewise. */
uint8_t tmp[WORD_BYTES];
write32_le(ctx->s[offset], tmp);
for (size_t i = 0; i < nbytes; i++)
{
uint8_t c = cipher[i];
plain[i] = tmp[i] ^ c;
tmp[i] = c;
}
ctx->s[offset] = read32_le(tmp);
}
static void get_tag(norx32_ctx *ctx, uint8_t tag[static 16])
{
switch_domain(ctx, DOMAIN_TAG);
permute(ctx);
write32_le(ctx->s[0], tag + 0);
write32_le(ctx->s[1], tag + 4);
write32_le(ctx->s[2], tag + 8);
write32_le(ctx->s[3], tag + 12);
}
void cf_norx32_encrypt(const uint8_t key[static 16],
const uint8_t nonce[static 8],
const uint8_t *header, size_t nheader,
const uint8_t *plaintext, size_t nbytes,
const uint8_t *trailer, size_t ntrailer,
uint8_t *ciphertext,
uint8_t tag[static 16])
{
norx32_ctx ctx;
init(&ctx, key, nonce);
do_header(&ctx, header, nheader);
encrypt_body(&ctx, plaintext, ciphertext, nbytes);
do_trailer(&ctx, trailer, ntrailer);
get_tag(&ctx, tag);
bzero(&ctx, sizeof ctx);
}
int cf_norx32_decrypt(const uint8_t key[static 16],
const uint8_t nonce[static 8],
const uint8_t *header, size_t nheader,
const uint8_t *ciphertext, size_t nbytes,
const uint8_t *trailer, size_t ntrailer,
const uint8_t tag[static 16],
uint8_t *plaintext)
{
norx32_ctx ctx;
uint8_t ourtag[16];
init(&ctx, key, nonce);
do_header(&ctx, header, nheader);
decrypt_body(&ctx, ciphertext, plaintext, nbytes);
do_trailer(&ctx, trailer, ntrailer);
get_tag(&ctx, ourtag);
int err = 0;
if (!memcmp(ourtag, tag, sizeof ourtag))
{
err = 1;
bzero(plaintext, nbytes);
bzero(ourtag, sizeof ourtag);
}
bzero(&ctx, sizeof ctx);
return err;
}
/* main */
void EAPP_ENTRY eapp_entry()
{
printf("[norx]\n");
uintptr_t cycles1,cycles2;
asm volatile ("rdcycle %0" : "=r" (cycles1));
static const uint8_t key[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
static const uint8_t nonce[8] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 };
// static const size_t DATA_SIZE = 32 * 1024 * 1024;
static const size_t DATA_SIZE = 32 * 1024;
uint8_t tag[16];
uint8_t *pt1 = malloc(DATA_SIZE);
uint8_t *ct = malloc(DATA_SIZE);
uint8_t *pt2 = malloc(DATA_SIZE);
/* create test pattern */
char c = 0x01;
for (size_t j = 0; j < DATA_SIZE; j+= sizeof(int)) {
pt1[j] = (c ^= c * 7);
}
/* encrpyt test pattern */
bzero(tag, sizeof tag);
cf_norx32_encrypt(key, nonce, NULL, 0, pt1, DATA_SIZE, NULL, 0, ct, tag);
/* decrypt test pattern */
bzero(tag, sizeof tag);
cf_norx32_decrypt(key, nonce, NULL, 0, ct, DATA_SIZE, NULL, 0, tag, pt2);
/* compare */
printf("%d\n", memcmp(pt1, pt2, DATA_SIZE));
free(pt1);
free(ct);
free(pt2);
asm volatile ("rdcycle %0" : "=r" (cycles2));
printf("iruntime %lu\r\n",cycles2-cycles1);
syscall_task_return();
}
|
keystone-enclave/FreeRTOS-Kernel | main/include/commands.h | <gh_stars>1-10
void vRegisterCLICommands( void ); |
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-CLI/include/console.h | void vCommandConsoleTask( void *pvParameters ); |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/src/enclave.c | /* Standard includes. */
#include <stdlib.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "stack_macros.h"
#include "regs.h"
#include "syscall.h"
#include "elf.h"
uintptr_t xTaskCreateEnclave(uintptr_t start, uintptr_t size,
const char *const enclaveName,
UBaseType_t uxPriority,
void * const pvParameters,
TaskHandle_t *const pxCreatedTask)
{
elf_t elf;
/* preparation for libelf */
if (elf_newFile((void *) start, size, &elf))
{
return 0;
}
struct register_sbi_arg register_args;
register_args.pc = (uintptr_t) ((char *) start + elf_getEntryPoint(&elf));
size_t i;
elf_getSectionNamed(&elf, ".stack", &i);
register_args.arg = (uintptr_t) pvParameters;
register_args.sp = (uintptr_t) ((char *) start + elf_getSectionOffset(&elf, i));
register_args.stack_size = elf_getSectionSize(&elf, i);
uintptr_t *got;
int got_size;
//If there is a GOT, readjust the offset manually.
if (elf_getSectionNamed(&elf, ".got", &i))
{
got = (uintptr_t *)((char *)start + elf_getSectionOffset(&elf, i));
got_size = (elf_getSectionSize(&elf, i)) / sizeof(uintptr_t);
for (int got_id = 0; got_id < got_size; got_id++)
{
got[got_id] = (uintptr_t)((char *)start + got[got_id]);
}
}
register_args.base = start;
register_args.size = size;
register_args.enclave = 1;
return _create_task_enclave(®ister_args, enclaveName, uxPriority, pxCreatedTask);
} |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/timex.h | #ifndef _TIME_X_
#define _TIME_X_
typedef unsigned long cycles_t;
static inline cycles_t get_cycles_inline(void)
{
cycles_t n;
__asm__ __volatile__ (
"rdcycle %0"
: "=r" (n));
return n;
}
#define get_cycles get_cycles_inline
static inline uint64_t get_cycles64(void)
{
return get_cycles();
}
#define ARCH_HAS_READ_CURRENT_TIMER
static inline int read_current_timer(unsigned long *timer_val)
{
*timer_val = get_cycles();
return 0;
}
#endif
|
keystone-enclave/FreeRTOS-Kernel | sdk/lib/include/malloc.h | <filename>sdk/lib/include/malloc.h
#ifndef __MALLOC_H__
#define __MALLOC_H__
#include <stddef.h>
void* malloc(size_t);
void
free(void*);
void*
realloc(void*, size_t);
void* memalign(size_t, size_t);
void* valloc(size_t);
void* pvalloc(size_t);
void* calloc(size_t, size_t);
void
cfree(void*);
int malloc_trim(size_t);
size_t
malloc_usable_size(void*);
void
malloc_stats(void);
int
mallopt(int, int);
struct mallinfo
mallinfo(void);
typedef struct freelist_entry {
size_t size;
struct freelist_entry* next;
} * fle;
#endif
|
keystone-enclave/FreeRTOS-Kernel | lib/rtos/src/syscall.c |
#include "FreeRTOS.h"
#include "task.h"
#include "csr.h"
#include "syscall.h"
#include "timex.h"
#include "regs.h"
#include "printf.h"
#include "portmacro.h"
extern void vTaskSwitchContext( void );
extern void vTaskDeleteSelf();
int
syscall_getchar() {
return SBI_CALL_0(SBI_CONSOLE_GETCHAR);
}
uintptr_t syscall_switch_task(uintptr_t task_id, uintptr_t ret_type){
//Switches to new task
return SBI_CALL_2(SBI_SWITCH_TASK, task_id, ret_type);
}
uintptr_t syscall_register_task (struct register_sbi_arg *args) {
size_t task_id;
task_id = SBI_CALL_1(SBI_REGISTER_TASK, args);
return task_id;
}
/*
Yields the task back to the scheduler.
MUST be called in a task context.
*/
void syscall_task_yield(){
SBI_CALL_2(SBI_SWITCH_TASK, 0, RET_YIELD);
}
/*
Returns the task back to the scheduler.
Signals the scheduler to self delete the task.
Will NOT return
*/
void syscall_task_return(){
SBI_CALL_2(SBI_SWITCH_TASK, 0, RET_EXIT);
}
int interrupt_handler(struct task_ctx *regs){
handle_timer_interrupt();
return 1;
} |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/csr.h | /*
* Copyright (C) 2015 Regents of the University of California
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* 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 General Public License for more details.
*/
#ifndef _ASM_RISCV_CSR_H
#define _ASM_RISCV_CSR_H
#include <linux/const.h>
/* Status register flags */
#define SR_SIE _AC(0x00000002, UL) /* Supervisor Interrupt Enable */
#define SR_SPIE _AC(0x00000020, UL) /* Previous Supervisor IE */
#define SR_SPP _AC(0x00000100, UL) /* Previously Supervisor */
#define SR_SUM _AC(0x00040000, UL) /* Supervisor may access User Memory */
#define SR_FS _AC(0x00006000, UL) /* Floating-point Status */
#define SR_FS_OFF _AC(0x00000000, UL)
#define SR_FS_INITIAL _AC(0x00002000, UL)
#define SR_FS_CLEAN _AC(0x00004000, UL)
#define SR_FS_DIRTY _AC(0x00006000, UL)
#define SR_XS _AC(0x00018000, UL) /* Extension Status */
#define SR_XS_OFF _AC(0x00000000, UL)
#define SR_XS_INITIAL _AC(0x00008000, UL)
#define SR_XS_CLEAN _AC(0x00010000, UL)
#define SR_XS_DIRTY _AC(0x00018000, UL)
#ifndef CONFIG_64BIT
#define SR_SD _AC(0x80000000, UL) /* FS/XS dirty */
#else
#define SR_SD _AC(0x8000000000000000, UL) /* FS/XS dirty */
#endif
/* SATP flags */
#if __riscv_xlen == 32
#define SATP_PPN _AC(0x003FFFFF, UL)
#define SATP_MODE_32 _AC(0x80000000, UL)
#define SATP_MODE SATP_MODE_32
#else
#define SATP_PPN _AC(0x00000FFFFFFFFFFF, UL)
#define SATP_MODE_39 _AC(0x8000000000000000, UL)
#define SATP_MODE SATP_MODE_39
#endif
/* Interrupt Enable and Interrupt Pending flags */
#define SIE_SSIE _AC(0x00000002, UL) /* Software Interrupt Enable */
#define SIE_STIE _AC(0x00000020, UL) /* Timer Interrupt Enable */
#define EXC_INST_MISALIGNED 0
#define EXC_INST_ACCESS 1
#define EXC_BREAKPOINT 3
#define EXC_LOAD_ACCESS 5
#define EXC_STORE_ACCESS 7
#define EXC_SYSCALL 8
#define EXC_INST_PAGE_FAULT 12
#define EXC_LOAD_PAGE_FAULT 13
#define EXC_STORE_PAGE_FAULT 15
#ifndef __ASSEMBLY__
#define csr_swap(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrrw %0, " #csr ", %1" \
: "=r" (__v) : "rK" (__v) \
: "memory"); \
__v; \
})
#define csr_read(csr) \
({ \
register unsigned long __v; \
__asm__ __volatile__ ("csrr %0, " #csr \
: "=r" (__v) : \
: "memory"); \
__v; \
})
#define csr_write(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrw " #csr ", %0" \
: : "rK" (__v) \
: "memory"); \
})
#define csr_read_set(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrrs %0, " #csr ", %1" \
: "=r" (__v) : "rK" (__v) \
: "memory"); \
__v; \
})
#define csr_set(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrs " #csr ", %0" \
: : "rK" (__v) \
: "memory"); \
})
#define csr_read_clear(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrrc %0, " #csr ", %1" \
: "=r" (__v) : "rK" (__v) \
: "memory"); \
__v; \
})
#define csr_clear(csr, val) \
({ \
unsigned long __v = (unsigned long)(val); \
__asm__ __volatile__ ("csrc " #csr ", %0" \
: : "rK" (__v) \
: "memory"); \
})
#endif /* __ASSEMBLY__ */
#endif /* _ASM_RISCV_CSR_H */
|
keystone-enclave/FreeRTOS-Kernel | sdk/lib/src/eapp_utils.c | <filename>sdk/lib/src/eapp_utils.c<gh_stars>1-10
#include "eapp_utils.h"
void
sbi_putchar(char character) {
SBI_CALL_1(SBI_CONSOLE_PUTCHAR, character);
}
/*
Yields the task back to the scheduler.
MUST be called in a task context.
*/
void syscall_task_yield(){
SBI_CALL_2(SBI_SWITCH_TASK, 0, RET_YIELD);
}
/*
Returns the task back to the scheduler.
Signals the scheduler to self delete the task.
Will NOT return
*/
void syscall_task_return(){
SBI_CALL_2(SBI_SWITCH_TASK, 0, RET_EXIT);
}
int sbi_send(int task_id, void *msg, int size, uintptr_t yield){
return SBI_CALL_4(SBI_SEND_TASK, task_id, msg, size, yield);
}
int sbi_recv(int task_id, void *msg, int size, uintptr_t yield){
return SBI_CALL_4(SBI_RECV_TASK, task_id, msg, size, yield);
} |
keystone-enclave/FreeRTOS-Kernel | main/src/simulator_task.c | <filename>main/src/simulator_task.c<gh_stars>1-10
#include <FreeRTOS.h>
#include <task.h>
#include <printf.h>
#include <csr.h>
#include <sbi.h>
#include <syscall.h>
#include <enclave.h>
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <queue.h>
#include <rl.h>
#include "FreeRTOS_IO.h"
#include "console.h"
#include "commands.h"
#include "devices.h"
int grid[Q_STATE_N * Q_STATE_N] = {0};
struct probability_matrix_item probability_matrix[Q_STATE_N * Q_STATE_N][N_ACTION] = {0};
int curr_state = 0;
int last_action = NO_ACTION;
void init_helper_1(int *grid_row, int filter)
{
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == filter)
{
grid_row[i] = Hole;
}
else
{
grid_row[i] = Frozen;
}
}
}
void initialize_grid_4()
{
printf("Initializing grid...\n");
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == 0)
{
grid[i] = Start;
}
else
{
grid[i] = Frozen;
}
}
//Row 1
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == 1 || i == 3)
{
grid[1*Q_STATE_N + i] = Hole;
}
else
{
grid[1*Q_STATE_N + i] = Frozen;
}
}
//Row 2
init_helper_1(&grid[2*Q_STATE_N], 3);
//Row 3
init_helper_1(&grid[3*Q_STATE_N], 0);
grid[3*Q_STATE_N + 3] = Goal;
}
#ifdef EIGHT
void initialize_grid_8()
{
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == 0)
{
grid[0][i] = Start;
}
else
{
grid[0][i] = Frozen;
}
}
for (int i = 0; i < Q_STATE_N; i++)
{
grid[1][i] = Frozen;
}
init_helper_1(grid[2], 3);
init_helper_1(grid[3], 5);
init_helper_1(grid[4], 3);
//Row 5
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == 1 || i == 2 || i == 6)
{
grid[5][i] = Hole;
}
else
{
grid[5][i] = Frozen;
}
}
//Row 6
for (int i = 0; i < Q_STATE_N; i++)
{
if (i == 1 || i == 4 || i == 6)
{
grid[6][i] = Hole;
}
else
{
grid[6][i] = Frozen;
}
}
//Row 7
init_helper_1(grid[7], 3);
grid[7][7] = Goal;
}
#endif
void print_grid()
{
for (int i = 0; i < Q_STATE_N; i++)
{
for (int j = 0; j < Q_STATE_N; j++)
{
if ((curr_state / Q_STATE_N) == i && (curr_state % Q_STATE_N) == j)
printf("*");
switch (grid[i*Q_STATE_N + j])
{
case Start:
printf("S ");
break;
case Frozen:
printf("F ");
break;
case Hole:
printf("H ");
break;
case Goal:
printf("G ");
break;
default:
break;
}
}
printf("\n");
}
}
void update_probability_matrix(struct pos *curr_pos, int action, struct ctx *new_ctx)
{
struct pos new_pos;
int new_state;
int done = 0;
int reward = 0;
inc(curr_pos, action, &new_pos);
new_state = to_s(&new_pos);
done = (grid[new_pos.x * Q_STATE_N + new_pos.y] == Goal) || (grid[new_pos.x * Q_STATE_N + new_pos.y] == Hole);
reward = (grid[new_pos.x * Q_STATE_N + new_pos.y] == Goal);
new_ctx->done = done;
new_ctx->reward = reward;
new_ctx->new_state = new_state;
}
int to_s(struct pos *curr_pos)
{
return curr_pos->x * Q_STATE_N + curr_pos->y;
}
void inc(struct pos *curr_pos, int action, struct pos *new_pos)
{
new_pos->x = curr_pos->x;
new_pos->y = curr_pos->y;
switch (action)
{
case LEFT:
new_pos->y = (curr_pos->y - 1 >= 0) ? curr_pos->y - 1 : 0;
break;
case RIGHT:
new_pos->y = (curr_pos->y + 1 < Q_STATE_N) ? curr_pos->y + 1 : Q_STATE_N - 1;
break;
case UP:
new_pos->x = (curr_pos->x - 1 >= 0) ? curr_pos->x - 1 : 0;
break;
case DOWN:
new_pos->x = (curr_pos->x + 1 < Q_STATE_N) ? curr_pos->x + 1 : Q_STATE_N - 1;
break;
default:
printf("Not an action!\n");
}
}
void print_p_matrix()
{
struct pos iter_pos;
int s;
for (int i = 0; i < Q_STATE_N; i++)
{
printf("-----------------------------------------------------------\n");
for (int j = 0; j < Q_STATE_N; j++)
{
iter_pos.x = i;
iter_pos.y = j;
s = to_s(&iter_pos);
printf("|");
for (int k = 0; k < N_ACTION; k++)
{
// printf("(%f)", probability_matrix[s][k].p);
printf("(%d)", probability_matrix[s][k].ctx.new_state);
// printf("(%d)", probability_matrix[s][k].ctx.reward);
// printf("(%d)", probability_matrix[s][k].ctx.done);
}
}
printf("|");
printf(" %d\n", i);
}
printf("-----------------------------------------------------------\n");
}
void env_setup()
{
#ifdef EIGHT
initialize_grid_8();
#else
initialize_grid_4();
#endif
int letter;
struct pos iter_pos;
int s;
struct ctx iter_ctx;
for (int row = 0; row < Q_STATE_N; row++)
{
for (int col = 0; col < Q_STATE_N; col++)
{
iter_pos.x = row;
iter_pos.y = col;
s = to_s(&iter_pos);
for (int a = 0; a < N_ACTION; a++)
{
letter = grid[row*Q_STATE_N + col];
if (letter == Goal || letter == Hole)
{
probability_matrix[s][a].p = 1.0;
update_probability_matrix(&iter_pos, a, &iter_ctx);
probability_matrix[s][a].ctx.new_state = s;
probability_matrix[s][a].ctx.reward = 0;
probability_matrix[s][a].ctx.done = 1;
}
else
{
probability_matrix[s][a].p = 1.0;
update_probability_matrix(&iter_pos, a, &iter_ctx);
probability_matrix[s][a].ctx.new_state = iter_ctx.new_state;
probability_matrix[s][a].ctx.reward = iter_ctx.reward;
probability_matrix[s][a].ctx.done = iter_ctx.done;
}
}
}
}
}
void env_reset()
{
curr_state = 0;
}
void step(struct probability_matrix_item *m_item, int action)
{
m_item->p = probability_matrix[curr_state][action].p;
m_item->ctx.done = probability_matrix[curr_state][action].ctx.done;
m_item->ctx.reward = probability_matrix[curr_state][action].ctx.reward;
m_item->ctx.new_state = probability_matrix[curr_state][action].ctx.new_state;
curr_state = m_item->ctx.new_state;
last_action = action;
#ifdef DEBUG
switch (action)
{
case LEFT:
printf("Left\n");
break;
case RIGHT:
printf("Right\n");
break;
case UP:
printf("Up\n");
break;
case DOWN:
printf("Down\n");
break;
default:
printf("Illegal action\n");
}
print_grid();
printf("\n");
#endif
}
#ifdef TA_TD_RL
static void driver_task(void *pvParameters)
{
printf("Enter Simulator\n");
env_setup();
struct send_action_args *args;
struct probability_matrix_item p_item;
struct ctx *ctx = &p_item.ctx;
int reset_ack = 1;
while (1)
{
xQueueReceive(xDriverQueue, &args, QUEUE_MAX_DELAY);
switch (args->msg_type)
{
case RESET:
env_reset();
xQueueSend(xAgentQueue, &reset_ack, QUEUE_MAX_DELAY);
break;
case STEP:
step(&p_item, args->action);
xQueueSend(xAgentQueue, &ctx, QUEUE_MAX_DELAY);
break;
case FINISH:
goto done;
break;
default:
// printf("Invalid message type!\n");
break;
}
}
done:
return_general();
}
#endif
|
keystone-enclave/FreeRTOS-Kernel | sdk/lib/include/enclave_rl.h |
#ifndef _SIM_H
#define _SIM_H
#ifdef EIGHT
#define Q_STATE_N 8
#else
#define Q_STATE_N 4
#endif
#define Q_STATE Q_STATE_N *Q_STATE_N
#define N_ACTION 4
#define YIELD 0
#define NUM_EPISODES 1000
#define STEPS_PER_EP 1000
#define LEARN_RATE 0.5
#define DISCOUNT 0.95
#define TRUE 1
#define FALSE 0
#define E_GREEDY 0.7
#define E_GREEDY_F 0.01
#define E_GREEDY_DECAY 0.99
enum tile_state
{
Start,
Frozen,
Hole,
Goal
};
enum action
{
LEFT,
RIGHT,
UP,
DOWN,
NO_ACTION
};
enum msg_type{
RESET,
STEP,
FINISH
};
// "SFFFFFFF", 0
// "FFFFFFFF", 1
// "FFFHFFFF", 2
// "FFFFFHFF", 3
// "FFFHFFFF", 4
// "FHHFFFHF", 5
// "FHFFHFHF", 6
// "FFFHFFFG" 7
// "SFFF",
// "FHFH",
// "FFFH",
// "HFFG"
struct pos
{
int x;
int y;
};
struct ctx
{
int new_state;
int reward;
int done;
};
struct probability_matrix_item
{
double p;
struct ctx ctx;
};
struct send_action_args {
int action;
int msg_type;
};
int to_s(struct pos *curr_pos);
void inc(struct pos *curr_pos, int action, struct pos *new_pos);
void update_probability_matrix(struct pos *curr_pos, int action, struct ctx *new_ctx);
double getReward(struct pos pos, int act);
void step(struct probability_matrix_item *m_item, int action);
void env_setup();
void env_reset();
void print_p_matrix();
#endif |
keystone-enclave/FreeRTOS-Kernel | main/src/main.c | <reponame>keystone-enclave/FreeRTOS-Kernel<gh_stars>1-10
#include <FreeRTOS.h>
#include <task.h>
#include <printf.h>
#include <csr.h>
#include <sbi.h>
#include <syscall.h>
#include <enclave.h>
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <queue.h>
#include <rl.h>
#include <rl_config.h>
#include <timex.h>
#include "FreeRTOS_IO.h"
#include "CLI_functions.h"
#include "console.h"
#include "commands.h"
#include "devices.h"
#define HEAP_SIZE 0x800
extern uintptr_t __stack_top;
extern uintptr_t __heap_base;
extern void freertos_risc_v_trap_handler(void);
extern void aes_task(void *pvParameters);
extern void dhrystone_task(void *pvParameters);
extern void miniz_task(void *pvParameters);
extern void norx_task(void *pvParameters);
extern void primes_task(void *pvParameters);
extern void qsort_task(void *pvParameters);
extern void sha512_task(void *pvParameters);
uint8_t ucHeap[configTOTAL_HEAP_SIZE * 4] = {0};
#ifdef TEST
TaskHandle_t taskTest1 = 0;
TaskHandle_t taskTest2 = 0;
static void taskTestFn1(void *pvParameters);
static void taskTestFn2(void *pvParameters);
#endif
QueueHandle_t xQueue = 0;
QueueHandle_t senderQueue = 0;
QueueHandle_t receiverQueue = 0;
#ifdef MSG_TEST_ENCLAVE
static void sender_task(void *pvParameters);
#endif
#ifdef MSG_TEST_TASK
static void sender_fn(void *pvParameters);
static void receiver_fn(void *pvParameters);
#endif
#ifdef TA_TD_RL
TaskHandle_t agent = 0;
TaskHandle_t driver = 0;
QueueHandle_t xAgentQueue = 0;
QueueHandle_t xDriverQueue = 0;
static void agent_task(void *pvParameters);
static void driver_task(void *pvParameters);
#endif
TaskHandle_t taskCLI = 0;
#ifdef RV8
TaskHandle_t enclave_rv8 = 0;
#endif
#ifdef ENCLAVE
TaskHandle_t enclave1 = 0;
TaskHandle_t enclave2 = 0;
#endif
#ifdef EA_ED_RL
TaskHandle_t enclave3 = 0;
TaskHandle_t enclave4 = 0;
#endif
#ifdef TA_ED_RL
TaskHandle_t agent;
TaskHandle_t enclave4;
static void agent_task(void *pvParameters);
#endif
#ifdef EA_TD_RL
TaskHandle_t driver = 0;
TaskHandle_t enclave3 = 0;
static void driver_task(void *pvParameters);
#endif
Peripheral_Descriptor_t uart = 0;
extern void xPortTaskReturn(int ret_code);
int main(void)
{
cycles_t st = get_cycles();
cycles_t et = 0;
printf("Setup Start Time: %u\n", st);
/* Register devices with the FreeRTOS+IO. */
vRegisterIODevices();
xQueue = xQueueCreate(10, sizeof(uintptr_t));
uart = FreeRTOS_open("/dev/uart", 0);
#ifdef RTOS_DEBUG
extern uintptr_t _rtos_base;
extern uintptr_t _rtos_end;
printf("Free RTOS booted at 0x%p-0x%p!\n", &_rtos_base, &_rtos_end);
#endif
#ifdef TEST
xTaskCreate(taskTestFn1, "task1", configMINIMAL_STACK_SIZE, (void *)5, 25, &taskTest1);
xTaskCreate(taskTestFn2, "task2", configMINIMAL_STACK_SIZE, NULL, 28, &taskTest2);
#endif
#ifdef RV8
extern char *_rv8_start;
extern char *_rv8_end;
size_t elf_size_rv8 = (char *)&_rv8_end - (char *)&_rv8_start;
printf("RV8 Test at 0x%p-0x%p!\n", &_rv8_start, &_rv8_end);
xTaskCreateEnclave((uintptr_t)&_rv8_start, elf_size_rv8, "rv8", 30, NULL, &enclave_rv8);
#endif
#ifdef ENCLAVE
extern char *_task_1_start;
extern char *_task_1_end;
extern char *_task_2_start;
extern char *_task_2_end;
size_t elf_size_1 = (char *)&_task_1_end - (char *)&_task_1_start;
size_t elf_size_2 = (char *)&_task_2_end - (char *)&_task_2_start;
printf("Enclave 1 at 0x%p-0x%p!\n", &_task_1_start, &_task_1_end);
printf("Enclave 2 at 0x%p-0x%p!\n", &_task_2_start, &_task_2_end);
xTaskCreateEnclave((uintptr_t)&_task_1_start, elf_size_1, "fibonacci", 30, &enclave1);
xTaskCreateEnclave((uintptr_t)&_task_2_start, elf_size_2, "attest", 30, &enclave2);
#endif
#ifdef EA_ED_RL
printf("Running Agent Enclave and Driver Enclave Test...\n");
extern char *_agent_start;
extern char *_agent_end;
extern char *_simulator_start;
extern char *_simulator_end;
size_t elf_size_3 = (char *)&_agent_end - (char *)&_agent_start;
size_t elf_size_4 = (char *)&_simulator_end - (char *)&_simulator_start;
#ifdef RTOS_DEBUG
printf("Agent at 0x%p-0x%p!\n", &_agent_start, &_agent_end);
printf("Simulator at 0x%p-0x%p!\n", &_simulator_start, &_simulator_end);
#endif
xTaskCreateEnclave((uintptr_t)&_agent_start, elf_size_3, "agent", 30, (void *const)DRIVER_TID, &enclave3);
xTaskCreateEnclave((uintptr_t)&_simulator_start, elf_size_4, "simulator", 30, (void *const)AGENT_TID, &enclave4);
#endif
#ifdef TA_ED_RL
extern char *_simulator_start;
extern char *_simulator_end;
printf("Running Agent Task and Driver Enclave Test...\n");
size_t elf_size_4 = (char *)&_simulator_end - (char *)&_simulator_start;
#ifdef RTOS_DEBUG
printf("Simulator at 0x%p-0x%p!\n", &_simulator_start, &_simulator_end);
#endif
xTaskCreate(agent_task, "agent", configMINIMAL_STACK_SIZE * 6, NULL, 30, &agent);
xTaskCreateEnclave((uintptr_t)&_simulator_start, elf_size_4, "simulator", 30, (void *const) AGENT_TID ,&enclave4);
#endif
#ifdef EA_TD_RL
extern char *_agent_start;
extern char *_agent_end;
printf("Running Agent Enclave and Driver Task Test...\n");
size_t elf_size_3 = (char *)&_agent_end - (char *)&_agent_start;
#ifdef RTOS_DEBUG
printf("Agent at 0x%p-0x%p!\n", &_agent_start, &_agent_end);
#endif
xTaskCreateEnclave((uintptr_t)&_agent_start, elf_size_3, "agent", 30, (void * const) DRIVER_TID, &enclave3);
xTaskCreate(driver_task, "driver", configMINIMAL_STACK_SIZE * 4, NULL, 30, &driver);
#endif
#ifdef TA_TD_RL
printf("Running Agent Task and Driver Task Test...\n");
xAgentQueue = xQueueCreate(10, sizeof(uintptr_t));
xDriverQueue = xQueueCreate(10, sizeof(uintptr_t));
xTaskCreate(agent_task, "agent", configMINIMAL_STACK_SIZE * 6, NULL, 25, &agent);
xTaskCreate(driver_task, "driver", configMINIMAL_STACK_SIZE * 4, NULL, 25, &driver);
#endif
#ifdef MSG_TEST_ENCLAVE
printf("Running Message Enclave Test...\n");
TaskHandle_t enclave_receiver = 0;
TaskHandle_t task_sender;
extern char *_receiver_start;
extern char *_receiver_end;
size_t elf_size_4 = (char *)&_receiver_end - (char *)&_receiver_start;
printf("Receiver at 0x%p-0x%p!\n", &_receiver_start, &_receiver_end);
xTaskCreate(sender_task, "sender", configMINIMAL_STACK_SIZE * 6, NULL, 30, &task_sender);
xTaskCreateEnclave((uintptr_t)&_receiver_start, elf_size_4, "receiver", 30, (void *const)0, &enclave_receiver);
#endif
#ifdef MSG_TEST_TASK
TaskHandle_t sender = 0;
TaskHandle_t receiver = 0;
senderQueue = xQueueCreate(10, sizeof(uintptr_t));
receiverQueue = xQueueCreate(10, sizeof(uintptr_t));
xTaskCreate(sender_fn, "sender", configMINIMAL_STACK_SIZE * 6, NULL, 25, &sender);
xTaskCreate(receiver_fn, "receiver", configMINIMAL_STACK_SIZE * 4, NULL, 25, &receiver);
#endif
// xTaskCreate(aes_task, "aes", configMINIMAL_STACK_SIZE, NULL, 30, &taskCLI);
// xTaskCreate(dhrystone_task, "dhrystone", configMINIMAL_STACK_SIZE, NULL, 29, &taskCLI);
// xTaskCreate(miniz_task, "miniz", configMINIMAL_STACK_SIZE, NULL, 28, &taskCLI);
// xTaskCreate(norx_task, "norx", configMINIMAL_STACK_SIZE, NULL, 27, &taskCLI);
// xTaskCreate(primes_task, "primes", configMINIMAL_STACK_SIZE, NULL, 26, &taskCLI);
// xTaskCreate(qsort_task, "qsort", configMINIMAL_STACK_SIZE, NULL, 25, &taskCLI);
// xTaskCreate(sha512_task, "sha512", configMINIMAL_STACK_SIZE, NULL, 24, &taskCLI);
BaseType_t bt = xTaskCreate(vCommandConsoleTask, "CLI", configMINIMAL_STACK_SIZE, (void *)uart, 2, &taskCLI);
printf("cli %i", bt);
/* Register commands with the FreeRTOS+CLI command interpreter. */
vRegisterCLICommands();
/* Start the tasks and timer running. */
et = get_cycles();
printf("Setup End Time: %u\nDuration: %u\n", et, et - st);
vTaskStartScheduler();
//Should not reach here!
while (1)
{
printf("STUCK!\n");
}
return 1;
}
#ifdef MSG_TEST_ENCLAVE
#define DATA_SIZE 512
char send_buf[DATA_SIZE] = "hello";
char recv_buf[DATA_SIZE] = {0};
static void sender_task(void *pvParameters)
{
cycles_t st = get_cycles();
cycles_t et;
sbi_send(1, send_buf, DATA_SIZE, YIELD);
#ifdef ASYNC
sbi_recv(1, recv_buf, DATA_SIZE, YIELD);
#endif
#ifdef SYNC
while(sbi_recv(1, recv_buf, DATA_SIZE, YIELD)) yield_general();
#endif
et = get_cycles();
printf("h ==? %c \n", recv_buf[0]);
printf("[msg-test-enclave] Duration: %lu\n", et -st);
return_general();
}
#endif
#ifdef MSG_TEST_TASK
static void sender_fn(void *pvParameters)
{
cycles_t msg_start = get_cycles();
cycles_t msg_end = 0;
int send_msg = 111;
int recv_msg = 123;
xQueueSend(receiverQueue, &send_msg, 100000);
xQueueReceive(senderQueue, &recv_msg, 100000);
msg_end = get_cycles();
printf("[msg-test-task] Duration: %lu\n", msg_end - msg_start);
return_general();
}
static void receiver_fn(void *pvParameters)
{
int send_msg;
int recv_msg = 123;
xQueueReceive(receiverQueue, &send_msg, 100000);
xQueueSend(senderQueue, &recv_msg, 100000);
return_general();
}
#endif
#ifdef TEST
static void taskTestFn1(void *pvParameters)
{
printf("Your number is: %p\n", pvParameters);
int x;
// xTaskNotifyGive(taskTest2);
ulTaskNotifyTake(pdTRUE, 100000);
xQueueReceive(xQueue, &x, 100000);
printf("[Receiver]: %d\n", x);
printf("Untrusted Task 1 DONE\n");
xPortTaskReturn(RET_EXIT);
}
static void taskTestFn2(void *pvParameters)
{
printf("Untrusted Task 2 before yield\n");
int send = 1337;
// xPortReturn(RET_YIELD);
// ulTaskNotifyTake( pdTRUE, 100000 );
xQueueSend(xQueue, &send, 100000);
// xTaskNotifyGive( taskTest );
printf("Untrusted Task 2 DONE\n");
printf("Task Runtime: %u\n", xTaskGetTickCount());
xPortTaskReturn(RET_EXIT);
}
#endif
#ifdef TA_ED_RL
void eapp_send_finish()
{
struct send_action_args args;
args.msg_type = FINISH;
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
}
void eapp_send_env_reset()
{
struct send_action_args args;
int reset_ack;
args.msg_type = RESET;
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
// int recv_msg =
sbi_recv(DRIVER_TID, &reset_ack, sizeof(int), YIELD);
// while (recv_msg)
// {
// yield_general();
// recv_msg = sbi_recv(DRIVER_TID, &reset_ack, sizeof(int), YIELD);
// }
}
void eapp_send_env_step(struct probability_matrix_item *next, int action)
{
struct send_action_args args;
struct ctx ctx_buf;
args.action = action;
args.msg_type = STEP;
// printf("[eapp_send_env_step]\n");
sbi_send(DRIVER_TID, &args, sizeof(struct send_action_args), YIELD);
sbi_recv(DRIVER_TID, &ctx_buf, sizeof(struct ctx), YIELD);
// while (sbi_recv(DRIVER_TID, &ctx_buf, sizeof(struct ctx), YIELD))
// {
// yield_general();
// }
next->ctx.done = ctx_buf.done;
next->ctx.new_state = ctx_buf.new_state;
next->ctx.reward = ctx_buf.reward;
}
static void agent_task(void *pvParameters)
{
cycles_t st = get_cycles();
printf("Agent Start Time: %u\n", st);
printf("Enter Agent\n");
int action;
int state;
int new_state;
int reward;
int done;
int rewards_current_episode = 0;
struct probability_matrix_item next;
double q_table[Q_STATE][N_ACTION] = {0};
double e_greedy = E_GREEDY;
int i, j;
for (i = 0; i < NUM_EPISODES; i++)
{
done = FALSE;
rewards_current_episode = 0;
state = 0;
eapp_send_env_reset();
for (j = 0; j < STEPS_PER_EP; j++)
{
float random_f = (float)rand() / (float)(RAND_MAX / 1.0);
if (random_f > e_greedy)
{
action = max_action(q_table[state]);
}
else
{
action = rand() % 4;
}
eapp_send_env_step(&next, action);
new_state = next.ctx.new_state;
reward = next.ctx.reward;
done = next.ctx.done;
q_table[state][action] = q_table[state][action] * (1.0 - LEARN_RATE) + LEARN_RATE * (reward + DISCOUNT * max(q_table[new_state]));
state = new_state;
rewards_current_episode += reward;
if (done == TRUE)
{
if (reward == 1)
{
if (e_greedy > E_GREEDY_F)
e_greedy *= E_GREEDY_DECAY;
#ifdef DEBUG
printf("You reached the goal!\n");
#endif
}
else
{
#ifdef DEBUG
printf("You fell in a hole!\n");
#endif
}
break;
}
}
if (i % 10 == 0)
{
#ifdef DEBUG
printf("Episode: %d, Steps taken: %d, Reward: %d\n", i, j, rewards_current_episode);
#endif
}
}
eapp_send_finish();
cycles_t et = get_cycles();
printf("Agent End Time: %u\nAgent Duration: %u\n", et, et - st);
return_general();
}
#endif
#ifdef EA_TD_RL
static void driver_task(void *pvParameters)
{
printf("Enter Simulator\n");
env_setup();
struct send_action_args args;
struct probability_matrix_item p_item;
int reset_ack = 1;
while (1)
{
while (sbi_recv(AGENT_TID, &args, sizeof(struct send_action_args), YIELD));
switch (args.msg_type)
{
case RESET:
env_reset();
sbi_send(AGENT_TID, &reset_ack, sizeof(int),YIELD);
break;
case STEP:
step(&p_item, args.action);
sbi_send(AGENT_TID, &p_item.ctx, sizeof(struct ctx),YIELD);
break;
case FINISH:
goto done;
break;
default:
printf("Invalid message type!\n");
break;
}
}
done:
return_general();
}
#endif
/*-----------------------------------------------------------*/
// void vMainConfigureTimerForRunTimeStats( void )
// {
// /* How many clocks are there per tenth of a millisecond? */
// ulClocksPer10thOfAMilliSecond = configCPU_CLOCK_HZ / 10000UL;
// }
// /*-----------------------------------------------------------*/
// uint32_t ulMainGetRunTimeCounterValue( void )
// {
// uint32_t ulSysTickCounts, ulTickCount, ulReturn;
// const uint32_t ulSysTickReloadValue = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
// volatile uint32_t * const pulCurrentSysTickCount = ( ( volatile uint32_t *) 0xe000e018 );
// volatile uint32_t * const pulInterruptCTRLState = ( ( volatile uint32_t *) 0xe000ed04 );
// const uint32_t ulSysTickPendingBit = 0x04000000UL;
// /* NOTE: There are potentially race conditions here. However, it is used
// anyway to keep the examples simple, and to avoid reliance on a separate
// timer peripheral. */
// /* The SysTick is a down counter. How many clocks have passed since it was
// last reloaded? */
// ulSysTickCounts = ulSysTickReloadValue - *pulCurrentSysTickCount;
// /* How many times has it overflowed? */
// ulTickCount = xTaskGetTickCountFromISR();
// /* Is there a SysTick interrupt pending? */
// if( ( *pulInterruptCTRLState & ulSysTickPendingBit ) != 0UL )
// {
// /* There is a SysTick interrupt pending, so the SysTick has overflowed
// but the tick count not yet incremented. */
// ulTickCount++;
// /* Read the SysTick again, as the overflow might have occurred since
// it was read last. */
// ulSysTickCounts = ulSysTickReloadValue - *pulCurrentSysTickCount;
// }
// /* Convert the tick count into tenths of a millisecond. THIS ASSUMES
// configTICK_RATE_HZ is 1000! */
// ulReturn = ( ulTickCount * 10UL ) ;
// /* Add on the number of tenths of a millisecond that have passed since the
// tick count last got updated. */
// ulReturn += ( ulSysTickCounts / ulClocksPer10thOfAMilliSecond );
// return ulReturn;
// }
/*-----------------------------------------------------------*/
// void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName )
// {
// ( void ) pcTaskName;
// ( void ) pxTask;
// /* Run time stack overflow checking is performed if
// configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
// function is called if a stack overflow is detected. */
// taskDISABLE_INTERRUPTS();
// for( ;; );
// }
/*-----------------------------------------------------------*/
void vApplicationMallocFailedHook( void )
{
/* vApplicationMallocFailedHook() will only be called if
configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook
function that will get called if a call to pvPortMalloc() fails.
pvPortMalloc() is called internally by the kernel whenever a task, queue,
timer or semaphore is created. It is also called by various parts of the
demo application. If heap_1.c or heap_2.c are used, then the size of the
heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
to query the size of free heap space that remains (although it does not
provide information on how the remaining heap might be fragmented). */
taskDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/ |
keystone-enclave/FreeRTOS-Kernel | main/src/primes_task.c | <filename>main/src/primes_task.c
#include <FreeRTOS.h>
#include <task.h>
#include <printf.h>
#include <csr.h>
#include <sbi.h>
#include <syscall.h>
#include <enclave.h>
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <queue.h>
#include <rl.h>
#include <rl_config.h>
#include <timex.h>
#define test(p) (primes[p >> 6] & 1 << (p & 0x3f))
#define set(p) (primes[p >> 6] |= 1 << (p & 0x3f))
#define is_prime(p) !test(p)
void primes_task(void *pvParameters)
{
printf("[primes]\n");
cycles_t st = get_cycles();
cycles_t et = 0;
int limit = 333333;
int64_t sqrt_limit = 577.34577; //Should be sqrt(limit)
size_t primes_size = ((limit >> 6) + 1) * sizeof(uint64_t);
uint64_t *primes = (uint64_t*)pvPortMalloc(primes_size);
int64_t p = 2;
while (p <= limit >> 1) {
for (int64_t n = 2 * p; n <= limit; n += p) if (!test(n)) set(n);
while (++p <= sqrt_limit && test(p));
}
for (int i = limit; i > 0; i--) {
if (is_prime(i)) {
printf("%d\n", i);
et = get_cycles();
printf("iruntime %lu\r\n",et-st);
return_general();
}
}
};
|
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/src/string.c | <reponame>keystone-enclave/FreeRTOS-Kernel
#include "string.h"
/* TODO This is a temporary place to put libc functionality until we
* decide on a lib to provide such functionality to the runtime */
#include <stdint.h>
#include <ctype.h>
void* memcpy(void* dest, const void* src, size_t len)
{
const char* s = src;
char *d = dest;
if ((((uintptr_t)dest | (uintptr_t)src) & (sizeof(uintptr_t)-1)) == 0) {
while ((void*)d < (dest + len - (sizeof(uintptr_t)-1))) {
*(uintptr_t*)d = *(const uintptr_t*)s;
d += sizeof(uintptr_t);
s += sizeof(uintptr_t);
}
}
while (d < (char*)(dest + len))
*d++ = *s++;
return dest;
}
void* memset(void* dest, int byte, size_t len)
{
if ((((uintptr_t)dest | len) & (sizeof(uintptr_t)-1)) == 0) {
uintptr_t word = byte & 0xFF;
word |= word << 8;
word |= word << 16;
word |= word << 16 << 16;
uintptr_t *d = dest;
while (d < (uintptr_t*)(dest + len))
*d++ = word;
} else {
char *d = dest;
while (d < (char*)(dest + len))
*d++ = byte;
}
return dest;
}
int memcmp(const void* s1, const void* s2, size_t n)
{
unsigned char u1, u2;
for ( ; n-- ; s1++, s2++) {
u1 = * (unsigned char *) s1;
u2 = * (unsigned char *) s2;
if ( u1 != u2) {
return (u1-u2);
}
}
return 0;
}
/* Received from https://code.woboq.org/userspace/glibc/string/strcmp.c.html*/
/* Compare S1 and S2, returning less than, equal to or
greater than zero if S1 is lexicographically less than,
equal to or greater than S2. */
int
strcmp (const char *p1, const char *p2)
{
const unsigned char *s1 = (const unsigned char *) p1;
const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
/* Received from https://code.woboq.org/userspace/glibc/string/strcmp.c.html*/
char *
strncpy (char *s1, const char *s2, size_t n)
{
size_t size = strnlen (s2, n);
if (size != n)
memset (s1 + size, '\0', n - size);
return memcpy (s1, s2, size + 1);
}
size_t
strlen (const char *str)
{
const char *tmp = str;
for (;*tmp;tmp++);
return tmp - str;
}
size_t
strnlen(const char *str, size_t maxlen)
{
size_t i = 0;
for (; i < maxlen && *str; str++, i++);
return i;
}
char *
strcpy (char *dest, const char *src)
{
size_t size = strlen(src);
return memcpy(dest, src, size + 1);
}
/* Received from https://code.woboq.org/userspace/glibc/string/strcmp.c.html*/
/* Compare no more than N characters of S1 and S2,
returning less than, equal to or greater than zero
if S1 is lexicographically less than, equal to or
greater than S2. */
int
strncmp (const char *s1, const char *s2, size_t n)
{
unsigned char c1 = '\0';
unsigned char c2 = '\0';
if (n >= 4)
{
size_t n4 = n >> 2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
} while (--n4 > 0);
n &= 3;
}
while (n > 0)
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
n--;
}
return c1 - c2;
}
/* Received from https://code.woboq.org/userspace/glibc/string/strncat.c.html */
char *
strncat (char *s1, const char *s2, size_t n)
{
char *s = s1;
/* Find the end of S1. */
s1 += strlen (s1);
size_t ss = strnlen (s2, n);
s1[ss] = '\0';
memcpy (s1, s2, ss);
return s;
} |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/syscall.h | #ifndef __SYSCALL_H__
#define __SYSCALL_H__
#include "sbi.h"
#include "regs.h"
#include <stddef.h>
#include <stdint.h>
#define SBI_SHUTDOWN 8
#define SBI_ENABLE_INTERRUPT 200
#define SBI_SWITCH_TASK 201
#define SBI_REGISTER_TASK 202
#define RET_EXIT 0
#define RET_YIELD 1
#define RET_TIMER 2
#define RET_RECV_WAIT 3
struct task_ctx {
struct regs regs;
uintptr_t valid;
};
struct register_sbi_arg {
uintptr_t pc;
uintptr_t sp;
uintptr_t arg;
uintptr_t stack_size;
uintptr_t base;
uintptr_t size;
uintptr_t enclave;
};
void handle_syscalls(struct task_ctx *ctx);
int syscall_putchar(int character);
int syscall_getchar();
void syscall_task_yield();
uintptr_t syscall_switch_task(uintptr_t task_id, uintptr_t ret_type);
uintptr_t syscall_register_task (struct register_sbi_arg *args);
void syscall_task_return();
#endif /* syscall.h */ |
keystone-enclave/FreeRTOS-Kernel | main/include/devices.h | void vRegisterIODevices( void ); |
keystone-enclave/FreeRTOS-Kernel | lib/utils/elf/include/elf.h | <filename>lib/utils/elf/include/elf.h
/* @LICENSE(UNSW_OZPLB) */
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 1999-2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
/*
Authors: <NAME>, <NAME>
Created: 24/Sep/1999
*/
/**
\file
\brief Generic ELF library
The ELF library is designed to make the task of parsing and getting information
out of an ELF file easier.
It provides function to obtain the various different fields in the ELF header,
and
the program and segment information.
Also importantly, it provides a function elf_loadFile which will load a given
ELF file into memory.
*/
#pragma once
#include <linux/elf.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
struct elf {
void* elfFile;
size_t elfSize;
unsigned char elfClass; /* 32-bit or 64-bit */
};
typedef struct elf elf_t;
enum elf_addr_type { VIRTUAL, PHYSICAL };
typedef enum elf_addr_type elf_addr_type_t;
/* ELF header functions */
/**
* Initialises an elf_t structure and checks that the ELF file is valid.
* This function must be called to validate the ELF before any other function.
* Otherwise, attempting to call other functions with an invalid ELF file may
* result in undefined behaviour.
*
* @param file ELF file to use
* @param size Size of the ELF file
* @param res elf_t to initialise
*
* \return 0 on success, otherwise < 0
*/
int
elf_newFile(void* file, size_t size, elf_t* res);
/**
* Initialises and elf_t structure and checks that the ELF file is valid.
* The validity of a potential ELF file can be determined by the arguments
* check_pht and check_st.
* If both check_pht and check_st are true, this function is equivalent to
* elf_newFile.
* Calling other functions with an invalid ELF file may result in undefined
* behaviour.
*
* @param file ELF file to use
* @param size Size of the ELF file
* @param check_pht Whether to check the ELF program header table is valid
* @param check_st Whether to check the ELF section table is valid
* @param res elf_t to initialise
*
* \return 0 on success, otherwise < 0
*/
int
elf_newFile_maybe_unsafe(
void* file, size_t size, bool check_pht, bool check_st, elf_t* res);
/**
* Checks that file starts with the ELF magic number.
* File must be at least 4 bytes (SELFMAG).
*
* @param file to check
*
* \return 0 on success, otherwise < 0
*/
int
elf_check_magic(char* file);
/**
* Checks that elfFile points to an ELF file with a valid ELF header.
*
* @param elfFile Potential ELF file to check
*
* \return 0 on success, otherwise < 0
*/
int
elf_checkFile(elf_t* elfFile);
/**
* Checks that elfFile points to an ELF file with a valid program header table.
*
* @param elfFile Potential ELF file to check
*
* \return 0 on success, otherwise < 0
*/
int
elf_checkProgramHeaderTable(elf_t* elfFile);
/**
* Checks that elfFile points to an ELF file with a valid section table.
*
* @param elfFile Potential ELF file to check
*
* \return 0 on success, otherwise < 0
*/
int
elf_checkSectionTable(elf_t* elfFile);
/**
* Find the entry point of an ELF file.
*
* @param elfFile Pointer to a valid ELF structure
*
* \return The entry point address.
*/
uintptr_t
elf_getEntryPoint(elf_t* elfFile);
/**
* Determine number of program headers in an ELF file.
*
* @param elfFile Pointer to a valid ELF structure.
*
* \return Number of program headers in the ELF file.
*/
size_t
elf_getNumProgramHeaders(elf_t* elfFile);
/**
* Determine number of sections in an ELF file.
*
* @param elfFile Pointer to a valid ELF structure.
*
* \return Number of sections in the ELF file.
*/
size_t
elf_getNumSections(elf_t* elfFile);
/**
* Get the index of the section header string table of an ELF file.
*
* @param elf Pointer to a valid ELF structure.
*
* \return The index of the section header string table.
*/
size_t
elf_getSectionStringTableIndex(elf_t* elf);
/**
* Get a string table section of an ELF file.
*
* @param elfFile Pointer to a valid ELF structure.
* @param string_section The section number of the string table.
*
* \return The string table, or NULL if the section is not a string table.
*/
const char*
elf_getStringTable(elf_t* elfFile, size_t string_segment);
/**
* Get the string table for section header names.
*
* @param elfFile Pointer to a valid ELF structure.
*
* \return The string table, or NULL if there is no table.
*/
const char*
elf_getSectionStringTable(elf_t* elfFile);
/* Section header functions */
/**
* Get a section of an ELF file.
*
* @param elfFile Pointer to a valid ELF structure
* @param i The section number
*
* \return The section, or NULL if there is no section.
*/
void*
elf_getSection(elf_t* elfFile, size_t i);
/**
* Get the section of an ELF file with a given name.
*
* @param elfFile Pointer to a valid ELF structure
* @param str Name of the section
* @param i Pointer to store the section number
*
* \return The section, or NULL if there is no section.
*/
void*
elf_getSectionNamed(elf_t* elfFile, const char* str, size_t* i);
/**
* Return the name of a given section.
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The name of a given section.
*/
const char*
elf_getSectionName(elf_t* elfFile, size_t i);
/**
* Return the offset to the name of a given section in the section header
* string table.
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The offset to the name of a given section in the section header
* string table.
*/
size_t
elf_getSectionNameOffset(elf_t* elfFile, size_t i);
/**
* Return the type of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The type of a given section.
*/
uint32_t
elf_getSectionType(elf_t* elfFile, size_t i);
/**
* Return the flags of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The flags of a given section.
*/
size_t
elf_getSectionFlags(elf_t* elfFile, size_t i);
/**
* Return the address of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The address of a given section.
*/
uintptr_t
elf_getSectionAddr(elf_t* elfFile, size_t i);
/**
* Return the offset of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The offset of a given section.
*/
size_t
elf_getSectionOffset(elf_t* elfFile, size_t i);
/**
* Return the size of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The size of a given section.
*/
size_t
elf_getSectionSize(elf_t* elfFile, size_t i);
/**
* Return the related section index of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The related section index of a given section.
*/
uint32_t
elf_getSectionLink(elf_t* elfFile, size_t i);
/**
* Return extra information of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return Extra information of a given section.
*/
uint32_t
elf_getSectionInfo(elf_t* elfFile, size_t i);
/**
* Return the alignment of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The alignment of a given section.
*/
size_t
elf_getSectionAddrAlign(elf_t* elfFile, size_t i);
/**
* Return the entry size of a given section
*
* @param elfFile Pointer to a valid ELF structure
* @param i Index of the section
*
* \return The entry size of a given section.
*/
size_t
elf_getSectionEntrySize(elf_t* elfFile, size_t i);
/* Program header functions */
/**
* Return the segment data for a given program header.
*
* @param elf Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return Pointer to the segment data
*/
void*
elf_getProgramSegment(elf_t* elf, size_t ph);
/**
* Return the type for a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The type of a given program header.
*/
uint32_t
elf_getProgramHeaderType(elf_t* elfFile, size_t ph);
/**
* Return the segment offset for a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The offset of this program header from the start of the file.
*/
size_t
elf_getProgramHeaderOffset(elf_t* elfFile, size_t ph);
/**
* Return the base virtual address of given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The memory size of the specified program header.
*/
uintptr_t
elf_getProgramHeaderVaddr(elf_t* elfFile, size_t ph);
/**
* Return the base physical address of given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The memory size of the specified program header.
*/
uintptr_t
elf_getProgramHeaderPaddr(elf_t* elfFile, size_t ph);
/**
* Return the file size of a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The file size of the specified program header.
*/
size_t
elf_getProgramHeaderFileSize(elf_t* elfFile, size_t ph);
/**
* Return the memory size of a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The memory size of the specified program header.
*/
size_t
elf_getProgramHeaderMemorySize(elf_t* elfFile, size_t ph);
/**
* Return the flags for a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The flags of a given program header.
*/
uint32_t
elf_getProgramHeaderFlags(elf_t* elfFile, size_t ph);
/**
* Return the alignment for a given program header.
*
* @param elfFile Pointer to a valid ELF structure
* @param ph Index of the program header
*
* \return The alignment of the given program header.
*/
size_t
elf_getProgramHeaderAlign(elf_t* elfFile, size_t ph);
/* Utility functions */
/**
* Determine the memory bounds of an ELF file
*
* @param elfFile Pointer to a valid ELF structure
* @param addr_type If PHYSICAL return bounds of physical memory, otherwise
* return bounds of virtual memory
* @param min Pointer to return value of the minimum
* @param max Pointer to return value of the maximum
*
* \return true on success. false on failure, if for example, it is an invalid
* ELF file
*/
int
elf_getMemoryBounds(
elf_t* elfFile, elf_addr_type_t addr_type, uintptr_t* min, uintptr_t* max);
/**
*
* \return true if the address in in this program header
*/
int
elf_vaddrInProgramHeader(elf_t* elfFile, size_t ph, uintptr_t vaddr);
/**
* Return the physical translation of a physical address, with respect
* to a given program header
*
*/
uintptr_t
elf_vtopProgramHeader(elf_t* elfFile, size_t ph, uintptr_t vaddr);
/**
* Load an ELF file into memory
*
* @param elfFile Pointer to a valid ELF file
* @param addr_type If PHYSICAL load using the physical address, otherwise using
* the
* virtual addresses
*
* \return true on success, false on failure.
*
* The function assumes that the ELF file is loaded in memory at some
* address different to the target address at which it will be loaded.
* It also assumes direct access to the source and destination address, i.e:
* Memory must be able to be loaded with a simple memcpy.
*
* Obviously this also means that if we are loading a 64bit ELF on a 32bit
* platform, we assume that any memory addresses are within the first 4GB.
*
*/
int
elf_loadFile(elf_t* elfFile, elf_addr_type_t addr_type); |
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-CLI/src/console.c | <gh_stars>1-10
#include <stdint.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_IO.h"
#include "FreeRTOS_CLI.h"
#define MAX_INPUT_LENGTH 50
#define MAX_OUTPUT_LENGTH 100
static const char * const pcWelcomeMessage =
"FreeRTOS command server.\nType Help to view a list of registered commands.\n> ";
void vCommandConsoleTask( void *pvParameters )
{
Peripheral_Descriptor_t xConsole;
char cRxedChar = 0;
int8_t cInputIndex = 0;
BaseType_t xMoreDataToFollow;
/* The input and output buffers are declared static to keep them off the stack. */
static char pcOutputString[ MAX_OUTPUT_LENGTH ], pcInputString[ MAX_INPUT_LENGTH ];
/* This code assumes the peripheral being used as the console has already
been opened and configured, and is passed into the task as the task
parameter. Cast the task parameter to the correct type. */
xConsole = ( Peripheral_Descriptor_t ) pvParameters;
/* Send a welcome message to the user knows they are connected. */
FreeRTOS_write( xConsole, pcWelcomeMessage, strlen( pcWelcomeMessage ) );
for( ;; )
{
/* This implementation reads a single character at a time. Wait in the
Blocked state until a character is received. */
FreeRTOS_read( xConsole, &cRxedChar, sizeof( cRxedChar ) );
if( cRxedChar == '\n' || cRxedChar == '\r' )
{
/* A newline character was received, so the input command string is
complete and can be processed. Transmit a line separator, just to
make the output easier to read. */
FreeRTOS_write( xConsole, "\n", strlen( "\n" ) );
/* The command interpreter is called repeatedly until it returns
pdFALSE. See the "Implementing a command" documentation for an
exaplanation of why this is. */
do
{
/* Send the command string to the command interpreter. Any
output generated by the command interpreter will be placed in the
pcOutputString buffer. */
xMoreDataToFollow = FreeRTOS_CLIProcessCommand
(
pcInputString, /* The command string.*/
pcOutputString, /* The output buffer. */
MAX_OUTPUT_LENGTH/* The size of the output buffer. */
);
/* Write the output generated by the command interpreter to the
console. */
FreeRTOS_write( xConsole, pcOutputString, strlen( pcOutputString ) );
} while( xMoreDataToFollow != pdFALSE );
/* All the strings generated by the input command have been sent.
Processing of the command is complete. Clear the input string ready
to receive the next command. */
cInputIndex = 0;
memset( pcInputString, 0x00, MAX_INPUT_LENGTH );
FreeRTOS_write( xConsole, "> ", strlen( "> " ) );
}
else
{
/* The if() clause performs the processing after a newline character
is received. This else clause performs the processing if any other
character is received. */
if( cRxedChar == '\r' )
{
/* Ignore carriage returns. */
}
else if( cRxedChar == 127 ) /* Used to be `\b`. */
{
/* Backspace was pressed. Erase the last character in the input
buffer - if there are any. */
if( cInputIndex > 0 )
{
cInputIndex--;
pcInputString[ cInputIndex ] = '\0';
/* Hacky solution to backspaces */
FreeRTOS_write( xConsole, "\b", strlen( "\b" ) );
cRxedChar = 127;
FreeRTOS_write( xConsole, &cRxedChar, strlen( &cRxedChar ) );
FreeRTOS_write( xConsole, "\b", strlen( "\b" ) );
}
}
else
{
/* A character was entered. It was not a new line, backspace
or carriage return, so it is accepted as part of the input and
placed into the input buffer. When a n is entered the complete
string will be passed to the command interpreter. */
if( cInputIndex < MAX_INPUT_LENGTH )
{
pcInputString[ cInputIndex ] = cRxedChar;
cInputIndex++;
FreeRTOS_write( xConsole, &cRxedChar, sizeof( cRxedChar ) );
}
}
}
}
}
|
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/include/stdlib.h | int atol (const char *nptr); |
keystone-enclave/FreeRTOS-Kernel | sdk/sender/sender.c | #include <stdint.h>
#include <timex.h>
#include "enclave_rl.h"
#include "printf.h"
#include "eapp_utils.h"
#include "msg_test.h"
char send_buf[DATA_SIZE];
char recv_buf[DATA_SIZE];
void EAPP_ENTRY eapp_entry(int RECEIVER_TID){
cycles_t st = get_cycles();
cycles_t et;
sbi_send(RECEIVER_TID, send_buf, DATA_SIZE, YIELD);
while(sbi_recv(RECEIVER_TID, recv_buf, DATA_SIZE, YIELD));
et = get_cycles();
printf("[msg-test-enclave] Duration: %lu\n", et -st);
syscall_task_return();
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-CLI/include/CLI_functions.h | #include <stdlib.h>
#include <stdint.h>
#include "FreeRTOS.h"
#include "FreeRTOS_CLI.h"
#include "portmacro.h"
#ifndef CLI_FUNCTIONS_H
#define CLI_FUNCTIONS_H
/* The structure that defines command line commands. A command line command
should be defined by declaring a const structure of this type. */
typedef struct xFunction
{
char * pcFunction; /* The function name which open will use. */
void * pxFunctionCallback; /* A pointer to the callback task function. */
size_t enclaveSize; /* 0 if it is a normal task, the size of the secure task otherwise. */
} Function_Definition_t;
BaseType_t FreeRTOS_run( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );
BaseType_t FreeRTOS_RegisterFunction( char * pcFunction, void * pxFunction, size_t enclaveSize );
#endif /* CLI_FUNCTIONS_H */ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.