microsoft cpprestsdk listen to multiple url with same ip? - cpprest-sdk

I want to use cpprestsdk to make a restful API,
I copied some code from here :
int main()
{
http_listener listener("http://0.0.0.0:9080/demo/work1");
cout<<"start server!"<<endl;
listener.support(methods::GET, handle_get);
listener.support(methods::POST, handle_post);
listener.support(methods::PUT, handle_put);
listener.support(methods::DEL, handle_del);
try
{
listener
.open()
.then([&listener]() {TRACE(L"\nstarting to listen\n"); })
.wait();
while (true);
}
catch (exception const & e)
{
cout << e.what() << endl;
}
return 0;
}
now I have to listen to not only "http://0.0.0.0:9080/demo/work1" , but also "http://0.0.0.0:9080/demo/work2", "http://0.0.0.0:9080/realfunction/work1". All in the same IP and port, but different sub-path
Should I use multiple listener to handle all the url one by one in multi-thread? Or there is any other way to handle this?

You can set
http_listener listener("http://0.0.0.0:9080/");
And then in the handler check the request. In the examples linked in cpprestsdk's github I saw things like
void handle_get(http_request message) {
auto path = uri::split_path(uri::decode(message.relative_uri().path()));
if (path.size() == 2 && path[0] == "demo" && path[1] == "work1") {
// ...
} else if (path.size() == 2 && path[0] == "demo" && path[1] == "work2") {
// ...
} else {
message.reply(status_codes::NotFound);
}
}

Related

How to properly forward/redirect calls with pjsua2

I can't find info on the net how to forward a call with pjsua2.
Currently Im trying with the xfer method but Im getting:
../src/pjsip-ua/sip_inv.c:3942: inv_on_state_null: Assertion `!"Unexpected transaction type"' failed.
There is no information about this error.
This is my code Im trying:
void MyAccount::onIncomingCall(OnIncomingCallParam &iprm)
{
MyCall *call = new MyCall(*this, iprm.callId);
...
calls.push_back(call);
...
QString fwd_to = fwd(QString::fromStdString(ci.remoteUri));
if(fwd_to != "NO_FWD")
{
info+="*** Xfer Call: ";
info+=QString::fromStdString(ci.remoteUri);
info+=" [";
info+=QString::fromStdString(ci.stateText);
info+="]\n";
infoChanged=true;
CallOpParam prm1;
prm1.statusCode = (pjsip_status_code)200;
call->answer(prm1);
pj_thread_sleep(2000);
CallOpParam prm2(true);
call->xfer(fwd_to.toStdString(), prm2);
}
else
{
// standart incoming
...
}
}
fwd is my own function which search a database if it needs to forward the call
I did something like this and works, dont know if some other way exist:
(answering with no media, setting flag and in other thread xfering call to fwd_to string)
if(fwd_to != "NO_FWD")
{
CallOpParam prm1;
prm1.statusCode = (pjsip_status_code)200;
call->answer(prm1);
call->fwd_to = fwd_to;
call->fwd=true;
}
FwdThread *fwd_thread = new FwdThread();
fwd_thread->start();
void FwdThread::run()
{
static pj_thread_desc s_desc;
static pj_thread_t *s_thread;
pj_thread_register("FwdThread", s_desc, &s_thread);
loop();
}
void FwdThread::loop()
{
while(1)
{
for(auto &call : pjt->v_calls)
{
if(call->fwd && call->answered)
{
call->fwd=false;
CallOpParam prm2(true);
call->xfer(call->fwd_to.toStdString(), prm2);
}
}
if(pjt->Stop)
break;
pj_thread_sleep(500);
}
}

How to host a html using sd card

i wanna host a webserver from a sd card using ESP8266. i look through the github library SDWebServer, and i tried the code it came out following error
error: 'class String' has no member named 'clear' and the line of code "path.clear();" is causing this error
Can anyone help to solve or anyone has better example code to share with me?
/* SDWebServer - Example WebServer with SD Card backend for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the ESP8266WebServer library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Have a FAT Formatted SD Card connected to the SPI port of the ESP8266
The web root is the SD Card root folder
File extensions with more than 3 charecters are not supported by the SD Library
File Names longer than 8 charecters will be truncated by the SD library, so keep filenames shorter
index.htm is the default index (works on subfolders as well)
upload the contents of SdRoot to the root of the SDcard and access the editor by going to http://esp8266sd.local/edit
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <SD.h>
#define DBG_OUTPUT_PORT Serial
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "esp8266sd";
ESP8266WebServer server(80);
static bool hasSD = false;
File uploadFile;
void returnOK() {
server.send(200, "text/plain", "");
}
void returnFail(String msg) {
server.send(500, "text/plain", msg + "\r\n");
}
bool loadFromSdCard(String path) {
String dataType = "text/plain";
if (path.endsWith("/")) {
path += "index.htm";
}
if (path.endsWith(".src")) {
path = path.substring(0, path.lastIndexOf("."));
} else if (path.endsWith(".htm")) {
dataType = "text/html";
} else if (path.endsWith(".css")) {
dataType = "text/css";
} else if (path.endsWith(".js")) {
dataType = "application/javascript";
} else if (path.endsWith(".png")) {
dataType = "image/png";
} else if (path.endsWith(".gif")) {
dataType = "image/gif";
} else if (path.endsWith(".jpg")) {
dataType = "image/jpeg";
} else if (path.endsWith(".ico")) {
dataType = "image/x-icon";
} else if (path.endsWith(".xml")) {
dataType = "text/xml";
} else if (path.endsWith(".pdf")) {
dataType = "application/pdf";
} else if (path.endsWith(".zip")) {
dataType = "application/zip";
}
File dataFile = SD.open(path.c_str());
if (dataFile.isDirectory()) {
path += "/index.htm";
dataType = "text/html";
dataFile = SD.open(path.c_str());
}
if (!dataFile) {
return false;
}
if (server.hasArg("download")) {
dataType = "application/octet-stream";
}
if (server.streamFile(dataFile, dataType) != dataFile.size()) {
DBG_OUTPUT_PORT.println("Sent less data than expected!");
}
dataFile.close();
return true;
}
void handleFileUpload() {
if (server.uri() != "/edit") {
return;
}
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
if (SD.exists((char *)upload.filename.c_str())) {
SD.remove((char *)upload.filename.c_str());
}
uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (uploadFile) {
uploadFile.write(upload.buf, upload.currentSize);
}
DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
} else if (upload.status == UPLOAD_FILE_END) {
if (uploadFile) {
uploadFile.close();
}
DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
}
}
void deleteRecursive(String path) {
File file = SD.open((char *)path.c_str());
if (!file.isDirectory()) {
file.close();
SD.remove((char *)path.c_str());
return;
}
file.rewindDirectory();
while (true) {
File entry = file.openNextFile();
if (!entry) {
break;
}
String entryPath = path + "/" + entry.name();
if (entry.isDirectory()) {
entry.close();
deleteRecursive(entryPath);
} else {
entry.close();
SD.remove((char *)entryPath.c_str());
}
yield();
}
SD.rmdir((char *)path.c_str());
file.close();
}
void handleDelete() {
if (server.args() == 0) {
return returnFail("BAD ARGS");
}
String path = server.arg(0);
if (path == "/" || !SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}
deleteRecursive(path);
returnOK();
}
void handleCreate() {
if (server.args() == 0) {
return returnFail("BAD ARGS");
}
String path = server.arg(0);
if (path == "/" || SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}
if (path.indexOf('.') > 0) {
File file = SD.open((char *)path.c_str(), FILE_WRITE);
if (file) {
file.write((const char *)0);
file.close();
}
} else {
SD.mkdir((char *)path.c_str());
}
returnOK();
}
void printDirectory() {
if (!server.hasArg("dir")) {
return returnFail("BAD ARGS");
}
String path = server.arg("dir");
if (path != "/" && !SD.exists((char *)path.c_str())) {
return returnFail("BAD PATH");
}
File dir = SD.open((char *)path.c_str());
path.clear();
if (!dir.isDirectory()) {
dir.close();
return returnFail("NOT DIR");
}
dir.rewindDirectory();
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/json", "");
WiFiClient client = server.client();
server.sendContent("[");
for (int cnt = 0; true; ++cnt) {
File entry = dir.openNextFile();
if (!entry) {
break;
}
String output;
if (cnt > 0) {
output = ',';
}
output += "{\"type\":\"";
output += (entry.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\"";
output += entry.name();
output += "\"";
output += "}";
server.sendContent(output);
entry.close();
}
server.sendContent("]");
server.sendContent(""); // Terminate the HTTP chunked transmission with a 0-length chunk
dir.close();
}
void handleNotFound() {
if (hasSD && loadFromSdCard(server.uri())) {
return;
}
String message = "SDCARD Not Detected\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
DBG_OUTPUT_PORT.print(message);
}
void setup(void) {
DBG_OUTPUT_PORT.begin(115200);
DBG_OUTPUT_PORT.setDebugOutput(true);
DBG_OUTPUT_PORT.print("\n");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
DBG_OUTPUT_PORT.print("Connecting to ");
DBG_OUTPUT_PORT.println(ssid);
// Wait for connection
uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
delay(500);
}
if (i == 21) {
DBG_OUTPUT_PORT.print("Could not connect to");
DBG_OUTPUT_PORT.println(ssid);
while (1) {
delay(500);
}
}
DBG_OUTPUT_PORT.print("Connected! IP address: ");
DBG_OUTPUT_PORT.println(WiFi.localIP());
if (MDNS.begin(host)) {
MDNS.addService("http", "tcp", 80);
DBG_OUTPUT_PORT.println("MDNS responder started");
DBG_OUTPUT_PORT.print("You can now connect to http://");
DBG_OUTPUT_PORT.print(host);
DBG_OUTPUT_PORT.println(".local");
}
server.on("/list", HTTP_GET, printDirectory);
server.on("/edit", HTTP_DELETE, handleDelete);
server.on("/edit", HTTP_PUT, handleCreate);
server.on("/edit", HTTP_POST, []() {
returnOK();
}, handleFileUpload);
server.onNotFound(handleNotFound);
server.begin();
DBG_OUTPUT_PORT.println("HTTP server started");
if (SD.begin(SS)) {
DBG_OUTPUT_PORT.println("SD Card initialized.");
hasSD = true;
}
}
void loop(void) {
server.handleClient();
MDNS.update();
}
The code compiles without warnings and errors. Used environment:
Arduino IDE v 1.8.13
ESP8266 community edition v 2.6.3
windows machine
My guess is old ESP or Arduino libs - versions above.
The code is ok as a starter for own projects.
One starting tip:
Replace all Strings with char functionsor you will have stability problems later on (Heap fragmentation)
you have to remove "hasSD &&" from void handleNotFound function.
it worked for me.

observing for subset of event using jtapi provider

I am using cisco jtapi v7+ and investigating whether I can add a provider to only listen to certain (not all) events. However, the only call I see in the API is the following:
provider.addObserver(ProviderObserver);
I would like to avoid filtering events in my application and have it done through the API. Any thoughts/insight on this would be appreciated!
You must add CallObserver instance to address which you want listen, then filtering events. For example:
Address srcAddr = provider.getAddress(src);
co = new CallObserver() {
public void callChangedEvent(CallEv[] eventList) {
for (int i = 0; i < eventList.length; ++i) {
try {
if (eventList[i].getID() == TermConnRingingEv.ID) {
session.getBasicRemote().sendText("new_call");
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (eventList[i].getID() == ConnDisconnectedEv.ID) {
try {
System.out.println("Disconnected");
session.getBasicRemote().sendText("disconnected");
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (eventList[i] instanceof CallObservationEndedEv) {
System.out.println("Event: Call Observation Ended");
}
if (eventList[i] instanceof CiscoAddrOutOfServiceEv) {
System.out.println("Event: Address Out of service");
}
System.out.println("State: " + eventList[i].getCall().getState());
}
}
};
srcAddr.addCallObserver(co);

addautomtioneventhandler on web pages

I'm trying to add an automation event handler for a ui button. I've tested on desktop applications and it's working but I've a problem with buttons in web pages.In fact I can invoke them with InvokePattern.Invoke() but I don't see the handler working after that!
this is my code :
if ((wantedElement != null))
{
element = wantedElement;
buttonEvent = new AutomationEventHandler(close_event);
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, element,TreeScope.Element,buttonEvent );
object pattern;
if (wantedElement.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))
{
InvokePattern invokePattern = (InvokePattern)pattern;
invokePattern.Invoke();
}
}
...
private static void close_event(object sender, AutomationEventArgs e)
{
AutomationElement sourceElement;
try
{
sourceElement = sender as AutomationElement;
Console.WriteLine("button try");
}
catch (ElementNotAvailableException)
{
return;
}
if (e.EventId == InvokePattern.InvokedEvent)
{
// TODO Add handling code.
Console.WriteLine("button invoked");
}
else
{
// TODO Handle any other events that have been subscribed to.
Console.WriteLine("button event");
}
}

WP - How to constantly update my location

Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}