Trying to get C++/WinRT non UWP program to recognize bluetooth LE devices: specific failure at get_weak() (error:not defined) - windows-runtime

I'm taking a shot at using C++/WinRT to find and communicate with Bluetooth LE devices in a non-UWP app.
(I'm trying to avoid UWP, as there appear to be some constraints on what you can do with it, and it looks kind of bloated to me.)
My background is a lot of programming and releasing for small-group distribution old-fashioned C++ WinMain-based programming, as in Petzold's "Programming Windows 95". My experience has been using the Win32 API only.
Unfortunately for me, MS documentation indicates that Bluetooth LE is not supported in Win32, and only in WinRT. Thus, this forces me to use something like C++/WinRT to access the API.
So, I took a shot at it by downloading the only available example of bluetooth LE access in C++ which I know of at all, which is Microsoft's C++WinRT UWP example.
I got that running as one Visual Studio 2022 project, and, since I am looking for a non-UWP program, I tried putting the relevant stuff into another project, for which I used Microsoft VS2022's built-in template for a C++/WinRT Console. When I try to stick into that what appearVS says to be the key elements of the C++/WinRT UWP example, and make modifications to fix obvious problems, I have an error in the code which I have no idea how to fix: it is on the several get_weak() calls, which VS intellisense says are "undefined". (The compile also fails with unable to find main.g.h and main.g.cpp .
Here is the code:
File main.h:
#pragma once
#include "main.g.h"
class find_devs
{
find_devs() {};
private:
std::vector<Windows::Devices::Enumeration::DeviceInformation> UnknownDevices;
Windows::Devices::Enumeration::DeviceWatcher deviceWatcher{ nullptr };
event_token deviceWatcherAddedToken;
event_token deviceWatcherUpdatedToken;
event_token deviceWatcherRemovedToken;
event_token deviceWatcherEnumerationCompletedToken;
event_token deviceWatcherStoppedToken;
void StartBleDeviceWatcher();
void StopBleDeviceWatcher();
std::vector<Windows::Devices::Enumeration::DeviceInformation>::iterator FindUnknownDevices(hstring const& id);
fire_and_forget DeviceWatcher_Added(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo);
fire_and_forget DeviceWatcher_Updated(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
fire_and_forget DeviceWatcher_Removed(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
fire_and_forget DeviceWatcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const&);
fire_and_forget DeviceWatcher_Stopped(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const&);
};
and main.cpp:
#include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Devices::Enumeration;
#include "pch.h"
#include "main.h"
#include "main.g.cpp"
using namespace winrt;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Foundation;
namespace winrt
{
hstring to_hstring(DevicePairingResultStatus status)
{
switch (status)
{
case DevicePairingResultStatus::Paired: return L"Paired";
case DevicePairingResultStatus::NotReadyToPair: return L"NotReadyToPair";
case DevicePairingResultStatus::NotPaired: return L"NotPaired";
case DevicePairingResultStatus::AlreadyPaired: return L"AlreadyPaired";
case DevicePairingResultStatus::ConnectionRejected: return L"ConnectionRejected";
case DevicePairingResultStatus::TooManyConnections: return L"TooManyConnections";
case DevicePairingResultStatus::HardwareFailure: return L"HardwareFailure";
case DevicePairingResultStatus::AuthenticationTimeout: return L"AuthenticationTimeout";
case DevicePairingResultStatus::AuthenticationNotAllowed: return L"AuthenticationNotAllowed";
case DevicePairingResultStatus::AuthenticationFailure: return L"AuthenticationFailure";
case DevicePairingResultStatus::NoSupportedProfiles: return L"NoSupportedProfiles";
case DevicePairingResultStatus::ProtectionLevelCouldNotBeMet: return L"ProtectionLevelCouldNotBeMet";
case DevicePairingResultStatus::AccessDenied: return L"AccessDenied";
case DevicePairingResultStatus::InvalidCeremonyData: return L"InvalidCeremonyData";
case DevicePairingResultStatus::PairingCanceled: return L"PairingCanceled";
case DevicePairingResultStatus::OperationAlreadyInProgress: return L"OperationAlreadyInProgress";
case DevicePairingResultStatus::RequiredHandlerNotRegistered: return L"RequiredHandlerNotRegistered";
case DevicePairingResultStatus::RejectedByHandler: return L"RejectedByHandler";
case DevicePairingResultStatus::RemoteDeviceHasAssociation: return L"RemoteDeviceHasAssociation";
case DevicePairingResultStatus::Failed: return L"Failed";
}
return L"Code " + to_hstring(static_cast<int>(status));
}
}
// This scenario uses a DeviceWatcher to enumerate nearby Bluetooth Low Energy devices,
// displays them in a ListView, and lets the user select a device and pair it.
// This device will be used by future scenarios.
// For more information about device discovery and pairing, including examples of
// customizing the pairing process, see the DeviceEnumerationAndPairing sample.
#pragma region UI Code
#pragma endregion
#pragma region Device discovery
/// <summary>
/// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired).
/// Attaches event handlers to populate the device collection.
/// </summary>
void find_devs::StartBleDeviceWatcher()
{
// Additional properties we would like about the device.
// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
auto requestedProperties = single_threaded_vector<hstring>({ L"System.Devices.Aep.DeviceAddress", L"System.Devices.Aep.IsConnected", L"System.Devices.Aep.Bluetooth.Le.IsConnectable" });
// BT_Code: Example showing paired and non-paired in a single query.
hstring aqsAllBluetoothLEDevices = L"(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
Windows::Devices::Enumeration::DeviceInformation::CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind::AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcherAddedToken = deviceWatcher.Added({ get_weak(), &DeviceWatcher_Added });
deviceWatcherUpdatedToken = deviceWatcher.Updated({ get_weak(), &DeviceWatcher_Updated });
deviceWatcherRemovedToken = deviceWatcher.Removed({ get_weak(), &DeviceWatcher_Removed });
deviceWatcherEnumerationCompletedToken = deviceWatcher.EnumerationCompleted({ get_weak(), &DeviceWatcher_EnumerationCompleted });
deviceWatcherStoppedToken = deviceWatcher.Stopped({ get_weak(), &DeviceWatcher_Stopped });
// Start the watcher. Active enumeration is limited to approximately 30 seconds.
// This limits power usage and reduces interference with other Bluetooth activities.
// To monitor for the presence of Bluetooth LE devices for an extended period,
// use the BluetoothLEAdvertisementWatcher runtime class. See the BluetoothAdvertisement
// sample for an example.
deviceWatcher.Start();
}
/// <summary>
/// Stops watching for all nearby Bluetooth devices.
/// </summary>
void find_devs::StopBleDeviceWatcher()
{
if (deviceWatcher != nullptr)
{
// Unregister the event handlers.
deviceWatcher.Added(deviceWatcherAddedToken);
deviceWatcher.Updated(deviceWatcherUpdatedToken);
deviceWatcher.Removed(deviceWatcherRemovedToken);
deviceWatcher.EnumerationCompleted(deviceWatcherEnumerationCompletedToken);
deviceWatcher.Stopped(deviceWatcherStoppedToken);
// Stop the watcher.
deviceWatcher.Stop();
deviceWatcher = nullptr;
}
}
std::vector<Windows::Devices::Enumeration::DeviceInformation>::iterator FindUnknownDevices(hstring const& id)
{
}
fire_and_forget find_devs::DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
}
fire_and_forget find_devs::DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
if (deviceInfo != UnknownDevices.end())
{
deviceInfo->Update(deviceInfoUpdate);
// If device has been updated with a friendly name it's no longer unknown.
}
}
}
fire_and_forget find_devs::DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
if (deviceInfo != UnknownDevices.end())
{
UnknownDevices.erase(deviceInfo);
}
}
}
fire_and_forget find_devs::DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, IInspectable const&)
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
}
}
fire_and_forget DeviceWatcher_Stopped(DeviceWatcher sender, IInspectable const&)
{
// Access this->deviceWatcher on the UI thread to avoid race conditions.
auto lifetime = get_strong();
co_await resume_foreground(Dispatcher());
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
}
}
#pragma endregion
int main()
{
init_apartment();
Uri uri(L"http://aka.ms/cppwinrt");
printf("Hello, %ls!\n", uri.AbsoluteUri().c_str());
}
and, for completeness, this is pch.h
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Devices.Enumeration.h>
The code is, I know, not complete. I haven't created a DeviceWatcher, etc., but I am apparently blocked in that I can't get the get_weaks() to pass intellisense screening or to compile.
Any guidance from people who know about this stuff would be great.
Bear in mind: I, myself, pretty much don't know what's going on. Due to the complexity, from my Win32 Petzold-style background, of the example MS C++/WinRT UWP example. It has all kinds of stuff in the Solution Explorer. There are .idl files, a packages.config, a bunch of different Xaml files, some generated c++ files. All this stuff is beyond my understanding, and I have not been able to pick it up with any speed from the MS documentation I can find.
(All I have figured out is that C++/WinRT is some sort of a thing where there are generated header and perhaps other files that are supposed to make your C++ code look like it's directly accessing WinRT classes. And, I have seen MS write that you can use winRT in non-UWP applications. Otherwise, I am lost.)

Related

Why is CreateFileAsync() continuation not executed?

In the below code, the continuation of CreateFileAsync() neither prints nor accesses pdone. However, the zero-length file, Hello.txt, is created.
auto pdone = make_shared<bool>(false);
create_task(folderLocal->CreateFileAsync("Hello.txt", CreationCollisionOption::ReplaceExisting)).then([pdone](StorageFile ^file) {
OutputDebugString(L"In CreateFileAsync continuation!\n");
*pdone = true;
});
create_task([pdone]{
OutputDebugString(L"In my task!\n");
});
create_async([pdone]{
OutputDebugString(L"In my async!\n");
});
while (!*pdone) {}
OutputDebugString(L"Done!\n");
In the debugger:
In my task!
In my async!
I'm not very familiar with debugging WinRT threads yet, but I do not see any obvious exception or any reason the continuation to the async operation should not execute. The target platform is the Hololens emulator.
Any thoughts are appreciated.
Thanks!
Harry's comment above is most likely the culprit - if you initiated this on a UI thread then by default the C++ tasks library (PPL) will try to schedule the completion on the same thread. This will never happen if you are spinning the thread waiting for the completion to happen (classic deadlock).
If you must do this (although you really should try and avoid it) you need to use a "continuation context" to tell PPL to run the continuation somewhere else.
Here's an example. First, basic XAML (just paste inside the Grid of a blank C++ XAML project):
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Hang the UI thread" Click="Hang"/>
<Button Content="Do not do this" Click="DoNotDoThis"/>
</StackPanel>
And the code (just paste after the MainPage constructor):
using namespace Windows::Storage;
using namespace concurrency;
void DoIt(task_continuation_context& context)
{
auto folder = ApplicationData::Current->LocalFolder;
auto done = std::make_shared<bool>(false);
create_task(folder->CreateFileAsync(L"x", CreationCollisionOption::ReplaceExisting))
.then([done](StorageFile^ file) mutable
{
OutputDebugString(L"Done creating file\n");
*done = true;
}, context);
OutputDebugString(L"Going to wait... DO NOT DO THIS IN PRODUCTION CODE!\n");
while (!*done)
;
OutputDebugString(L"Done waiting\n");
}
void MainPage::Hang(Platform::Object^ sender, RoutedEventArgs^ e)
{
OutputDebugString(L"Starting Hang\n");
// The default context == the UI thread (if called from UI)
DoIt(task_continuation_context::use_default());
OutputDebugString(L"Ending Hang\n");
}
void MainPage::DoNotDoThis(Platform::Object^ sender, RoutedEventArgs^ e)
{
OutputDebugString(L"Starting DoNotDoThis\n");
// An arbitrary context will pick another thread (not the UI)
DoIt(task_continuation_context::use_arbitrary());
OutputDebugString(L"Ending DoNotDoThis\n");
}
As noted, you shouldn't do this. If you need synchronous File I/O, and you're accessing files in your own package, use the Win32 API CreateFile2. If you need to access files outside of your package (eg, from a file picker or the photos library) you should use a fully-async programming approach.
I believe using task_continuation_context::use_arbitarty() is the correct way of doing this, however I think microsoft suggests using it slightly differently unless i have misunderstood this link (scroll all the way to the bottom): https://msdn.microsoft.com/en-us/library/hh750082.aspx
create_task(folderLocal->CreateFileAsync("Hello.txt", CreationCollisionOption::ReplaceExisting)).then([pdone](StorageFile ^file) {
OutputDebugString(L"In CreateFileAsync continuation!\n");
*pdone = true;
}, task_continuation_context::use_arbitrary());

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

windows 8 app FileOpenPicker np file info

I'm trying to get some file information about a file the user select with the FileOpenPicker, but all the information like the path and name are empty. When I try to view the object in a breakpoint I got the following message:
file = 0x03489cd4 <Information not available, no symbols loaded for shell32.dll>
I use the following code for calling the FileOpenPicker and handeling the file
#include "pch.h"
#include "LocalFilePicker.h"
using namespace concurrency;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
const int LocalFilePicker::AUDIO = 0;
const int LocalFilePicker::VIDEO = 1;
const int LocalFilePicker::IMAGES = 2;
LocalFilePicker::LocalFilePicker()
{
_init();
}
void LocalFilePicker::_init()
{
_openPicker = ref new FileOpenPicker();
_openPicker->ViewMode = PickerViewMode::Thumbnail;
}
void LocalFilePicker::askFile(int categorie)
{
switch (categorie)
{
case 0:
break;
case 1:
_openPicker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
_openPicker->FileTypeFilter->Append(".mp4");
break;
case 2:
break;
default:
break;
}
create_task(_openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
int n = 0;
wchar_t buf[1024];
_snwprintf_s(buf, 1024, _TRUNCATE, L"Test: '%s'\n", file->Path);
OutputDebugString(buf);
}
else
{
OutputDebugString(L"canceled");
}
});
}
Can anybody see whats wrong with the code or some problems with settings for the app why it isn't work as expected.
First an explanation why you are having trouble debugging, this is going to happen a lot more when you write WinRT programs. First, do make sure that you have the correct debugging engine enabled. Tools + Options, Debugging, General. Ensure that the "Use Managed Compatibility Mode" is turned off.
You can now inspect the "file" option, it should resemble this:
Hard to interpret of course. What you are looking at is a proxy. It is a COM term, a wrapper for COM objects that are not thread-safe or live in another process or machine. The proxy implementation lives in shell32.dll, thus the confuzzling diagnostic message. You can't see the actual object at all, accessing its properties requires calling proxy methods. Something that the debugger is not capable of doing, a proxy marshals the call from one thread to another, that other thread is frozen while the debugger break is active.
That makes you pretty blind, in tough cases you may want to write a littler helper code to store the property in a local variable. Like:
auto path = file->Path;
No trouble inspecting or watching that one. You should now have confidence that there's nothing wrong with file and you get a perfectly good path. Note how writing const wchar_t* path = file->Path; gets you a loud complaint from the compiler.
Which helps you find the bug, you can't pass a Platform::String to a printf() style function. Just like you can't with, say, std::wstring. You need to use an accessor function to convert it. Fix:
_snwprintf_s(buf, 1024, _TRUNCATE,
L"Test: '%s'\n",
file->Path->Data());

Windows phone 8 pjsip library integration

Im pretty much new in sip development and trying to implement a windows phone 8 client using pjsip.
ive build the sample application from pjsip ,which creates pjsua app with telnet connectivity.
Right now ,what i dont get is,how will i use this library and integrate in my app without telnet,
i just need to put a manual dial pad and call from there,to accomplish this,what is going to be the procedure?
pjsip for android or iphone has two sample application ,csipsimple and siphon ,but pjsip for windows phone 8 has no application like this.
any help regarding the way to go ahead would be very helpful.
Thanks
Since you mention that you've tried the windows phone telnet app sample, I assume you've downloaded the PJSIP winphone source as mentioned in their wp8 getting started guide. To create a simple app that perform outgoing and receive incoming call as you mentioned, you can simply reuse this winphone project.
Open the winphone project and do:
Create new Windows Phone project and set this as startup project (let's call this project SIP_UI). This will serve as the UI. You can just create a "Call button" that will perform outgoing call later.
Follow the existing pjsua_wp WMAppManifest.xml settings for this SIP_UI. Especially the capabilities part. Your app won't work if you simply use the default settings.
Create new Windows Phone Runtime project (let's call this SIP_WINPRT). Create a class and a method inside of this class that will perform the actual call later.
Change property setting for SIP_WINPRT (right click SIP_WINPRT project -> property) by following the existing pjsua_wp_backend's. Change especially on the References, Additional include directories, and preprocessor definitions. Adjust the path accordingly.
Search for simple_pjsua.c in the winphone sample. And try to implement that in the class you've created in SIP_WINPRT. Sample that I've created:
#include "pch.h"
#include "backend.h"
#include "pjsua.h"
#define SIP_DOMAIN "dogdomain"
#define SIP_USER "dog"
#define SIP_PASSWD "dog"
using namespace backend;
using namespace Platform;
SipletRuntimeComponent::SipletRuntimeComponent()
{
}
/* Display error and exit application */
static void error_exit(const char *title, pj_status_t status)
{
//pjsua_perror(THIS_FILE, title, status);
pjsua_destroy();
exit(1);
}
/* Callback called by the library upon receiving incoming call */
static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id,
pjsip_rx_data *rdata)
{
pjsua_call_info ci;
PJ_UNUSED_ARG(acc_id);
PJ_UNUSED_ARG(rdata);
pjsua_call_get_info(call_id, &ci);
//PJ_LOG(3,(THIS_FILE, "Incoming call from %.*s!!",
// (int)ci.remote_info.slen,
// ci.remote_info.ptr));
/* Automatically answer incoming calls with 200/OK */
pjsua_call_answer(call_id, 200, NULL, NULL);
}
/* Callback called by the library when call's media state has changed */
static void on_call_media_state(pjsua_call_id call_id)
{
pjsua_call_info ci;
pjsua_call_get_info(call_id, &ci);
if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) {
// When media is active, connect call to sound device.
pjsua_conf_connect(ci.conf_slot, 0);
pjsua_conf_connect(0, ci.conf_slot);
}
}
/* Callback called by the library when call's state has changed */
static void on_call_state(pjsua_call_id call_id, pjsip_event *e)
{
pjsua_call_info ci;
PJ_UNUSED_ARG(e);
pjsua_call_get_info(call_id, &ci);
//PJ_LOG(3,(THIS_FILE, "Call %d state=%.*s", call_id,
// (int)ci.state_text.slen,
// ci.state_text.ptr));
}
int SipletRuntimeComponent::SipCall(int address)
{
/* Create pjsua */
pj_status_t status;
status = pjsua_create();
if (status != PJ_SUCCESS){
//Error in pjsua_create()
return -1;
}
/* Validate the URL*/
char url[50] = "sip:cat:cat#catdomain:5060";
status = pjsua_verify_url(url);
if (status != PJ_SUCCESS){
//Invalid URL given
return -1;
}
/* Init pjsua */
{
pjsua_config cfg;
pjsua_logging_config log_cfg;
pjsua_config_default(&cfg);
cfg.cb.on_incoming_call = &on_incoming_call;
cfg.cb.on_call_media_state = &on_call_media_state;
cfg.cb.on_call_state = &on_call_state;
pjsua_logging_config_default(&log_cfg);
log_cfg.console_level = 4;
status = pjsua_init(&cfg, &log_cfg, NULL);
if (status != PJ_SUCCESS){
//Error in pjsua_init()
pjsua_destroy();
return -1;
}
}
/* Add UDP transport. */
{
pjsua_transport_config cfg;
pjsua_transport_config_default(&cfg);
cfg.port = 5060;
status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL);
if (status != PJ_SUCCESS){
//Error creating transport
pjsua_destroy();
return -1;
}
}
/* Initialization is done, now start pjsua */
status = pjsua_start();
if (status != PJ_SUCCESS){
//Error starting pjsua
pjsua_destroy();
return -1;
}
/* Register to SIP server by creating SIP account. */
pjsua_acc_id acc_id;
{
pjsua_acc_config cfg;
pjsua_acc_config_default(&cfg);
cfg.id = pj_str("sip:" SIP_USER "#" SIP_DOMAIN);
cfg.reg_uri = pj_str("sip:" SIP_DOMAIN);
cfg.cred_count = 1;
cfg.cred_info[0].realm = pj_str(SIP_DOMAIN);
cfg.cred_info[0].scheme = pj_str("digest");
cfg.cred_info[0].username = pj_str(SIP_USER);
cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
cfg.cred_info[0].data = pj_str(SIP_PASSWD);
status = pjsua_acc_add(&cfg, PJ_TRUE, &acc_id);
if (status != PJ_SUCCESS){
//Error adding account
pjsua_destroy();
return -1;
}
}
/* make call to the URL. */
pj_str_t uri = pj_str(url);
status = pjsua_call_make_call(acc_id, &uri, 0, NULL, NULL, NULL);
if (status != PJ_SUCCESS){
//Error making call
pjsua_destroy();
return -1;
}
return address + 1;
}
Add SIP_WINPRT as a reference in SIP_UI project.
Call the SIP_WINPRT when the Call button is pressed.
Well, your problems doesn't seem to be related with PJSip but with UI Development.
I suggest that you create your UI (using XAML/C# or XAML/C++ and don't forget it must be a Windows Phone 8.0 Silverlight project). Then you start referencing the PJSip library.
Hope it helps!

Always move to specific uiviewcontroller

I have a IOS app, that uses a network connection, and at times, it looses this network connection, whenever it does, I want the app to move back to a specific UIViewController.. What is the best way to achieve this?
Can I do this from the appDelegate?
Are you using the Reachability class described in the Apple documentation? If not, you should take a look at it. It will give you network status, including whether you are connected to the internet. It has a notification of network status change so you can put an observer in you app delegate or anywhere else you need it to accomplish your objective.
There is a lot of help already available on the web with examples on how to use Reachability, and this one may be something you can start with.
Update
Raachability change notifications can be used to inform your app when the connection is lost or restored. See the notification statement in the code below for the Reachability class;
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, #"info was NULL in ReachabilityCallback");
NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], #"info was wrong class in ReachabilityCallback");
//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
// in case someon uses the Reachablity object in a different thread.
NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
Reachability* noteObject = (Reachability*) info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
[myPool release];
}
For this to work you have to call startNotifier:
- (BOOL) startNotifier
{
BOOL retVal = NO;
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
retVal = YES;
}
}
return retVal;
}