Can you help me make sense of this class constructor? (Adafruit_ATParser) - constructor

I am building a device for my research team. To briefly describe it, this device uses a motor and load sensor connected to an Arduino to apply a rotational force to a corn stalk and record the resistance of the stalk. We are in the process of building Bluetooth into the device. We are using this BT module.
We have a BLE GATT Service with 2 characteristics for storing DATA and 1 for holding the command which is an integer that will be read by the device and acted on. Reading the command characteristic is where we encounter our problem.
void get_input(){
uint16_t bufSize = 15;
char inputBuffer[bufSize];
bleParse = Adafruit_ATParser(); // Throws error: bleParse was not declared in this scope
bleParse.atcommandStrReply("AT+GATTCHAR=3",&inputBuffer,bufSize,1000);
Serial.print("input:");
Serial.println(inputBuffer);
}
The functions I am trying to use are found in the library for the module in Adarfruit_ATParser.cpp
/******************************************************************************/
/*!
#brief Constructor
*/
/******************************************************************************/
Adafruit_ATParser::Adafruit_ATParser(void)
{
_mode = BLUEFRUIT_MODE_COMMAND;
_verbose = false;
}
******************************************************************************/
/*!
#brief Send an AT command and get multiline string response into
user-provided buffer.
#param[in] cmd Command
#param[in] buf Provided buffer
#param[in] bufsize buffer size
#param[in] timeout timeout in milliseconds
*/
/******************************************************************************/
uint16_t Adafruit_ATParser::atcommandStrReply(const char cmd[], char* buf, uint16_t bufsize, uint16_t timeout)
{
uint16_t result_bytes;
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
// Execute command with parameter and get response
println(cmd);
result_bytes = this->readline(buf, bufsize, timeout, true);
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
return result_bytes;
}
None of the examples in the library use this. They all create their own parsers. For example, the neopixel_picker example sketch has a file called packetParser.cpp which I believe retrieves data from the BT module for that specific sketch, but it never includes or uses Adafruit_ATParser.. There are no examples of this constructor anywhere and I cannot figure out how to use it. I have tried these ways:
bleParse = Adafruit_ATParser();
Adafruit_ATParser bleParse();
Adafruit_ATParser();
ble.Adafruit_ATParser bleParse();
note: ble is an object that signifies a Serial connection between arduino and BT created with:
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
Can anyone give me a clue on how to use the Adafruit_ATParser() constructor? Also, if the constructor has no reference to the ble object, how does it pass AT commands to the BT module?
I know this is a big ask, I appreciate any input you can give me.

Like this
Adafruit_ATParser bleParse;
You were closest with this one Adafruit_ATParser bleParse();. This is a common beginner mistake because it looks right. Unfortunately it declares a function bleParse which takes no arguments and returns a Adafruit_ATParser object.
I can't answer the second question.
EDIT
I've taken the time to have a look at the code. This is what I found
class Adafruit_BluefruitLE_UART : public Adafruit_BLE
{
and
class Adafruit_BLE : public Adafruit_ATParser
{
what this means is that the Adafruit_BluefruitLE_UART class is derived from the Adafruit_BLE class which in turn is derived from the Adafruit_ATParser class. Derivation means that any public methods in Adafruit_BLE can also be used on a Adafruit_BluefruitLE_UART object. You already have an Adafruit_BluefruitLE_UART object (you called it ble) so you can just use the method you want to use on that object.
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
ble.atcommandStrReply( ... );

Related

Find string length without using builtin string.length method in web methods?

I want to find length of given string with out using pub.string.length (built in function) in web methods .
Ex:If we give name "abcdef" i want result like 6 .
You could write your own java service, but that sounds redundant to me.
Here's an (as yet untested) code sample:
public static final void checkStringSize(IData pipeline)
throws ServiceException {
// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String inputString = IDataUtil.getString( pipelineCursor, "inputString" );
pipelineCursor.destroy();
long length = -1;
length = inputString.length();
// pipeline
IDataCursor pipelineCursor_1 = pipeline.getCursor();
IDataUtil.put( pipelineCursor_1, "length", ""+length );
pipelineCursor_1.destroy();
}
You could manually count the length of the string by using pub.string:substring until it gets an error.
I wouldn't recommend this - it's inelegant, possibly quite slow and it still uses a function from pub.string, which you appear to be avoiding.
Anyway, here's a way to do it, click the link to see the image.
webMethods code sample - https://i.stack.imgur.com/FE9oU.jpg
Just make sure the input string cannot be null - otherwise the substring won't throw an error and it will have an infinite loop.

How do I cast C++/CX runtime object to native C pointer type?

I am doing a C++/CX runtime wrapper, and I need pass C++/CX Object pointer to native C. How do I do it, and convert the native pointer back to C++/CX Object reference type?
void XClassA::do(XClass ^ B)
{
void * ptr = (void*)(B); // how to convert it?
}
And also, C++/CX uses Reference Counting, if I cast the Object reference to native pointer, how do I manage the pointer life cycle?
update (request from #Hans Passant)
Background of the question,
Native C
I am trying to use C++/CX wrap Native C library (not C++) as Windows Runtime Component. Native c has many callback functions which declared as the following,
for example,
//declare in native c
typedef int (GetData*)(void *, char* arg1, size_t arg2);
void * is a pointer to object instance.
and the callback will be executed in native c during runtime.
We expect Application(C#/C++CX ...) to implement the method.
WinRT wrapper (C++/CX)
my idea is the following,
(1) Provide interface to Application
// XRtWrapperNamespace
public interface class XWinRtDataWrapper
{
//declare in base class
void getData(IVector<byte> ^ data);
}
to let Application implement the function. As I cannot export native data type, I provide IVector to get data from Application.
(2) Declare a global callback function to convert IVector<byte>^ to native data type char *, like following,
// when Native C executes callback function,
// it will forward in the method in C++/CX.
// The method calls the implementation method via object pointer.
// (And here is my my question)
void XRtWrapperNamespace::callbackWrapper(void * ptr, char *, int length)
{
// create Vector to save "out" data
auto data = ref new Vector<byte>();
// I expect I could call the implementation from Application.
ptr->getData(data); // bad example.
// convert IVector data to char *
// ...
}
My question is
How do I keep windows object reference to native C?
It looks impossible, but any solution to do it?
Application (example)
//Application
public ref class XAppData: public XWinRtDataWrapper
{
public:
virtual void getData(IVector<byte> ^ data)
{
//implementation here
}
}
You are not on the right track. I'll assume you #include a c header in your component:
extern "C" {
#include "native.h"
}
And this header contains:
typedef int (* GetData)(void* buffer, int buflen);
void initialize(GetData callback);
Where the initialize() function must be called to initialize the C code, setting the callback function pointer. And that you want the client code to directly write into buffer whose allocated size is buflen. Some sort of error indication would be useful, as well as allowing the client code to specify how many bytes it actually wrote into the buffer. Thus the int return value.
The equivalent of function pointers in WinRT are delegates. So you'll want to declare one that matches your C function pointer in functionality. In your .cpp file write:
using namespace Platform;
namespace YourNamespace {
public delegate int GetDataDelegate(WriteOnlyArray<byte>^ buffer);
// More here...
}
There are two basic ways to let the client code use the delegate. You can add a method that lets the client set the delegate, equivalent to way initialize() works. Or you can raise an event, the more WinRT-centric way. I'll use an event. Note that instancing is an issue, their is no decent mapping from having multiple component objects to a single C function pointer. I'll gloss this over by declaring the event static. Writing the ref class declaration:
public ref class MyComponent sealed
{
public:
MyComponent();
static event GetDataDelegate^ GetData;
private:
static int GetDataImpl(void* buffer, int buflen);
};
The class constructor needs to initialize the C code:
MyComponent::MyComponent() {
initialize(GetDataImpl);
}
And we need the little adapter method that makes the C callback raise the event so the client code can fill the buffer:
int MyComponent::GetDataImpl(void* buffer, int buflen) {
return GetData(ArrayReference<byte>((byte*)buffer, buflen));
}

Sending Paramters to a CCCallFuncND::create Cocos2d-X

I have the following code in my Cocos2d-X application
void SampleRequest::setResponseCallback(CCCallFuncND* cb){
if(cb){
cb->retain();
stored_cb=cb;
}
}
void SampleRequest::executeStoredCallback(){
if(stored_cb)
stored_cb->execute();
}
void SampleRequest::releaseCallback(){
if(stored_cb){
stored_cb->release();
stored_cb=NULL;
}
}
and a simple class
void RequestHandler::handleSampleRequest(int data){
CCLog("--------------------------------------------> Its here for me to do %d",data);
}
and another peace of code
int i=10;
SampleRequest *t=new SampleRequest();
t->setResponseCallback(
CCCallFuncND::create(
this,
callfuncND_selector(RequestHandler::handleSampleRequest),
(void*)&i));
but the value of i recieved is 0. How can i send the value of I back to the call back function, and how can i send multiple parameters to this function.
Kind Regards,
int i=10;
Are you declaring i as a temporary variable on the stack, rather than on the heap, or as request object instance data?
If so, your i variable will be destroyed when the block within which it is created exits (variable scope ends).
That could explain why the callback receives a value pointing to undefined memory, that has been destroyed at the time of the call.
Try using the new operator, or storing your i value inside your request object up until the cb call is made.
how can i send multiple parameters to this function
You would not ; Simply pass a pointer to a structure or object. If all your stored data is in your "request" instance, you can pass the instance itself, as well.
For an example, assuming, again, that the data passed to the callback is going to remain in memory at the time of the call to the callback function (ie, the "RequestData" instance below):
struct RequestData
{
int value1 ;
int value2 ;
// ....
} ;
class RequestHandler: public cocos2d::CCObject
{
// ...
public:
void requestCallback( CCNode* sender, void* pData ) ;
}
In your implementation:
RequestHandler::requestCallback( CCNode* sender, void* pData )
{
RequestData* pRequestData = static_cast<RequestData*>( pData ) ;
if ( pRequestData )
{
// do something ...
}
}
To construct your call, build an instance of RequestData containing all the data you need to pass to the callback, make sure it is allocated on the heap with "new" or part of another object (in a queue, for instance) so that its data will still be valid in memory at the time the callback is called. I insist a bit on this point because you need some kind of data storage mechanism as part of your design, otherwise your callbacks may find themselves working off invalid addresses in memory (dangling pointers).
Essentially, from your previous code:
RequestData* pRequestData = new RequestData();
// fill in the structure data here...
SampleRequest *t=new SampleRequest();
t->setResponseCallback(
CCCallFuncND::create(
this,
callfuncND_selector(RequestHandler::requestCallback),
(void*)pRequestData));
// Use like this
void* data = (int*) 10;
int value = *((int*) &data);

How can I use SWIG to handle a JAVA to C++ call with a pointer-to-pointer argout argument?

The problem involved a JAVA call to a C-function (API) which returned a pointer-to-pointer as an argout argument. I was trying to call the C API from JAVA and I had no way to modify the API.
Using SWIG typemap to pass pointer-to-pointer:
Here is another approach using typemaps. It is targetting Perl, not Java, but the concepts are the same. And I finally managed to get it working using typemaps and no helper functions:
For this function:
typedef void * MyType;
int getblock( int a, int b, MyType *block );
I have 2 typemaps:
%typemap(perl5, in, numinputs=0) void ** data( void * scrap )
{
$1 = &scrap;
}
%typemap(perl5, argout) void ** data
{
SV* tempsv = sv_newmortal();
if ( argvi >= items ) EXTEND(sp,1);
SWIG_MakePtr( tempsv, (void *)*$1, $descriptor(void *), 0);
$result = tempsv;
argvi++;
}
And the function is defined as:
int getblock( int a, int b, void ** data );
In my swig .i file. Now, this passes back an opaque pointer in the argout typemap, becaust that's what useful for this particular situation, however, you could replace the SWIG_MakePtr line with stuff to actually do stuff with the data in the pointer if you wanted to. Also, when I want to pass the pointer into a function, I have a typemap that looks like this:
%typemap(perl5, in) void * data
{
if ( !(SvROK($input)) croak( "Not a reference...\n" );
if ( SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0 ) == -1 )
croak( "Couldn't convert $1 to $1_descriptor\n");
}
And the function is defined as:
int useblock( void * data );
In my swig .i file.
Obviously, this is all perl, but should map pretty directly to Java as far as the typemap architecture goes. Hope it helps...
[Swig] Java: Using C helper function to pass pointer-to-pointer
The problem involved a JAVA call to a C-function (API) which returned a pointer-to-pointer as an argout argument. I was trying to call the C API from JAVA and I had no way to modify the API.
The API.h header file contained:
extern int ReadMessage(HEADER **hdr);
The original C-call looked like:
HEADER *hdr;
int status;
status = ReadMessage(&hdr);
The function of the API was to store data at the memory location specified by the pointer-to-pointer.
I tried to use SWIG to create the appropriate interface file. SWIG.i created the file SWIGTYPE_p_p_header.java from API.h. The problem is the SWIGTYPE_p_p_header constructor initialized swigCPtr to 0.
The JAVA call looked like:
SWIGTYPE_p_p_header hdr = new SWIGTYPE_p_p_header();
status = SWIG.ReadMessage(hdr);
But when I called the API from JAVA the ptr was always 0.
I finally gave up passing the pointer-to-pointer as an input argument. Instead I defined another C-function in SWIG.i to return the pointer-to-pointer in a return value. I thought it was a Kludge ... but it worked!
You may want to try this:
SWIG.i looks like:
// return pointer-to-pointer
%inline %{
HEADER *ReadMessageHelper() {
HEADER *hdr;
int returnValue;
returnValue = ReadMessage(&hdr);
if (returnValue!= 1) hdr = NULL;
return hdr;
}%}
The inline function above could leak memory as Java won't take ownership of the memory created by ReadMessageHelper, since the HEADER instance iscreated on the heap.
The fix for the memory leak is to define ReadMessageHelper as a newobject in order for Java to take control of the memory.
%newobject ReadMessageHelper();
JAVA call now would look like:
HEADER hdr;
hdr = SWIG.ReadMessageHelper();
If you are lucky, as I was, you may have another API available to release the message buffer. In which case, you wouldn’t have to do the previous step.
William Fulton, the SWIG guru, had this to say about the approach above:
“I wouldn't see the helper function as a kludge, more the simplest solution to a tricky problem. Consider what the equivalent pure 100% Java code would be for ReadMessage(). I don't think there is an equivalent as Java classes are passed by reference and there is no such thing as a reference to a reference, or pointer to a pointer in Java. In the C function you have, a HEADER instances is created by ReadMessage and passed back to the caller. I don't see how one can do the equivalent in Java without providing some wrapper class around HEADER and passing the wrapper to the ReadMessage function. At the end of the day, ReadMessage returns a newly created HEADER and the Java way of returning newly created objects is to return it in the return value, not via a parameter.”

How do i get a reference to an alchemy asm declared variable into flash?

i have a variable declared in alchemy asm:
asm("var buffer:Vector.<Number> = new Vector.<Number>(100, true);");
i can populate it with data like so:
asm("buffer[%0] = %1;" : : "r"(index) : "r"(value));
what i can't figure out is how to get a reference of that asm "buffer" variable into actionscript.
(i did think of one way... what i did was to throw the "buffer" from alchemy asm, and then catch it in actionscript, but unfortunately it seems to leak a lot of memory).
is there a better alternative to doing this?
please note that performance is critical, and using default alchemy marshaling is way too slow.
asm is only for passing numbers back and forth, which means we'll have to use Alchemy's internal int-to-object mappings. Digging through the intermediate AS3 code (to see it, set the ACHACKS_TMPS environment variable to '1'), it seems that CTypemap.AS3ValType does the mapping. So you can return an asm-created object like this:
static AS3_Val alc_return_obj(void *self, AS3_Val args) {
int len= 100;
// create custom data in AS3
asm("var as3Buffer:Vector.<Number> = new Vector.<Number>(%0, true);" : : "r"(len));
// populate the vector with multiples of pi (just for fun)
for (int idx= 0; idx < len; idx++) {
double value= 3.14159265 * idx;
asm("as3Buffer[%0] = %1;" : : "r"(idx) , "r"(value));
}
// get a C reference to the AS3 object
AS3_Val alcBuffer;
asm("%0 CTypemap.AS3ValType.createC(as3Buffer)[0];" : "=r"(alcBuffer));
return alcBuffer;
}
Note: While this is fun hackery, it might not be the best way to solve this problem. This is probably not the fastest way to get data out of Alchemy and into Flash. For that, I suggest using a ByteArray to copy data into and out of Alchemy's RAM. See this SO question for some techniques in that area.