I'm using the Spinnaker SDK for controlling FLIR cameras. If at any moment the application crashes with a camera being used, every next execution of the application throws an AccessException, like:
Spinnaker::GenApi::CommandNode::Execute: Message = GenICam::AccessException= Node is not writable. : AccessException thrown in node 'UserSetLoad' while calling 'UserSetLoad.Execute()'
The only solution I've found so far is to unplug and plug in the camera, but this is not an acceptable solution in some environments where the application is going to be used.
Here a sample code (not fully compilable since it is extracted from a larger codebase, but gives you an idea of the workflow):
// System instance is prepared before using the camera
Spinnaker::SystemPtr m_system = Spinnaker::System::GetInstance();
// Method in class that initializes the camera
bool initCamera(int index)
{
SmartCameraList cameras(m_system->GetCameras());
const auto cameras_count = cameras.GetSize();
if (cameras_count < 1) { return false; }
if (index >= (int)cameras_count) { return false; }
m_camera = cameras[index];
if (!m_camera) { return false; }
if (m_camera->IsInitialized()) { return false; } // passes
m_camera->DeInit(); // does nothing
m_camera->Init();
if (!m_camera->IsInitialized()) { return false; } // passes
// Default properties
try {
m_camera->UserSetSelector.SetValue(UserSetSelector_Default);
m_camera->UserSetDefault.SetValue(UserSetDefault_Default);
m_camera->UserSetLoad.Execute(); //< thrown here
m_camera->BalanceWhiteAuto.SetValue(BalanceWhiteAuto_Continuous);
m_camera->SensorShutterMode.SetValue(SensorShutterMode_Global);
} catch (Spinnaker::Exception e) {
std::cout << e.GetFullErrorMessage() << '\n';
return false;
}
return true;
}
// m_system->ReleaseInstance() is called when the application finishes using the camera
As you can see, camera is correctly initialized, but it seems that something else is holding the camera.
I've checked in official forums, looking for more generic GenICam related issues and nothing.
Is there any way to reset the camera before using it?
I solved this issue by connecting and disconnecting to the camera SW wise.
Starting capture by launching the following code in a separate thread:
void Cam::MainThread(){
m_cameraHandler->BeginAcquisition();
while(m_threadCtx.wait(ZERO_DURATION)){ //sleepwait
try {
ImagePtr pResultImage = m_cameraHandler->GetNextImage(1000);
const size_t width = pResultImage->GetWidth();
const size_t height = pResultImage->GetHeight();
cv::Mat_<uint16_t> img(height,width);
memcpy(img.data,pResultImage->GetData(),pResultImage->GetWidth()*pResultImage->GetHeight()*sizeof(uint16_t));
if (pResultImage->IsIncomplete())
cout << "Error";
else {
pResultImage->Release();
}
}
catch (Spinnaker::Exception& e)
{
CLerror << "Error: " << e.what();
}
}
}
Then stopping the camera
m_threadCtx.stop();
m_pMainThread->join();
m_cameraHandler->EndAcquisition();
m_cameraHandler->DeInit();
m_cameraHandler = nullptr;
m_spCameraList = nullptr;
delete(m_pMainThread);
After that you can open the camera and upload the file again and it should work.
worked for me
Related
My game snapshot Attachment> Blockquote
My canvas constructs
public class DrawingView4 extends View{
DrawingView4(Context context4)
{
super(context4);
}
#Override protected void onDraw(Canvas canvas4)
{
int tile4=0;
if (DoneDrawFacilities && doneloading) {
}
else {
for (int i4=0; i4< 17 && notfixingorientation; i4++){
if (i4< 16) {
for (int ii4=0; ii4 < 16; ii4++){
try {
//Checking the data of all spots of the game map from package directory.
//Then Draw in canvas if the data of the spot occupied by type of human and core facilities,
FacilityList = new Gson().fromJson(FileUtil.readFile(FileUtil.getPackageDataDir(getApplicationContext()).concat("/GameResource/Tile".concat(String.valueOf((long)(tile4 + 1)).concat(".data")))), new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
if (FacilityList.get((int)0).get("Type").toString().equals("Human")) {
canvas4.drawBitmap(BitmapFactory.decodeFile(AllObjects.getString(String.valueOf((long)(tile4)), "")),null,new Rect(ii4*120, i4*120, 120*(ii4+1),120*(i4+1)), null);
}
if (FacilityList.get((int)0).get("Type").toString().equals("Core")) {
if (FacilityList.get((int)0).get("Name").toString().equals("Arena")) {
canvas4.drawBitmap(BitmapFactory.decodeFile(AllObjects.getString(String.valueOf((long)(tile4)), "")),null,new Rect(7*120, 7*120, 120*(8+1),120*(8+1)), null);
}
else {
}
}
} catch (Exception e) {
}
FacilityList.clear();
tile4++;
}
}
else {
DoneDrawFacilities = true;
}
}
}
}}
Blockquote
My Relocate button
//I use sharepreference called AllObjects rather than a list and I Only update the path of objects in specific tile in sharedpreference such as in variable 1, 2, etc. and then re-draw using this code below, next time I update the objects path and get this object path from the same json file in the package directory. Too decode to Bitmap and then Draw in canvas.
//Some other code are removed that just updating some data in specific file directory.
AA_structures_facilities.removeAllViews();
AA_structures_facilities.addView(new DrawingView4(GameActivity.this));
// But It freezes the screen or stop me from touching the touch event in a second everytime I update new canvas.
//WHILE MY touchevent is hundled in the parent LinearLayout where the canvas is placed.
Hello, if i try to build this code here, ill get a error and dont know what to do.
void wxsocket_test_finalFrame::OnServerStart(wxCommandEvent& WXUNUSED(event))
{
// Create the address - defaults to localhost:0 initially
wxIPV4address addr;
addr.Service(3000);
// Create the socket. We maintain a class pointer so we can
// shut it down
m_server = new wxSocketServer(addr);
// We use Ok() here to see if the server is really listening
if (! m_server->Ok())
{
return;
}
// Set up the event handler and subscribe to connection events
m_server->SetEventHandler(*this, SERVER_ID);
m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
m_server->Notify(true);
}
void wxsocket_test_finalFrame::OnServerEvent(wxSocketEvent& WXUNUSED(event))
{
// Accept the new connection and get the socket pointer
wxSocketBase* sock = m_server->Accept(false);
// Tell the new socket how and where to process its events
sock->SetEventHandler(*this, SOCKET_ID);
sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
sock->Notify(true);
}
void wxsocket_test_finalFrame::OnSocketEvent(wxSocketEvent& event)
{
wxSocketBase *sock = event.GetSocket();
// Process the event
switch(event.GetSocketEvent())
{
case wxSOCKET_INPUT:
{
char buf[10];
// Read the data
sock->Read(buf, sizeof(buf));
// Write it back
sock->Write(buf, sizeof(buf));
// We are done with the socket, destroy it
sock->Destroy();
break;
}
case wxSOCKET_LOST:
{
sock->Destroy();
break;
}
}
}
\wxsocket_test_finalMain.cpp|99|error: 'm_server' was not declared in this scope|
OS: Windows
Compiler: gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
im a bloody newbie and cant figure out what is happening here, someone has a clue ?
I really want to know how do I can update the position of the user in the map while the UWP app was running in bakground
Here is my code right now
private async void PinPoints()
{
//Pin point to the map
Windows.Devices.Geolocation.Geopoint position = await Library.Position();
double lat = position.Position.Latitude;
double lon = position.Position.Longitude;
//Geoposition alttest = await Library.Temp();
//alt = alttest.Coordinate.Altitude;
DependencyObject marker = Library.Marker(""
//+ Environment.NewLine + "Altitude " + alt
);
Display.Children.Add(marker);
Windows.UI.Xaml.Controls.Maps.MapControl.SetLocation(marker, position);
Windows.UI.Xaml.Controls.Maps.MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 0.5));
Display.LandmarksVisible = true;
Display.ZoomLevel = 16;
Display.Center = position;
}
This function will pinpoint the current location for me but it will do only when user open this page due to I've put it in the public Map() {}
Current : Get the location when open map page and when I walk the map still be the same place
What I want : The position keep changing while I move on and also run on background (If application is close location data still changed)
Is there any code to solve this location problem if I have to add code where should I fix and what should I do?
Additional now I perform the background (Not sure is it work or not) by create the Window Runtime Component (Universal) with class like this
*I already put this project as the reference of the main one
namespace BackgroundRunning
{
public sealed class TaskBG : IBackgroundTask
{
BackgroundTaskDeferral _deferral = null;
Accelerometer _accelerometer = null;
Geolocator _locator = new Geolocator();
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
try
{
// force gps quality readings
_locator.DesiredAccuracy = PositionAccuracy.High;
taskInstance.Canceled += taskInstance_Canceled;
_accelerometer = Windows.Devices.Sensors.Accelerometer.GetDefault();
_accelerometer.ReportInterval = _accelerometer.MinimumReportInterval > 5000 ? _accelerometer.MinimumReportInterval : 5000;
_accelerometer.ReadingChanged += accelerometer_ReadingChanged;
}
catch (Exception ex)
{
// Add your chosen analytics here
System.Diagnostics.Debug.WriteLine(ex);
}
}
void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_deferral.Complete();
}
async void accelerometer_ReadingChanged(Windows.Devices.Sensors.Accelerometer sender, Windows.Devices.Sensors.AccelerometerReadingChangedEventArgs args)
{
try
{
if (_locator.LocationStatus != PositionStatus.Disabled)
{
try
{
Geoposition pos = await _locator.GetGeopositionAsync();
}
catch (Exception ex)
{
if (ex.HResult != unchecked((int)0x800705b4))
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
public void Dispose()
{
if (_accelerometer != null)
{
_accelerometer.ReadingChanged -= accelerometer_ReadingChanged;
_accelerometer.ReportInterval = 0;
}
}
}
}
Your Solution :
Make 3 projects in your solution.
1> Background Task "references App_Code"
2> App_Code "contains calculations,mostly Backend Code"
3> Map(Main Project) "references App_Code"
Register a background Task to your project and specify the time interval after which it should run again
Scenario 1> App Open,User Requests Update
Trigger Your background Task from code behind.
Scenario 2> App Closed,Not Being Used
Run your background task!
So basically keep your backgroundTask simple(make it a class in whose run method you just call the proper App_Code Classes Method) and all calculations that you want to happen in the background keep them in App_Code. Also, if I am no wrong the minimum interval between which a background Task is triggered by itself cannot be set below 15 minutes.
For real-time you could look at SignalR ( can't help any further here)
I want to know of any pure QML way to find out whether the application is in the background or not and then accordingly stop or play music. In meego the alternate way to do is through the PlatformWindow Element but it does not exist in Symbian QML. Help needed please
Finally I got it working :) and i did it though Qt way... here are the steps
1) Create a class MyEventFilter
class myEventFilter : public QObject
{
bool eventFilter(QObject *obj, QEvent *event) {
switch(event->type()) {
case QEvent::WindowActivate:
emit qmlvisiblechange(true);
qDebug() << "Window activated";
bis_foreground=true;
return true;
case QEvent::WindowDeactivate:
emit qmlvisiblechange(false);
qDebug() << "Window deactivated";
bis_foreground=false;
return true;
default:
return false;
}
}
void dosomething();
private:
int something;
public:
bool bis_foreground;
Q_OBJECT
public slots:
Q_INVOKABLE QString checkvisibility() {
if (bis_foreground==true) return "true";
else return "false";
}
signals:
void qmlvisiblechange(bool is_foreground);
};
2) Then in main.cpp include this file include the class and add setContext propery like this
context->setContextProperty("myqmlobject", &ef);
3) in qml file call it like this:
Item {
id: name
Connections
{
target:myqmlobject
onQmlvisiblechange:
{
if(is_foreground)
{
//dont do anything...
}
else
{
playSound.stop()
}
}
}
}
Enjoy :)
Why do you need a pure QML way?
You can detect if an application has been sent to the background by installing an event filter.
Check: http://www.developer.nokia.com/Community/Wiki/Detecting_when_a_Qt_application_has_been_switched_to_the_background_and_when_resumed
For a "pure" QML way, there is the Symbian QML element:
http://doc.qt.nokia.com/qt-components-symbian/qml-symbian.html
It has a foreground property that indicates whether the app is in the foreground or in the background. You can try connecting to onForegroundChanged.
From the documentation, the Symbian element is not "creatable". It exists as a context property named symbian. So a sample usage would be:
import QtQuick 1.1
import com.nokia.symbian 1.1
PageStackWindow {
id: window
initialPage: MainPage {tools: toolBarLayout}
showStatusBar: true
showToolBar: true
function appForegroundChanged() {
console.log("Foreground: " + symbian.foreground)
}
function appCurrentTimeChanged() {
console.log("Current time: " + symbian.currentTime)
}
Component.onCompleted: {
symbian.currentTimeChanged.connect(appCurrentTimeChanged)
symbian.foregroundChanged.connect(appForegroundChanged)
}
ToolBarLayout {
id: toolBarLayout
ToolButton {
flat: true
iconSource: "toolbar-back"
onClicked: window.pageStack.depth <= 1 ? Qt.quit() : window.pageStack.pop()
}
}
}
I've just started using NAudio (1.4) solely for MP3 playback. I've been working off the documentation and the source code for the samples. Currently I have this in a class:
IWavePlayer waveOutDevice;
WaveStream mainOutputStream;
WaveChannel32 volumeStream;
public AudioPlaybackService() : base() {
waveOutDevice = new WasapiOut(AudioClientShareMode.Shared, 100);
}
public bool LoadTrack(string trackPath, float volume)
{
if (!File.Exists(trackPath))
return false;
try
{
mainOutputStream = new Mp3FileReader(trackPath);
volumeStream = new WaveChannel32(mainOutputStream);
volumeStream.Volume = volume;
waveOutDevice.Init(mainOutputStream);
}
catch (Exception e)
{
Logger.Error("Failed to load track for playback {0} :: {1}", trackPath, e.ToString());
return false;
}
return true;
}
public bool PlayTrack()
{
if (waveOutDevice == null || waveOutDevice.PlaybackState == PlaybackState.Playing)
return false;
waveOutDevice.Play();
return true;
}
public bool StopTrack()
{
if (waveOutDevice == null || waveOutDevice.PlaybackState == PlaybackState.Stopped)
return false;
waveOutDevice.Stop();
mainOutputStream.CurrentTime = TimeSpan.Zero;
return true;
}
This loads and plays my test track fine, my issue is with the Stop() function. Firstly should I need to reset the CurrentTime property after calling Stop()? Currently it acts more like a pause button i.e. it resumes the track in the same place it was "stopped". If I do need to reset the CurrentTime I now have a problem where if I click stop, the track stops, but if I click play again afterwards I get a little leftover noise before the track starts again.
Looking at the source code of one of the samples all it does is call Stop().
In our use of naudio, we never stop the audio. Any stop-like functionality causes a silent waveform (zeroes) to be fed to the wave out. This was mainly due to instability in naudio when stopping and starting too frequently, but it also prevents the "leftover buffer" problem.