cocos2d-x Convert nsstring to char* - cocos2d-x

NSString *_str=#"rank";
const char *color_char1 = [_str cStringUsingEncoding:NSASCIIStringEncoding];
I run it in iphone 6.0 Simulator, it works fine; but when I run it on new iPad it crashes.
I can't get color_char1 ,why?

const char * myChar = [#"hey I am an NSString" UTF8String];
That should work :D

try this code.
NSString *_str=#"rank";
const char *color_char1 = (char *)_str;

Related

how do i publish the data on mqtt of the bme680 sensor using ESP32cam

I am using windows 10 and working on getting the gas readings from BME680 using esp32cam. I tried to add this:
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
//#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <Arduino_JSON.h>
//uint64_t mac;
//uint32_t high;
//uint32_t low;
// Replace the next variables with your SSID/Password combination
const char* ssid = "";
const char* password = "";
// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "";
const char* mqtt_server = "";
const char* mqtt_port = "";
const char* mqtt_user = "";
const char* mqtt_password = "";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
//uncomment the following lines if you're using SPI
#include <SPI.h>
#define BME_SCK 14
#define BME_MISO 12
#define BME_MOSI 13
#define BME_CS 15
//Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;
float pressure = 0;
float gas = 0;
//Device ID
//uint64_t chip_id;
//chip_id=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
// LED Pin
const int ledPin = 4;
void setup() {
Serial.begin(115200);
// default settings
// (you can also pass in a Wire library object like &Wire2)
//status = bme.begin();
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
WiFi.begin();
}
setup_wifi();
client.setServer(mqtt_server,...);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
// Set up oversampling and filter initialization
bme.setTemperatureOversampling(BME680_OS_8X);
bme.setHumidityOversampling(BME680_OS_2X);
bme.setPressureOversampling(BME680_OS_4X);
bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
bme.setGasHeater(320, 150); // 320*C for 150 ms
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
if (String(topic) == "esp32/output") {
Serial.print("Changing output to ");
if(messageTemp == "on"){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(messageTemp == "off"){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
// Subscribe
client.subscribe("esp32/output");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(20000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
// Temperature in Celsius
temperature = bme.readTemperature();
// Uncomment the next line to set temperature in Fahrenheit
// (and comment the previous temperature line)
//temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
// Convert the value to a char array
char tempString[8];
dtostrf(temperature, 1, 2, tempString);
//Serial.print("Temperature: ");
//Serial.println(tempString);
//client.publish("esp32/temperature", tempString);
humidity = bme.readHumidity();
// Convert the value to a char array
char humString[8];
dtostrf(humidity, 1, 2, humString);
//Serial.print("Humidity: ");
//Serial.println(humString);
//client.publish("esp32/humidity", humString);
pressure = bme.readPressure();
//Convert the value to a char array
char preString[16];
dtostrf(pressure, 1, 2, preString);
//Serial.print("Pressure: ");
//Serial.println(preString);
//client.publish("esp32/pressure", preString);
gas = bme.readGas();
//Serial.print(bme.gas_resistance / 1000.0);
char gasString[8];
dtostrf(gas, 1, 2, gasString);
//Serial.println(" KOhms");
char macValue[13]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEfuseMac();
sprintf(macValue, "%012x", mac);
//Serial.print("ChipID: ");
//Serial.println(chipId);
//client.publish("esp32/chipid", chipId);
JSONVar data;
data["temperature"] = temperature;
data["humidity"] = humidity;
data["pressure"] = pressure;
data["macValue"] = macValue;
data["gas"] = gas;
//Serial.print("data.keys() = ");
//Serial.println(data.keys());
//Serial.print("Data = ");
//Serial.println(data);
String jsonString = JSON.stringify(data);
//Serial.print("JSON.stringify(data) = ");
//Serial.println(jsonString);
client.publish("esp32/data", jsonString.c_str());
}
}
everything got compiled perfectly. But when i tried to upload the code, this error came up:
Arduino: 1.8.9 (Windows 10), Board: "ESP32 Wrover Module, Huge APP
(3MB No OTA), QIO, 80MHz, 115200, Verbose"
Sketch uses 789282 bytes (25%) of program storage space. Maximum
is 3145728 bytes.
Global variables use 40652 bytes (12%) of dynamic memory, leaving
287028 bytes for local variables. Maximum is 327680 bytes.
esptool.py v2.6
Serial port COM7
Connecting.....
Chip is .....(revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse,
Coding Scheme None
MAC: .....
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Warning: Could not auto-detect Flash size (FlashID=0xffffff,
SizeID=0xff), defaulting to 4MB
Compressed 8192 bytes to 47...
A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
I don't know why is this thing coming up because previously everything was working fine when I tried to incorporate BME280 and publish the available data on MQTT. Now, I have switched to bme680.
EDIT:
I tried to disconnect BME from ESP32, then uploaded the code, then connected BME back. The error did not show up, but still, the data is not being shown this time, rather something like this, continually:
rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun 8 2016 00:22:57
It looks to me that ESP32-CAM is not in the bootloader mode when you try to upload the code.
Did you connect IO0 and GND pins and push the reset button?
You should see the message that ESP32 is ready for upload in the terminal window.
Sorry for the late reply ... :)

Parsing data from incoming HTTP Post request on ESP8266/Wemos

I'm sending an HTTP Post request on my Android App to my Wemos D1 mini pro and want to parse the incoming data (which is a json). My current code just prints out the whole POST request and I need to trim it so I only get the needed data. There are several examples out there but nothing matched my needs or worked at all.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
const char* ssid = "myssid";
const char* password = "mypassword";
char c;
String readString = String(100);
WiFiServer wifiServer(80);
void setup() {
Serial.begin(9600);
delay(1000);
WiFi.begin(ssid, password);
WiFi.mode(WIFI_STA);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting..");
}
Serial.print("Connected to WiFi. IP:");
Serial.println(WiFi.localIP());
wifiServer.begin();
}
//for parsing the actual JSON later
//you can ignore this at this moment because I don't even get the needed string to parse it from JSON
void handleReceivedMessage(String message){
StaticJsonBuffer<500> JSONBuffer; //Memory pool
JsonObject& parsed = JSONBuffer.parseObject(message); //Parse message
if (!parsed.success()) { //Check for errors in parsing
Serial.println("Parsing failed");
return;
}
const char * name3 = parsed["name"]; //Get name from HTTP
Serial.println("name3");
}
void loop() {
WiFiClient client = wifiServer.available();
if (client) {
Serial.println("Client connected");
while (client.connected()) {
while (client.available()>0) {
//instream from mobile device
char c = client.read();
if (readString.length() < 100) {
//store characters to string
readString.concat(c);
//Serial.print(c);
}
Serial.print(c);
//if HTTP request has ended
if (c == '\n') {
//Serial.println(readString);
delay(50);
//handleReceivedMessage(readString);
readString = "";
client.stop();
}
}}}}
Well first of all you seem to be using ArduinoJson lib version 5, now I could share the code I worked with and never failed me with version 5. But i'm going to encourage you to update the library to version 6 and share with you my piece of code.
I use this normally when I need to get information out of API's
DynamicJsonDocument doc(1024);
char* payload1 = (char*)malloc(http.getSize() + 1);
http.getString().toCharArray(payload1, http.getSize() + 1);
Serial.println(payload1);
http.end();
auto error = deserializeJson(doc, payload1);
free(payload1);
if (error) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
return;
}
serializeJsonPretty(doc, Serial);
now as you can see, I'm using a getString method from httpClient lib in order to fill my char array and than parse it into json object (pretty much the same thing you was attempting, only difference is the memory pointers and Memory allocations.
Hopefully this will work with you.

How do I work with complex numbers in CUSPARSE?

I'm currently working with CUSPARSE. I'm having trouble because I don't know how to print a complex number. For example, when I write:
cuComplex a;
a.x=1.2;
a.y=2.2;
How do I print the varable a?
I've tried :
cout<< a;
but it doesn't work.
You will need to overload the << operator to take in cuComplex and cuDoubleComplex data types.
std::ostream& operator<<(std::ostream& strm, const cuComplex& in)
{
char sgn[2] = "+-"
strm << in.x << sgn[in.y < 0] << " i"<< std::abs(in.y);
return strm;
}
You can do the same for cuDoubleComplex
The data in std::complex is identical to the corresponding data in a cuComplex, i.e. you can reinterpret_cast pointers (and therefore arrays, too) of one type to the other – it works in practise and is, I think, actually guaranteed by C++11, you can test it like this:
namespace check_stdComplexdouble_to_cuDoubleComplex_binary_compatibility{
using std::complex;
const complex<double> testarr[] = { complex<double>(0.,.5)
, complex<double>(1.,1.5) };
const cuDoubleComplex* cucomplexd
= reinterpret_cast<const cuDoubleComplex*>(testarr);
auto tester() -> bool {
assert( cuCreal(cucomplexd[0])==0. && cuCimag(cucomplexd[0])==.5
&& cuCreal(cucomplexd[1])==1. && cuCimag(cucomplexd[1])==1.5 );
return true;
}
const bool ok = tester();
bool good(){return ok;}
};
If you call a CUBLAS function that's supposed to read/write from/to an std::complex<float>, you can just give it a reinterpret_casted pointer, e.g.
std::complex<double> result;
xhandle->cublasstat = yhandle->cublasstat
= cublasZdotc( *xhandle->cublashandle
, xhandle->vect_dimension
, xhandle->vector, 1
, yhandle->vector, 1
, reinterpret_cast<cuDoubleComplex*>(&result) );

How to Call an Application with Parameters in NPAPI for Mac

I try to create a simple NPAPI which passes an URL to Safari.
plugin_invoke method is below:
bool plugin_invoke(NPObject *obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) {
// Make sure the method called is "open".
NPUTF8 *name = npnfuncs->utf8fromidentifier(methodName);
if(strcmp(name, plugin_method_name_open) == 0) {
npnfuncs->memfree(name);
BOOLEAN_TO_NPVARIANT(false, *result);
// Meke sure the arugment has at least one String parameter.
if(argCount > 0 && NPVARIANT_IS_STRING(args[0])) {
// Build CFURL object from the arugment.
NPString str = NPVARIANT_TO_STRING(args[0]);
CFURLRef url = CFURLCreateWithBytes(NULL, (const UInt8 *)str.UTF8Characters, str.UTF8Length, kCFStringEncodingUTF8, NULL);
if(url) {
// Open URL with the default application by Launch Service.
//OSStatus res = LSOpenCFURLRef(url, NULL);
//CFRelease(url);
OSStatus resultt = eventNotHandledErr;
//FSRef appRef;
FSRef appRef = {0};
Boolean isDir =true;
resultt = FSPathMakeRef((UInt8 *) "/Applications/Safari.app", &appRef,
&isDir);
LSApplicationParameters appParams = {0, kLSLaunchDefaults};
appParams.application = &appRef;
appParams.version = 0;
appParams.flags = kLSLaunchDefaults;
resultt = LSOpenApplication(&appParams, NULL);
BOOLEAN_TO_NPVARIANT(resultt == noErr, *result);
}
}
return true;
}
npnfuncs->memfree(name);
return false;
}
Currently it just invokes Safari but URL can not be passed.
How can I pass an example URL to the Safari in NPAPI? I read LSOpenFromURLSpec might work but I could not create the code.
Read the documentation for Launch Services, especially LSOpenURLsWithRole.
FYI, nothing about your question is NPAPI-specific, it's just about launching a Mac application from another process. In general you'll get more answers if you don't post general questions as NPAPI questions, since way more people know the answers to general Mac questions than to NPAPI-specific questions.

iOS 5.0 ignoring NSSetUncaughtExceptionHandler?

I've noticed some strange behavior in iOS 5: NSSetUncaughtExceptionHandler() doesn't seem to do anything anymore.
I have the following code:
static NSString* documentsDirectory()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
static void handleException(NSException *exception)
{
// Write something to the documents dir
NSString* path = [documentsDirectory() stringByAppendingPathComponent:#"crashlog.txt"];
NSString* str = #"Handled exception";
NSError* err;
if(![str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err])
{
NSLog(#"Failed to write to file");
}
NSLog(#"Handled exception");
}
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSSetUncaughtExceptionHandler(&handleException);
[NSException raise:#"Test" format:#"Testing"];
...
}
The above code works on any device or simulator running 4.x or earlier. However, when I run it on the 5.0 simulator, the exception handler doesn't get called (doesn't write the file to the documents dir, doesn't log, and doesn't trigger if I set a breakpoint inside the handler).
Unfortunately, I don't have a 5.0 device available for testing, so I'm hoping someone could confirm that it's broken on 5.0 so I can file a bug report (or correct me, if there's a problem with my code).
Use iOS 6.0 SDK, build and run it on simulator 5.0! It works!
//////Code:
static NSString* documentsDirectory()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
static void handleException(NSException *exception)
{
// Write something to the documents dir
NSString* path = [documentsDirectory() stringByAppendingPathComponent:#"crashlog.txt"];
NSString* str = #"Handled exception";
NSError* err;
if(![str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err])
{
NSLog(#"Failed to write to file");
}
NSLog(#"Handled exception");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSSetUncaughtExceptionHandler(&handleException);
[NSException raise:#"Test" format:#"Testing"];
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[NSSetUncaughtExceptionHandlerTestViewController alloc] initWithNibName:#"NSSetUncaughtExceptionHandlerTestViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
//////Terminal log:
2012-10-09 20:06:24.726 NSSetUncaughtExceptionHandlerTest[7815:c07] Handled exception
2012-10-09 20:06:24.727 NSSetUncaughtExceptionHandlerTest[7815:c07] *** Terminating app due to uncaught exception 'Test', reason: 'Testing'
*** First throw call stack:
(0x14a4052 0xea4d0a 0x144ca78 0x144c9e9 0x29d7 0x129d6 0x138a6 0x22743 0x231f8 0x16aa9 0x138efa9 0x14781c5 0x13dd022 0x13db90a 0x13dadb4 0x13daccb 0x132a7 0x14a9b 0x28b2 0x27e5)
terminate called throwing an exception(lldb)
I'm seeing the same thing. It works on my iPad, but not in the simulator. If someone confirms on the phone, please feel free to edit this answer to reflect that.