BB Slot not firing for Http Connection - httprequest

I am very new to blackberry and working with cascades.
I've implemented a simple http connection (HTTP POST).
The response is problematic, sometimes I am the response is shown in a toast, and sometimes it simply doesn't show anything.
Here is the code :
void ApplicationUI::work(QString clgId){
QNetworkAccessManager connection;
QUrl url("http://abc.co.in/test/test.php");
//url.addQueryItem("parameter", "2");
//QNetworkRequest request(url);
QByteArray data;
data.append("test=1");
QNetworkReply *reply = connection.post(request, data);
connect(reply, SIGNAL(finished()), SLOT(postFinished()));
showToast("OK");/*If I comment this line. The postFinished() is not called*/
}
void ApplicationUI::postFinished(void){
showToast("PostFinished");
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (reply->error() == QNetworkReply::NoError){
// No error
QString result = reply->readAll();
showToast(result);
}
else{
// error occurred
int errorCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << errorCode << endl << reply->errorString();
showToast(reply->errorString());
}
reply->deleteLater();
}
void ApplicationUI::showToast(QString text) {
bb::system::SystemToast toast;
toast.setBody(text);
toast.killTimer(5);
toast.setPosition(bb::system::SystemUiPosition::BottomCenter);
toast.exec();
}
I am in a fix about what the problem is, please help.

I would recommend having a look at the BlackBerry 10 Networking documentation.
Networking documentation
There is also a sample project showing how to use HTTP post and HTTP get to communicate with a server.
github sample project

Related

How do i send an intent via react native to Print Connect zebra app

I am currently trying to communicate with a Zebra printer via a react-native application, on mobile I am trying to send my ZPL code (instructions for the printer to print the content i want) from my application to the printer via PrintConnect, Zebra also provides a pdf file guiding people on how to communicate to the app via intents available here however the examples dislpayed on the guide are using a different language.
My question then is how would i go about replicating this (Page 96, Passthrough Intent example) :
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.zebra.printconnect",
"com.zebra.printconnect.print.PassthroughService"));
intent.putExtra("com.zebra.printconnect.PrintService.PASSTHROUGH_DATA", passthroughBytes);
intent.putExtra("com.zebra.printconnect.PrintService.RESULT_RECEIVER", buildIPCSafeReceiver(new
ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == 0) { // Result code 0 indicates success
// Handle successful print
} else {
// Handle unsuccessful print
// Error message (null on successful print)
String errorMessage = resultData.getString("com.zebra.printconnect.PrintService.ERROR_MESSAGE");
}
}
}));
Into something acceptable by the react-native-send-intent package such as this:
SendIntentAndroid.openApp("com.mycorp.myapp", {
"com.mycorp.myapp.reason": "just because",
"com.mycorp.myapp.data": "must be a string",
}).then(wasOpened => {});
Thank you for the time you took to read my question.

Sending Cloud to Device Messages using IoT DevKit and Azure IoT Hub - Device Code

I need to send a message from the IoT Hub to the DevKit Device. Based on https://learn.microsoft.com/en-au/azure/iot-hub/iot-hub-devguide-c2d-guidance I want to send a Direct Method as I need to manage a bank of relays.
I have an IoT DevKit and have successfully configured it and are able to send device to IoT Hub messages but am looking for a sample to do this the other way. I currently can only find samples that set the device twin properties, not send direct methods. On the server-side I believe I would use Microsoft.Azure.Devices.ServiceClient to SendAsync a message to the device (happy to be corrected is incorrect).
On the device I think (???) I need to use SetDeviceMethodCallback but I have no idea how to initialise it and receive messages. Ideally, the sample would also include how to send an acknowledgement that the message was received and actioned.
Any help would be appreciated even if just to let me know I am on the right track here. Thanks in advance.
Here is some sample that I used before with the IoT DevKit (=Mxchip) on the device side:
static int DeviceMethodCallback(const char *methodName, const unsigned char *payload, int size, unsigned char **response, int *response_size)
{
LogInfo("Try to invoke method %s", methodName);
const char *responseMessage = "\"Successfully invoke device method\"";
int result = 200;
if (strcmp(methodName, "start") == 0)
{
DoSomething();
}
else if (strcmp(methodName, "stop") == 0)
{
DoSomethingElse();
}
else
{
LogInfo("No method %s found", methodName);
responseMessage = "\"No method found\"";
result = 404;
}
*response_size = strlen(responseMessage) + 1;
*response = (unsigned char *)strdup(responseMessage);
return result;
}
DevKitMQTTClient_SetDeviceMethodCallback(DeviceMethodCallback);
On the services side (where you do the method invocation) here is some C# example
ServiceClient _iothubServiceClient = ServiceClient.CreateFromConnectionString(config["iothubowner_cs"]);
var result = await _iothubServiceClient.InvokeDeviceMethodAsync(deviceid, "start");
var status = result.Status;

I need answer of one jade agent to depend on information from others and don't know how to do it

I'm new to jade and I have 5 agents in eclipse that have formula for finding an average and the question is how to send information from agent to this formula for calculation?
I'll be glad if someone can help me with this.
For example, there is one of my agents. There's no formula, because I don't know how to represent it. This is math expression of it: n+=alfa(y(1,2)-y(1,1))
public class FirstAgent extends Agent {
private Logger myLogger = Logger.getMyLogger(getClass().getName());
public class WaitInfoAndReplyBehaviour extends CyclicBehaviour {
public WaitInfoAndReplyBehaviour(Agent a) {
super(a);
}
public void action() {
ACLMessage msg = myAgent.receive();
if(msg != null){
ACLMessage reply = msg.createReply();
if(msg.getPerformative()== ACLMessage.REQUEST){
String content = msg.getContent();
if ((content != null) && (content.indexOf("What is your number?") != -1)){
myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Received Info Request from "+msg.getSender().getLocalName());
reply.setPerformative(ACLMessage.INFORM);
try {
reply.setContentObject(7);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected request ["+content+"] received from "+msg.getSender().getLocalName());
reply.setPerformative(ACLMessage.REFUSE);
reply.setContent("( UnexpectedContent ("+content+"))");
}
}
else {
myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected message ["+ACLMessage.getPerformative(msg.getPerformative())+"] received from "+msg.getSender().getLocalName());
reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
reply.setContent("( (Unexpected-act "+ACLMessage.getPerformative(msg.getPerformative())+") )");
}
send(reply);
}
else {
block();
}
}
}
So from what I can make out you want to (1) send a formula/task to multiple platforms, (2) have them performed locally, (3) and have the results communicated back.
I think there are atleast two ways of doing this:
The first is sending an object in an ACLMessage using Java Serialisation. This is a more OOP approach and not very "Agenty".
The second being the cloning or creating a local task agent.
Using Java SerialZation. (Solution 1)
Create an object for the calculation
class CalculationTask implements serialization
{ int n;
int calculate(){
n+=alfa(y(1,2)-y(1,1));
}
}
send the calculation object via ACLMESSAGE from the senderAgent.
request.setContentObject(new CalculationTask())
recieve the calculation object by recieverAgent and perform calculation on the object. Then response setting the complete task in the response.
CalculationTask myTask = request.getContentObject();
myTask.calculate();
ACLMESSAGE response = request.createReply();
response.setContentObject(myTask());
response.setPerformative(ACLMESSAGE.INFORM)
send(response)
The senderAgent then receives the complete job.
ACLMESSAGE inform = getMessage();
CalculationTask completeTask = inform.getContentObject();
completeTask.process()
Creating local Task Agents (Solution 2)
The Agent Orientated way of doing it would be to launch a task agent on each platform. Have each task agent complete the task and respond appropriately.

Lync Client API exception - Specified method is not supported

I am developing simple chat application using CWE which sends messages by using contextual data. I'm having "Specified method is not supported" exception message. This exception occurs when I try to start chat with group. one-to-one chat works fine with no exception. since I'm having same code on both sender & receiver side, I'm confused that how to make this work. Please help.
My code snippet as as follows.
void method1()
{
//
//here I have code to send an IM saying "lets chat in extension window"
//
try
{
Dictionary<ContextType, object> context = new Dictionary<ContextType, object>();
context.Add(ContextType.ApplicationId, "{1226271D-64C9-4F24-B416-E6A583F45A1C}");
context.Add(ContextType.ApplicationData, "initial_data_request");
try { IAsyncResult res = conversation.BeginSendInitialContext(context, null, null); }
catch (Exception e1)
{
MessageBox.Show(e1.Data+"\n\n"+e1.Message);
}
}
catch (Exception ee)
{
MessageBox.Show("Client Platform Exception: " + ee.Message);
}
}
This is the method I call when my application starts. It is supposed to send initial context so that receiver clients when receive this should open my extension application.
I found the answer. It is showing that exception because contextual data will not work in a group conversation.
Found the related thread here..
http://social.msdn.microsoft.com/Forums/lync/en-US/b4e46648-7097-4348-8327-6864f1c12ab2/contextdata-in-a-group-conversation?forum=communicatorsdk

OpenSL ES RegisterCallback causes crash

I have to use OpenSL for my project (tried Soundpool but it's not good at all). However, after playing the sound multiple times (around 35 continuous times), the app is shutdown (I guess maybe because of overflow).
I tried to free the buffer/memory to solve the problem (and for god sake, I don't know how to do by using this OpenSL). So I decided to try to free when the file was finished playing. OpenSL ES provide us the RegisterCallback function which might help. New problem occurred, in my case (using URI file), RegisterCallback caused my app crash again. It's stuck.
Here is my code. Please help. It crashed right after //register callback for uri.
static short fdBuffer[SAWTOOTH_FRAMES];
// create URI audio player
jboolean Java_jp_mobigame_ayakashi_CardGameActivity_createUriAudioPlayer(JNIEnv* env, jclass clazz,
jstring uri)
{
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n createUri \n");
SLresult result;
// convert Java string to UTF-8
const jbyte *utf8 = (*env)->GetStringUTFChars(env, uri, NULL);
assert(NULL != utf8);
// configure audio source
// (requires the INTERNET permission depending on the uri parameter)
SLDataLocator_URI loc_uri = {SL_DATALOCATOR_URI, (SLchar *) utf8};
SLDataFormat_MIME format_mime = {SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED};
SLDataSource audioSrc = {&loc_uri, &format_mime};
// configure audio sink
SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject};
SLDataSink audioSnk = {&loc_outmix, NULL};
// create audio player
const SLInterfaceID ids[3] = {SL_IID_SEEK, SL_IID_MUTESOLO /*SL_IID_BUFFERQUEUE*/, SL_IID_VOLUME};
const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
result = (*engineEngine)->CreateAudioPlayer(engineEngine, &uriPlayerObject, &audioSrc,
&audioSnk, 3, ids, req);
// note that an invalid URI is not detected here, but during prepare/prefetch on Android,
// or possibly during Realize on other platforms
assert(SL_RESULT_SUCCESS == result);
// release the Java string and UTF-8
(*env)->ReleaseStringUTFChars(env, uri, utf8);
// realize the player
result = (*uriPlayerObject)->Realize(uriPlayerObject, SL_BOOLEAN_FALSE);
// this will always succeed on Android, but we check result for portability to other platforms
if (SL_RESULT_SUCCESS != result) {
(*uriPlayerObject)->Destroy(uriPlayerObject);
uriPlayerObject = NULL;
return JNI_FALSE;
}
// get the play interface
result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_PLAY, &uriPlayerPlay);
assert(SL_RESULT_SUCCESS == result);
// get the seek interface
result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_SEEK, &uriPlayerSeek);
assert(SL_RESULT_SUCCESS == result);
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n createUri 1\n");
//get the buffer queue interface
result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &uriPlayerBufferQueue);
assert(SL_RESULT_SUCCESS == result);
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n createUri 2\n");
//register callback for uri
result = (*uriPlayerBufferQueue)->RegisterCallback(uriPlayerBufferQueue, bqUriPlayerCallback, NULL);
assert(SL_RESULT_SUCCESS == result);
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n createUri 4\n");
//Enqueue
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG", "\n createUri 3\n");
result = (*uriPlayerBufferQueue)->Enqueue(uriPlayerBufferQueue, fdBuffer, sizeof(fdBuffer));
// get the mute/solo interface
result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_MUTESOLO, &uriPlayerMuteSolo);
assert(SL_RESULT_SUCCESS == result);
// get the volume interface
result = (*uriPlayerObject)->GetInterface(uriPlayerObject, SL_IID_VOLUME, &uriPlayerVolume);
assert(SL_RESULT_SUCCESS == result);
return JNI_TRUE;
}
It looks like you are trying to get a buffer queue interface, even though you are specifying a uri source. You also appear to be enqueing data. If you are just trying to play audio from a uri, you shouldn't need to do this. If you are trying to output to a buffer instead of the speakers, then this may be valid. I'm no OpenSL expert by any means, so there could be a reason for this. However, if there isn't a reason for that, try registering the callback on the player object instead.
(*uriPlayerPlay)->RegisterCallback(uriPlayerPlay, bqUriPlayerCallback, NULL);
As a side note, you will probably want to set the callback event mask. There are several options, but I believe the one you are looking for is:
(*uriPlayerPlay)->SetCallbackEventsMask(uriPlayerPlay, SL_PLAYEVENT_HEADATEND)
Please note that there might be issues with this. See https://groups.google.com/forum/?fromgroups=#!topic/android-ndk/7YaqlKlDMO4.
If this doesn't help, it might be helpful to see your definition of the callback function. I believe it should look something like:
static void bqUriPlayerCallback (SLPlayItf caller, void *pContext, SLuint32 playevent)