WxSocket (Was not declared in this scope) - wxwidgets

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 ?

Related

Automatically pausing/continuing a service when OS suspends

I made a Windows Service process that can be started/stopped/paused/continued.
The service is created with CreateService() and the service starts a service controller with RegisterServiceCtrlHandlerExA().
Even though the service can subscribe to power setting notifications using RegisterPowerSettingNotification() I find that these only represent events like battery/mains for laptops, and such. Not for suspend/sleep of the OS.
How can I tell the SCM to automatically pause my service before the OS suspends/sleeps? And continue my service after it wakes up again?
This requires calling the PowerRegisterSuspendResumeNotification() function.
For this, you need to #include <powrprof.h> and link against powrprof.lib.
The callback itself looks like:
static ULONG DeviceNotifyCallbackRoutine
(
PVOID Context,
ULONG Type, // PBT_APMSUSPEND, PBT_APMRESUMESUSPEND, or PBT_APMRESUMEAUTOMATIC
PVOID Setting // Unused
)
{
LOGI("DeviceNotifyCallbackRoutine");
if (Type == PBT_APMSUSPEND)
{
turboledz_pause_all_devices();
LOGI("Devices paused.");
}
if (Type == PBT_APMRESUMEAUTOMATIC)
{
turboledz_paused = 0;
LOGI("Device unpaused.");
}
return 0;
}
static DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS notifycb =
{
DeviceNotifyCallbackRoutine,
NULL,
};
And then register it with:
HPOWERNOTIFY registration;
const DWORD registered = PowerRegisterSuspendResumeNotification
(
DEVICE_NOTIFY_CALLBACK,
&notifycb,
&registration
);
if (registered != ERROR_SUCCESS)
{
const DWORD err = GetLastError();
LOGI("PowerRegisterSuspendResumeNotification failed with error 0x%lx", err);
}

boost::asio: how can I make some clients listen to server and other client read/write to server at the same time

I am a novice about boost::asio, I write a server, some clients can connect to it and keep listening.
class socket_server {
public:
~socket_server() { io_context.stop(); };
int server_process();
private:
boost::asio::io_context io_context;
};
int socket_server::server_process() {
try {
unlink("/var/run/socket");
server s(io_context, "/var/run/socket");
INFO("server_process, start run\n");
io_context.run();
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
class server {
public:
server(boost::asio::io_context &io_context, const std::string &file)
: acceptor_(io_context, stream_protocol::endpoint(file)), socket_id_(0) {
do_accept();
}
private:
void do_accept();
stream_protocol::acceptor acceptor_;
int socket_id_;
};
void server::do_accept() {
INFO("do accept\n");
acceptor_.async_accept(
[this](std::error_code ec, stream_protocol::socket socket) {
if (!ec) {
INFO("new session create\n");
std::make_shared<session>(std::move(socket), socket_id_++)->start();
}
do_accept();
});
}
class session : public std::enable_shared_from_this<session> {
public:
session(stream_protocol::socket sock, int socket_id)
: socket_(std::move(sock)), socket_id_(socket_id) {}
~session() { socket_id_--; }
void start();
private:
void do_read();
void do_write(std::array<char, 1024> data);
int get_id() { return socket_id_; }
// The socket used to communicate with the client.
stream_protocol::socket socket_;
// Buffer used to store data received from the client.
std::array<char, 1024> data_;
int socket_id_;
};
void session::start() { do_read(); }
void session::do_read() {
INFO("in do_read\n");
auto self(shared_from_this());
socket_.async_read_some(
boost::asio::buffer(data_),
[this, self](std::error_code ec, std::size_t length) {
if (!ec) {
if (request.find("listen") != std::string::npos) {
std::unique_lock<std::mutex> lock(unsol_mutex);
unsol_cond.wait(lock)
do_write(get_unsol_data());
} else {
std::unique_lock<std::mutex> lock(send_mutex);
if (send_cond.wait_for(lock, std::chrono::seconds(2)) ==
std::cv_status::timeout) {
ERROR("response time out\n");
}
do_write(get_write_data());
}
}
});
}
In do_read(), I found when a client is listening (block in unsol_cond.wait(lock)), another client can not go to do_read().
Is it due to make_shared session? Is there a better implementation suggestion?
Thanks~
You're using blocking synchronization primitives in async code. That's an anti-pattern.
Firstly, as you noticed, the blocking operations will prevent the event loop from progressing.
Secondly, holding locks across async calls is often a bug (it doesn't guard the critical execution during execution of the async operation).
For simple integration with Asio proactor model, you can often
use a strand instead.
Under the hood, it will end up using mutexes, just like now, but only
if the concurrency model requires it. That mainly depends on the
execution context used and/or how many threads are running the
services.
Use a queue with a async send-chain. I have quite a few answers on this site that show you how to do that.
I would gladly demonstrate, but the code is too incomplete, and the naming doesn't really give me an idea what things mean ("listen"/"unsol"?, nothing ever signals those conditions so... hard to guess what they do in reality)

"Node is not writable" exception after a camera crash

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

UDP server crashes when receiving datagram

I'm discovering Dart language. To train myself, I try to code a simple UDP server that logs every datagram received.
Here's my code so far:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
class UDPServer {
static final UDPServer _instance = new UDPServer._internal();
// Socket used by the server.
RawDatagramSocket _udpSocket;
factory UDPServer() {
return _instance;
}
UDPServer._internal();
/// Starts the server.
Future start() async {
await RawDatagramSocket
.bind(InternetAddress.ANY_IP_V4, Protocol.udpPort, reuseAddress: true)
.then((RawDatagramSocket udpSocket) {
_udpSocket = udpSocket;
_udpSocket.listen((RawSocketEvent event) {
switch (event) {
case RawSocketEvent.READ:
_readDatagram();
break;
case RawSocketEvent.CLOSED:
print("Connection closed.");
break;
}
});
});
}
void _readDatagram() {
Datagram datagram = _udpSocket.receive();
if (datagram != null) {
String content = new String.fromCharCodes(datagram.data).trim();
String address = datagram.address.address;
print('Received "$content" from $address');
}
}
}
It works partially great... After logging some messages, it just crashes. The number varies between 1 and ~5. And IDEA just logs Lost connection to device., nothing more. I tried to debug but didn't find anything.
Does anyone have an idea why it crashes? Many thanks in advance.
EDIT: I forgot to mention but I was using this code into a Flutter application and it seems to come from that. See this Github issue for more info.

How to use Pub/sub with hiredis in C++?

I am trying to test this pub/sub function of redis with hiredis client via c++.
I can see that subscribing to certain channel seems to be easy enough to do through redisCommand Api.
However I am wondering how the reply is coming back when somebody publish to the certain server.
Thank you
https://github.com/redis/hiredis/issues/55
aluiken commented on Mar 2, 2012
void onMessage(redisAsyncContext *c, void *reply, void *privdata) {
redisReply *r = reply;
if (reply == NULL) return;
if (r->type == REDIS_REPLY_ARRAY) {
for (int j = 0; j < r->elements; j++) {
printf("%u) %s\n", j, r->element[j]->str);
}
}
}
int main (int argc, char **argv) {
signal(SIGPIPE, SIG_IGN);
struct event_base *base = event_base_new();
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
printf("error: %s\n", c->errstr);
return 1;
}
redisLibeventAttach(c, base);
redisAsyncCommand(c, onMessage, NULL, "SUBSCRIBE testtopic");
event_base_dispatch(base);
return 0;
}
This is a late answer, but you can try redis-plus-plus, which is based on hiredis, and written in C++ 11.
Disclaimer: I'm the author of this library. If you have any problem with this client, feel free to let me know. If you like it, also feel free to star it :)
Sample code:
Redis redis("tcp://127.0.0.1:6379");
// Create a Subscriber.
auto sub = redis.subscriber();
// Set callback functions.
sub.on_message([](std::string channel, std::string msg) {
// Process message of MESSAGE type.
});
sub.on_pmessage([](std::string pattern, std::string channel, std::string msg) {
// Process message of PMESSAGE type.
});
sub.on_meta([](Subscriber::MsgType type, OptionalString channel, long long num) {
// Process message of META type.
});
// Subscribe to channels and patterns.
sub.subscribe("channel1");
sub.subscribe({"channel2", "channel3"});
sub.psubscribe("pattern1*");
// Consume messages in a loop.
while (true) {
try {
sub.consume();
} catch (...) {
// Handle exceptions.
}
}
Check the doc for detail.
Observer pattern is what we see in pub/sub feature of Redis.
All subscribers are observers and subject is the channel which is being modified by publishers.
When a publisher modifies a channel i.e. executes command like redis-cli> publish foo value
This change is communicated by Redis server to all observers (i.e. subscribers)
So Redis server has list of all observers for a particular channel.